【问题标题】:mongodb text search with multiple fields具有多个字段的mongodb文本搜索
【发布时间】:2014-06-17 06:52:03
【问题描述】:

我正在尝试使用多个字段进行 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
}

我尝试了 google 和 mongodb 文档,但找不到任何东西。

【问题讨论】:

  • 那不是文本索引。该名称将在每个字段名称和其他指示符之后带有“文本”。

标签: mongodb


【解决方案1】:

您应该在要搜索的字段上创建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
}

【讨论】:

  • 我已经有:db.deals.ensureIndex({name:"text"},{description:"text"},{category:"text"})
  • 谢谢@Christian,你能告诉我如何确保猫鼬中的索引吗?我已经使用这一行来创建索引:Schema.index({name:2,description:1,category:1});
  • @MukeshSoni 你可能应该在一个单独的问题中问这个问题。这样它就可以帮助其他人。
  • 由于没有再次提问,您可以通过var model = mongoose.model('ModelName', Schema); model.collection.ensureIndex({name: 'text', description: 'text', category: 'text'}, function(error) {});确保自己索引
  • 那么如何在索引字段上进行搜索呢?即查找具有 name="a" 和 description="b" 等的文档。
猜你喜欢
  • 1970-01-01
  • 2016-10-16
  • 2020-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多