Mongoengine 简明教程

MongoDB 支持使用可以对字符串内容执行文本搜索的查询运算符。如前所述,要设置文本索引,请使用 $ 符号作为索引的前缀名。对于文本索引,索引字段的权重表示相对于其他索引字段在文本搜索分数方面的字段的重要程度。你还可以再类的元字典中指定默认语言。

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.

支持的语言列表位于 https://docs.mongodb.com/manual/reference/text-search-languages/ 。MongoEngine API 由 QuerySet 对象的 search_text() 方法组成。在索引字段中要搜索的字符串作为参数给出。

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.

在以下示例中,我们首先定义一个名为 lang 的 Document 类,其中包含两个字符串字段,即语言的名称及其特征。我们还在两个字段上分别创建了具有相应权重的索引。

In the following example, we first define a Document class called lang with two string fields, name of language and its features. We also create indexes on both fields with respective weights.

from mongoengine import *
con=connect('newdb')

class lang (Document):
   name=StringField()
   features=StringField()
   meta = {'indexes': [
      {'fields': ['$name', "$features"],
         'default_language': 'english',
         'weights': {'name': 2, 'features': 10}
      }]
   }

l1=lang()
l1.name='C++'
l1.features='Object oriented language for OS development'
l1.save()
l2=lang()
l2.name='Python'
l2.features='dynamically typed and object oriented for data science, AI and ML'
l2.save()
l3=lang()
l3.name='HTML'
l3.features='scripting language for web page development'
l3.save()

为了对单词“oriented”执行搜索,我们使用 search_text() 方法,如下所示:

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

docs=lang.objects.search_text('oriented')
for doc in docs:
   print (doc.name)

上述代码的输出是其描述中包含单词“oriented”(在本例中为“Python”和“C++”)的语言的名称。

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