MongoEngine – Text search

MongoDB supports use of query operators that can perform text search on a string content. As described earlier, to set a text index prefix name of index with $ symbol. For a text index, the weight of an indexed field denotes the significance of the field relative to the other indexed fields in terms of the text search score. You can also specify default language in meta dictionary of the class.
List of supported languages can be found at
https://docs.mongodb.com/manual/reference/text-search-languages/
MongoEngine API consists of search_text() method for QuerySet object. The string to be searched in indexed fields is given as argument.
In the following example, we first define a Document class called Books with two string fields, name of book and its features. We also create indexes on both fields with respective weights.

from mongoengine import connect
from mongoengine import StringField, IntField, Document, DecimalField, ListField
connect('mydata', host='mongodb://localhost/mydata')
class Books(Document):
book_id = IntField(unique=True, required=True)
book_name = StringField(max_length=50)
book_price = DecimalField()
book_features = StringField()
meta = {'indexes': [
{'fields': ['$book_name', "$book_features"],
'default_language': 'english',
'weights': {'book_name': 2, 'book_features': 10}
}]
}
b1 = Books(book_id="1014", book_name="C++", book_price=2599,
book_features='Object oriented language for OS development').save()
b2 = Books(book_id="1015", book_name="Python", book_price=3579,
book_features='dynamically typed and object oriented for data science, AI and ML').save()
b3 = Books(book_id="1016", book_name="JavaScript", book_price=2599,
book_features='Client side scripting language used to power the web developement').save()

In order to perform search for word ‘oriented’, we employ search_text() method as follows −

from mongoengine import connect
from mongoengine import StringField, IntField, Document, DecimalField, ListField
connect('mydata', host='mongodb://localhost/mydata')
class Books(Document):
book_id = IntField(unique=True, required=True)
book_name = StringField(max_length=50)
book_price = DecimalField()
book_features = StringField()
meta = {'indexes': [
{'fields': ['$book_name', "$book_features"],
'default_language': 'english',
'weights': {'book_name': 2, 'book_features': 10}
}]
}
docs = Books.objects.search_text('oriented')
for doc in docs:
print(doc.book_name)

Output of the above code will be names of languages in whose description the word ‘oriented’ occurs (‘Python and ‘C++’ in this case).

MongoEngine – Signals (Prev Lesson)