2015-05-27 40 views
2

我試圖通過pymongo爲我的mongodb集合應用索引。我使用pymongo中的多字段索引

db[collection_name].ensure_index([("field_name" , "text"),("unique", 1), ("dropDups" , 1)])

和它的作品。但是現在如何將它應用於多個領域呢? 像這樣

db[collection_name].ensure_index([("field_name1" , "text"),("field_name2", "text"),("field_name3", "text"),("unique", 1), ("dropDups" , 1)])

我知道我們可以在蒙戈外殼db.collection.ensureIndex({"$**":"text"},{"name":"TextIndex"}) ,但我不想給指數的所有領域。有人可以幫我嗎?從the doc of createIndex

+1

要一個綜合指數,或單獨索引所需的文本字段? – Nishant

+0

我想通過python腳本做複合/複合索引 – Mrunmayee

回答

1
>>> from pymongo import IndexModel, ASCENDING, DESCENDING 
>>> index1 = IndexModel([("hello", DESCENDING), 
...      ("world", ASCENDING)], name="hello_world") 

這在doc提到用於pymongo

db[collection_name].ensure_index([("field_name1" , TEXT),("field_name2", TEXT)],name="index_name")) 

這將提供一個綜合指數[欄位1,欄位2]

http://api.mongodb.org/python/current/api/pymongo/collection.html#pymongo.collection.Collection.create_indexes

+0

db [collection_name] .ensure_index([(「field_name1」,TEXT),(「field_name2」,TEXT),(「field_name3」,TEXT)],(「unique」,1),( 「dropDups」,1))當它使用它給我TypeError:ensure_index()最多3個參數(給定4)。但是當我使用db [collection_name] .ensure_index([(「field_name1」,TEXT),(「field_name2」,TEXT)],name =「index_name」))它工作!謝謝.. – Mrunmayee

+0

更改了答案,根據您的建議,接受它,如果它幫助... – Nishant

2

直:

>>> my_collection.create_index([("field_name1", TEXT), 
...        ("field_name2", TEXT), 
           unique=True, 
           dropDups=1]) 

要注意的是:

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.

無論如何,這將創建field_name1field_name2一個compound index

最後請注意,使用compound text indexes時有一些限制。

+0

我想,你把它弄錯了,「獨一無二」這裏不是一個字段,它對於複合索引的唯一性。 – Nishant

+0

@Nishant我多麼傻...謝謝你的評論! –

+0

:)不用擔心19K rock – Nishant