Multiple field Indexing in pymongo

隐身守侯 提交于 2019-12-10 16:03:22

问题


I am trying to apply indexing for my mongodb collection through pymongo. I am using

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

and it works. But now how can apply it for multiple fields? Something like this

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

I know we can use db.collection.ensureIndex({"$**":"text"},{"name":"TextIndex"}) in mongo shell but I dont want to Index all the fields. Can anybody help me out?


回答1:


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

This was mentioned in the doc for pymongo

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

This will provide a composite index on [field_name1,field_name2]

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




回答2:


Straight from the doc of createIndex:

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

Beware that:

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.

Anyway, this will create a compound index on field_name1 and field_name2.

Finally, please notice there are some limitation when using compound text indexes though.



来源:https://stackoverflow.com/questions/30480781/multiple-field-indexing-in-pymongo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!