【问题标题】:How to nested query in mongodb?如何在mongodb中嵌套查询?
【发布时间】:2020-04-06 20:19:02
【问题描述】:

如何在 Pymongo 中索引嵌套对象,以便我可以执行全文搜索。例如我有这样的集合对象......

{
   "_id":"ObjectId("   "5e8b0fa1c869790699efdb2d"   ")",
   "xmlfileid": "334355343343223567",
   "threads":{
      "threads_participants":{
         "participant":[
            {
               "@reference": rits_dbx_1
            },
            {
               "@reference": rits_dbx_2
            }
         ]
      },
      "thread":{
         "namedAnchor":"{' ': 'NORP', 'Ho': 'PERSON', 'Lets': 'PERSON', 'Boris Johnson': 'PERSON', 'Britain': 'GPE'}",
         "selectedText":{
            "fragment":[
               {
                  "@class":"next_steps",
                  "#text":"rits_dbx_1 said hello this is a good site."
               },
               {
                  "@class":"other",
                  "#text":"rits_dbx_1 said ho ho."
               },
               {
                  "@class":"other",
                  "#text":"rits_dbx_1 said lets put some meaningful stuff here."
               },
            ]
         }
      }
   }
}

我在我的网站中放置了搜索框,当用户在搜索框中键入 #text 时,我想显示 #textclass 以及 xmlfileid

到目前为止,我已经使用以下命令创建了索引。而且我不知道这是获得结果的正确方法,也请帮助查询。

db.xml_collection.createIndex({"threads.thread.selectedText.fragment": "text"})

在我的 python 代码中,我有这个,但什么也没打印

result = collection.find({"$text": {"$search": "ho ho"}})

【问题讨论】:

    标签: mongodb pymongo


    【解决方案1】:

    你的索引是错误的。

    MongoDB 提供text 索引来支持对字符串内容的文本搜索查询。 文本索引可以包含任何值为字符串或字符串元素数组的字段。

    https://docs.mongodb.com/manual/core/index-text/

    如果您只想索引#text 字段,请将您的索引更改为:

    db.xml_collection.createIndex({"threads.thread.selectedText.fragment.#text": "text"})
    

    另外,您可以创建Wildcard text index,MongoDB 将索引所有key:value 对(其中value 是字符串/字符串数组)

    db.xml_collection.createIndex({"$**": "text"})
    

    注意:您需要删除此集合之前的所有 text 索引

    【讨论】:

    • 感谢它的工作。我将使用通配符,因为我们的要求略有变化。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-04
    • 2021-07-03
    • 1970-01-01
    • 2015-11-19
    • 1970-01-01
    • 2018-03-09
    • 2021-01-31
    相关资源
    最近更新 更多