文本搜索
在本页面
MONGODB ATLAS搜索
[success] Note视图不支持文本搜索
此示例演示了如何在仅指定文本字段的情况下构建文本索引并使用它来coffee shops。
使用以下文档创建一个集合存储:
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" } )
例如,您可以使用以下查询来查找包含“coffee”、“shop”和“java”列表中任何术语的所有商店:
db.stores.find( { $text: { $search: "java coffee shop" } } )
您还可以通过将短语包装在双引号中来搜索精确的短语。如果**$search**字符串包含一个短语和单个术语,文本搜索将只匹配包含该短语的文档。
例如,以下将查找包 含“coffee shop”的所有文档:
db.stores.find( { $text: { $search: "\"coffee shop\"" } } )
要排除一个单词,可以在前面加上一个“-”字符。例如,要查找所有包含“java”或“shop”但不包含“coffee”的商店,请使用以下方法:
db.stores.find( { $text: { $search: "java shop -coffee" } } )
默认情况下,MongoDB将以无序的顺序返回结果。但是,文本搜索查询将为每个文档计算一个相关性分数,该分数指定文档与查询的匹配程度。
db.stores.find(
{ $text: { $search: "java coffee shop" } },
{ score: { $meta: "textScore" } }
).sort( { score: { $meta: "textScore" } } )
文本搜索也可以在聚合管道中使用。
译者:杨帅
校对:杨帅
最近更新 1yr ago