perdurabo93
perdurabo93

Reputation: 473

With PyMongo how do I import indexes using create_index() that were exported with index_information()?

What do you need to do to the output of index_information() such that it can then be re-imported using create_index() or create_indexes() ?

>>> from pymongo import MongoClient
>>> client = MongoClient("mongodb://host1")
>>> db = client.MYDB
>>> collection = db.MYCOLLECTION
>>> index = db.provisioning.index_information()
>>> index
{u'_id_': {u'ns': u'MYDB.MYCOLLECTION', u'key': [(u'_id', 1)], u'v': 1}, u'Name_1': {u'unique': True, u'key': [(u'Name', 1)], u'v': 1, u'ns': u'MYDB.MYCOLLECTION', u'background': False}, u'MongoType_1': {u'key': [(u'MongoType', 1)], u'ns': u'MYDB.MYCOLLECTION', u'background': False, u'v': 1}}
>>> client2 = MongoClient("mongodb://host2")
>>> db2 = client2.MYDB
>>> collection2 = db2.MYCOLLECTION
>>> collection2.create_index(index)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python2.6/site-packages/pymongo/collection.py", line 1161, in create_index
    keys = helpers._index_list(keys)
  File "/usr/lib64/python2.6/site-packages/pymongo/helpers.py", line 55, in _index_list
    raise TypeError("if no direction is specified, "
TypeError: if no direction is specified, key_or_list must be an instance of list
>>> collection2.create_indexes(index)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python2.6/site-packages/pymongo/collection.py", line 1046, in create_indexes
    raise TypeError("indexes must be a list")
TypeError: indexes must be a list

Upvotes: 1

Views: 566

Answers (1)

Abhijeet Kasurde
Abhijeet Kasurde

Reputation: 4127

Try this basic code, this will iterate and add all index from one collection to other collection,

from pymongo import MongoClient

client = MongoClient("mongodb://host1")
db = client.MYDB
collection = db.MYCOLLECTION
index = db.provisioning.index_information()

client2 = MongoClient("mongodb://host2")
db2 = client2.MYDB
collection2 = db2.MYCOLLECTION
for i in index.keys():
    name_index = index[i]['key'][0][0]
    order = index[i]['key'][0][1]
    collection2.create_index([(name_index, order)])

Upvotes: 1

Related Questions