pymongo 中的多字段索引

Mru*_*yee 6 indexing mongodb pymongo

我正在尝试通过 pymongo 为我的 mongodb 集合应用索引。我在用

db[collection_name].ensure_index([("field_name" , "text"),("unique", 1), ("dropDups" , 1)])

它有效。但是现在如何将其应用于多个领域?像这样的东西

db[collection_name].ensure_index([("field_name1" , "text"),("field_name2", "text"),("field_name3", "text"),("unique", 1), ("dropDups" , 1)])

我知道我们可以db.collection.ensureIndex({"$**":"text"},{"name":"TextIndex"}) 在 mongo shell 中使用,但我不想索引所有字段。有人可以帮我吗?

Nis*_*ant 5

>>> from pymongo import IndexModel, ASCENDING, DESCENDING
>>> index1 = IndexModel([("hello", DESCENDING),
...                      ("world", ASCENDING)], name="hello_world")
Run Code Online (Sandbox Code Playgroud)

pymongo 的文档中提到了这一点

db[collection_name].create_index([("field_name1" , TEXT),("field_name2", TEXT)],name="index_name"))
Run Code Online (Sandbox Code Playgroud)

这将提供 [field_name1,field_name2] 上的复合索引

http://api.mongodb.org/python/current/api/pymongo/collection.html#pymongo.collection.Collection.create_indexes