mongodb带有多个字段的文本搜索 [英] mongodb text search with multiple fields
问题描述
我正在尝试使用多个字段工作的mongodb全文搜索. 我已经在3个字段(名称,说明,类别)上设置了索引,并使用
I'm trying to get mongodb fulltext search with multiple fields working. I've set the index on 3 fields-name,description, category, and verified with
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
}
]
现在,如果我尝试使用以下命令执行文本搜索-
Now, if I try to perform a text search, using the follwing command-
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文档,但找不到任何东西.
I tried google and mongodb docs but I couldn't find anything.
推荐答案
您应创建文本索引在您要搜索的字段上:
You should create a text index on the fields you want to search:
db.deals.ensureIndex({ name: "text", description : "text", category : "text" });
从 $ text 运算符的文档中:
$ text对用索引的字段的内容执行文本搜索 文本索引.
$text performs a text search on the content of the fields indexed with a text index.
为三个字段创建的索引是复合索引,而不是文本索引.文本索引将如下所示:
The index you created for your three fields is a compound index, not a text index. The text index will look like this:
{
"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
}
这篇关于mongodb带有多个字段的文本搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!