Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongodb text search with multiple fields

Tags:

mongodb

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\nTree: TEXT : query=alias, language=, tag=NULL\nSort: {}\nProj: {}\n 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.

like image 516
Mukesh Soni Avatar asked Jun 17 '14 06:06

Mukesh Soni


1 Answers

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
}
like image 120
Christian P Avatar answered Sep 30 '22 17:09

Christian P