Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple field Indexing in pymongo

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?

like image 859
Mrunmayee Avatar asked May 27 '15 11:05

Mrunmayee


2 Answers

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

like image 178
Nishant Avatar answered Sep 20 '22 09:09

Nishant


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.

like image 20
Sylvain Leroux Avatar answered Sep 18 '22 09:09

Sylvain Leroux