Reputation: 5084
I have a collection that looks something like this
{ "text1" : "text",
"url" : "http:....",
"title" : "the title",
......,
"search_metadata" : { "tags" : [ "tag1", "tag2", "tag3" ],
"title" : "the title",
"topcis": [ "topic1", "topic2"]
}
}
I want to be able to add a text index to search_metadata
and all it's subdocuments.
ensureIndex({search_metadata:"text"})
Gives me no results
and:
ensureIndex({"$**":"text"})
will give me irrelevant data
How can I make it happen?
Upvotes: 2
Views: 2241
Reputation: 21692
From the text indexes page:
text indexes can include any field whose value is a string or an array of string elements. To perform queries that access the text index, use the $text query operator
Your search_metadata
field is a series of sub-documents, not a string or an array of strings, so it basically is not in the right format to make use of a text index in MongoDB as it is currently structured.
Now, embedded in search_metadata
you have both strings and arrays of strings, so you could use a text index on those, so an index on {search_metadata.tags : "text"}
for example fits the criteria and should work just fine.
Hence, it's a choice between restructuring the field to meet the text index criteria, or a matter of indexing the relevant sub-fields. If you take the latter approach you may find that you don't need text indexes on each of the fields and a simpler (and far smaller) index may serve you just as well (using a normal index on tags and then $elemMatch for example).
Upvotes: 3