【问题标题】:Multiple field Indexing in pymongopymongo中的多字段索引
【发布时间】:2015-08-09 10:33:11
【问题描述】:

我正在尝试通过 pymongo 为我的 mongodb 集合应用索引。我正在使用

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"}) 在 mongo shell 中,但我不想索引所有字段。谁能帮帮我?

【问题讨论】:

  • 您想要一个复合索引,还是在所需的文本字段上使用单独的索引?
  • 我想通过python脚本做复合/复合索引

标签: mongodb indexing pymongo


【解决方案1】:
>>> from pymongo import IndexModel, ASCENDING, DESCENDING
>>> index1 = IndexModel([("hello", DESCENDING),
...                      ("world", ASCENDING)], name="hello_world")

pymongo 的文档中提到了这一点

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

这将在 [field_name1,field_name2] 上提供复合索引

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

【讨论】:

  • 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")) 它起作用了!谢谢..
【解决方案2】:

直接来自the doc of createIndex

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

请注意:

dropDups 不受 MongoDB 2.7.5 或更高版本的支持。服务器会静默忽略该选项,如果检测到重复值,则使用该选项构建的唯一索引将失败。

无论如何,这将在field_name1field_name2 上创建一个compound index

最后,请注意使用compound text indexes 时有一些限制。

【讨论】:

  • 我想,你误会了,这里的“唯一”不是一个字段,它是为了复合索引的唯一性。
  • @Nishant 我有多傻...谢谢你的评论!
  • :) 别担心 19K 摇滚
猜你喜欢
  • 2019-05-22
  • 2016-02-06
  • 2016-06-19
  • 2016-12-20
  • 1970-01-01
  • 1970-01-01
  • 2019-04-18
  • 1970-01-01
  • 2010-09-17
相关资源
最近更新 更多