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?
>>> 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].create_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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With