Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

mongodb text search with multiple fields

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 (), which returns-

[
    {
        "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)

got the following error message:

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

I tried google and mongodb docs but I couldn't find anything.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should create a text index on the fields you want to search:

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

From the documentation of the $text operator:

$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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...