具有多个字段的mongodb文本搜索

时间:2014-06-17 06:52:03

标签: mongodb

我正在尝试使用多个字段进行mongodb全文搜索。 我已经在3个字段 - 名称,描述,类别上设置了索引,并使用

进行了验证

document.collection.getIndexes (), 返回 -

[
    {
        "v" : 1,
        "key" : {
            "_id" : 1
        },
        "name" : "_id_",
        "ns" : "document.collection"
    },
    {
        "v" : 1,
        "key" : {
            "name" : 2,
            "description" : 1,
            "category" : 1
        },
        "name" : "name_2_description_1_category_1",
        "ns" : "document.collection",
        "background" : true,
        "safe" : null
    }
]

现在,如果我尝试使用以下命令执行文本搜索 -

db.collection.find(  {$text:{$search:'alias'}}  ).limit(10)

收到以下错误消息:

error: {
    "$err" : "Unable to execute query: error processing query: ns=document.collection limit=10 skip=0\nTree: TEXT : query=alias, language=, tag=NULL\nSort: {}\nProj: {}\n planner returned error: need exactly one text index for $text query",
    "code" : 17007
}

我试过谷歌和mongodb文档,但我找不到任何东西。

2 个答案:

答案 0 :(得分:16)

您应该在要搜索的字段上创建text index

db.deals.ensureIndex({ name: "text", description : "text", category : "text" });

来自$text运营商的文档:

  

$ text对索引的字段的内容执行文本搜索   文本索引。

您为三个字段创建的索引是复合索引,而不是文本索引。文本索引如下所示:

{
    "v" : 1,
    "key" : {
        "_fts" : "text",
        "_ftsx" : 1
    },
    "name" : "name_text_description_text_category_text",
    "ns" : "test.deals",
    "weights" : {
        "category" : 1,
        "description" : 1,
        "name" : 1
    },
    "default_language" : "english",
    "language_override" : "language",
    "textIndexVersion" : 2
}

答案 1 :(得分:0)

使用上面的示例

Obj3

这是否意味着我正在创建一个索引或3,还可以仅搜索名称或描述,还是必须始终列出所有3个?

此外,如果我想为电话号码添加另一个索引怎么办?