Overview
在本指南中,您可以学习;了解如何查询Atlas Search索引,以及如何在Ruby驾驶员应用程序中使用高级全文搜索功能。您可以使用 $search
聚合管道阶段查询搜索索引。
要了解有关 $search
管道阶段的更多信息,请参阅 MongoDB Server 手册中的 $search 指南。
注意
仅适用于 Atlas for MongoDB v4.2 及更高版本
$search
聚合管道操作符仅适用于运行 MongoDB 4v.2 或更高版本且被 Atlas Search 索引涵盖的 MongoDB Atlas 集群上托管的集合。要详细了解该操作符所需的设置和功能,请参阅 Atlas Search 文档。
样本数据
sample_mflix.movies
本指南中的示例使用Atlas示例数据集中的 集合。要学习;了解如何创建免费的MongoDB Atlas 群集并加载示例数据集,请参阅 Ruby驱动程序入门。
创建 Atlas Search 索引
在对Atlas集合执行搜索之前,必须先在该集合上创建Atlas Search索引。 Atlas Search索引是一种以可搜索格式对数据进行分类的数据结构。要学习;了解如何创建Atlas Search索引,请参阅Atlas Search和Atlas Vector Search索引指南。
搜索您的数据
要使用$search
聚合管道阶段,您必须指定Atlas Search查询运算符来指示要运行的查询类型。您可以选择使用收集器来指定查询输出的值和范围。要查看Atlas Search可用的所有操作符和收集器的表格,请参阅Atlas文档中的操作符和收集器页面。
以下示例使用compound
操作符将多个操作符组合成一个查询。要学习;了解更多信息,请参阅Atlas文档中的复合操作指南。
该查询具有以下搜索条件:
genres
字段不得包含Comedy
。title
字段必须包含字符串New York
。
查询还包括以下阶段:
pipeline = [ { "$search" => { "index" => "index_name", "compound" => { "mustNot" => [ { "text" => { "query" => ["Comedy"], "path" => "genres" } } ], "must" => [ { "text" => { "query" => ["New York"], "path" => "title" } } ] } } }, { "$limit" => 10 }, { "$project" => { "_id" => 0, "title" => 1, "score" => { "$meta" => "searchScore" } } } ] result = collection.aggregate(pipeline) puts result.to_a
{'title': 'New York, New York', 'score': 6.786379814147949} {'title': 'New York', 'score': 6.258603096008301} {'title': 'New York Doll', 'score': 5.381444931030273} {'title': 'Escape from New York', 'score': 4.719935417175293} {'title': 'Autumn in New York', 'score': 4.719935417175293} {'title': 'Sleepless in New York', 'score': 4.719935417175293} {'title': 'Gangs of New York', 'score': 4.719935417175293} {'title': 'Sherlock Holmes in New York', 'score': 4.203253746032715} {'title': 'New York: A Documentary Film', 'score': 4.203253746032715} {'title': 'An Englishman in New York', 'score': 4.203253746032715}
更多信息
要学习有关可用的 Atlas Search 操作符的更多信息,请参阅 MongoDB Atlas 文档中的操作符和收集器指南。
如需了解有关 Atlas Search 的更多信息,并查看更多查询示例,请参阅 Atlas Search 文档。
如果您想对存储在 Atlas 中的数据执行向量搜索,您必须使用 Atlas Vector Search。如要了解有关 Atlas Vector Search 的更多信息,请参阅 Atlas Vector Search 文档。