Error using text index on Mongodb

I am trying to play with text index on Mongodb.

I already used a text index in one collection:

db.ensureIndex({field1 : "text"}) 

and it works.

But I repeated another collection, and I received the following message:

 db.movies.ensureIndex({genres: "text"}) { "createdCollectionAutomatically" : false, "numIndexesBefore" : 1, "ok" : 0, "errmsg" : "found language override field in document with non-string type", "code" : 17261 } 

In the collection "films" there is a field of "genres", which is an array of strings. For instance:

 > db.movies.findOne() { "_id" : ObjectId("51c460fdc30a209dd9621dc4"), "genres" : [ "Crime", "Drama" ] ... } 

This field is present in all documents.

I do not understand this error. Any ideas?

+5
source share
2 answers

This error occurs when you try to create a text index in a field in a document, and the document has a field named language , which is of type not string .

From docs :

If the collection contains documents or subdocuments that are in different languages, include a field with the name of the language in the documents or subdocuments and specify as the value the language for this document or subdocument.

MongoDB will use the specified language for this document or sub-page when creating a text index

By default, the language on which text indexes are built is English . If a field named language present in the document area, MongoDb assumes that this is a field that defines the language that will be used to create indexes for this document.

So, in order to fool MongoDB in such cases when you use text index and have a field named language , which is part of the document, and not a field for indicating the language for building indexes, you need to set the language_override attribute for some dummy field that does not exist. This is to tell MongoDb that, look, you should use English as the default language, and if my document contains a field called dummy , then use the value in this field as the language to create the index for this document and not the language field.

 db.movies.ensureIndex( { generes: "text" }, { language_override: "dummy" } ) 
+12
source

Your movie collection contains a "language" field with a type not accepted by mongo DB. Make sure that the “language” is not an empty string, contains only these values ​​(see Text Search Languages ):

 da or danish nl or dutch en or english fi or finnish fr or french de or german hu or hungarian it or italian nb or norwegian pt or portuguese ro or romanian ru or russian es or spanish sv or swedish tr or turkish 
+1
source

Source: https://habr.com/ru/post/1207855/


All Articles