create_index using pymongo

19 views
Skip to first unread message

DK

unread,
Sep 26, 2018, 6:48:20 PM9/26/18
to mongodb-user
I need to restore MongoDB which was sharded on dev env.
Before starting restore I need to build build indexes and enable sharding on collection so that when DB is restored collections get sharded.
To accomplish that I need to build  index on collection dynamically  

How to build  index using LIST which will be passed as first para to pymongo create_index(key_or_list, deprecated_unique=None, ttl=300, **kwargs)  

I have following JSON file in which index info is stored.

{"_id": "client_415.reviews", "key": {"year": 1.0, "state": 1.0}, "unique": false}

client = MongoClient(URI,port)
client.admin.command('enableSharding', dbname)
db = client[dbname]
col =db[CollectionName]  ## Collection Name will be "reviews"
json_data = f.read()
loaded_json = json.loads(json_data)

col.create_index(LISTName)
#  it should form something like  create_index([('year',1),('state',1) ], unique = false)
Now how should I build LIST to pass to create_index  ??


Thanks for looking into it.

DK

Bernie Hackett

unread,
Sep 27, 2018, 7:36:33 PM9/27/18
to mongodb-user
The reason create_index requires a list is that Python dictionaries (previous to CPython 3.6) don't preserve order. The order of fields in an index key is critical. You can get the list you need using collections.OrderedDict and the object_pairs_hook parameter to json.loads:

from json import loads

from collections import OrderedDict

list(loads('{"_id": "client_415.reviews", "key": {"year": 1.0, "state": 1.0}, "unique": false}', object_pairs_hook=OrderedDict)['key'].items())


Reply all
Reply to author
Forward
0 new messages