问题
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