Mongodb:如何索引多个嵌套文本字段?

时间:2014-08-15 14:18:58

标签: mongodb search indexing

我的数据库中有以下类型的json:

{ 
    "_id" : "519817e508a16b447c00020e", "keyword" : "Just an example query", 
    "results" : 
    {
        "1" : {"base_domain" : "example1.com", "href" : "http://www.example1.com/"},
        "2" : { "base_domain" : "example2.com", "href" : "http://www.example2.com/"},
        "3" : { "base_domain" : "example3.com", "href" : "http://www.example3.com/"},
        "4" : { "base_domain" : "example4.com", "href" : "http://www.example4.com/"},
        "5" : { "base_domain" : "example5.com", "href" : "http://www.example5.com/"},
        "6" : { "base_domain" : "example6.com", "href" : "http://www.example6.com/"},
        "7" : { "base_domain" : "example7.com", "href" : "http://www.example7.com/"},
        "8" : { "base_domain" : "example8.com", "href" : "http://www.example8.com/"},
        "9" : { "base_domain" : "example9.com", "href" : "http://www.example9.com/"},
        "10" : { "base_domain" : "example10.com", "href" : "http://www.example10.com/"}
    } 
}

我的目标是获得以下查询的结果:

> db.ranking.find({ $text: { $search: "http://www.example9.com"}})

当我在所有文本字段上创建索引时,它可以正常工作

> db.ranking.ensureIndex({ "$**": "text" }))

但是当我仅在"结果"上创建索引时字段:

> db.ranking.ensureIndex( {"results" : "text"} )

为什么?

1 个答案:

答案 0 :(得分:4)

问题在于"结果"不是字段,它是子文档。在MongoDB的文本字段上创建索引的语法要求所有字段的符号," $ * ",您正确使用它们,或者所有文本字段的列表:

  

创建文字索引

     

您可以在值为a的字段上创建文本索引   字符串或字符串元素数组。在上创建文本索引时   多个字段,您可以指定单个字段或您可以使用   通配符说明符($ **)。

http://docs.mongodb.org/manual/tutorial/create-text-index-on-multiple-fields/

在你的情况下看起来像:

db.ranking.ensureIndex(
                           {
                             "keyword": "text",
                             "results.1.href": "text",
                             "results.1.href": "text",
                             "results.2.href": "text",
                             "results.3.href": "text",
                             "results.4.href": "text",
                             "results.5.href": "text",
                             "results.6.href": "text",
                             "results.7.href": "text",
                             "results.8.href": "text",
                             "results.9.href": "text",
                             "results.10.href": "text"
                           }
                       )
相关问题