MongoDB提供文本索引来支持对字符串内容的文本搜索查询。文本索引可以包括任何值为字符串或字符串元素数组的字段。
要执行文本搜索查询,必须在集合上具有文本索引。一个集合只能有一个文本搜索索引,但是该索引可以覆盖多个字段。
db.stores.insert(
[
{ _id: 1, name: "Java Hut", description: "Coffee and cakes" },
{ _id: 2, name: "Burger Buns", description: "Gourmet hamburgers" },
{ _id: 3, name: "Coffee Shop", description: "Just coffee" },
{ _id: 4, name: "Clothes Clothes Clothes", description: "Discount clothing" },
{ _id: 5, name: "Java Shopping", description: "Indonesian goods" }
]
)
> db.stores.createIndex( { name: "text", description: "text" } )
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
>
你也可以用双引号来搜索准确的短语。如果$search字符串包含短语和单个术语,文本搜索将只匹配包含短语的文档。
For example, the following will find all documents containing “coffee shop”:
> db.stores.find( { $text: { $search: "\"coffee shop\"" } } )
{ "_id" : 3, "name" : "Coffee Shop", "description" : "Just coffee" }
>
要排除一个单词,可以在前面加一个“-”字符。例如,要查找所有包含“java”或“shop”但不包含“coffee”的商店,请使用以下命令:
> db.stores.find( { $text: { $search: "java shop -coffee" } } )
{ "_id" : 5, "name" : "Java Shopping", "description" : "Indonesian goods" }
>
默认情况下,MongoDB将以未排序的顺序返回结果。但是,文本搜索查询将为每个文档计算一个相关性评分,该评分指定文档与查询的匹配程度。
> db.stores.find(
... { $text: { $search: "java coffee shop" } },
... { score: { $meta: "textScore" } }
... ).sort( { score: { $meta: "textScore" } } )
{ "_id" : 3, "name" : "Coffee Shop", "description" : "Just coffee", "score" : 2.25 }
{ "_id" : 1, "name" : "Java Hut", "description" : "Coffee and cakes", "score" : 1.5 }
{ "_id" : 5, "name" : "Java Shopping", "description" : "Indonesian goods", "score" : 1.5 }
>
文本操作符
使用$text查询操作符对具有文本索引的集合执行文本搜索。
$text将使用空格和大多数标点符号作为分隔符标记搜索字符串,并在搜索字符串中执行逻辑标记或所有此类标记。
扫描二维码关注公众号,回复:
5373779 查看本文章
例如,您可以使用以下查询来查找列表“coffee”、“shop”和“java”中包含任何术语的所有商店:
> db.stores.find( { $text: { $search: "java coffee shop" } } )
{ "_id" : 3, "name" : "Coffee Shop", "description" : "Just coffee" }
{ "_id" : 1, "name" : "Java Hut", "description" : "Coffee and cakes" }
{ "_id" : 5, "name" : "Java Shopping", "description" : "Indonesian goods" }
>