pymongo 中的多字段索引

Multiple field Indexing in 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 但我不想索引所有字段。有人可以帮我吗?

直接来自the doc of createIndex

>>> my_collection.create_index([("field_name1", TEXT),
...                             ("field_name2", TEXT),
                                unique=True,
                                dropDups=1])

注意:

dropDups is not supported by MongoDB 2.7.5 or newer. The option is silently ignored by the server and unique index builds using the option will fail if a duplicate value is detected.

无论如何,这将在 field_name1field_name2 上创建一个 compound index

最后,请注意使用 compound text indexes 时有一些限制。

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

pymongo 的文档中提到了这一点

db[collection_name].create_index([("field_name1" , TEXT),("field_name2", TEXT)],name="index_name"))

这将在 [field_name1,field_name2]

上提供复合索引

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