Atlas Search
Overview
在本指南中,您可以学习;了解如何查询Atlas Search索引并在PyMongo应用程序中使用高级全文搜索功能。您可以使用 $search
聚合管道阶段查询搜索索引。
要学习;了解有关 $search
管道阶段的更多信息,请参阅MongoDB Server手册中的 $搜索指南。
注意
仅适用于 Atlas for MongoDB v4.2 及更高版本
$search
聚合管道操作符仅适用于运行 MongoDB 4v.2 或更高版本且被 Atlas Search 索引涵盖的 MongoDB Atlas 集群上托管的集合。要详细了解该操作符所需的设置和功能,请参阅 Atlas Search 文档。
样本数据
本指南中的示例使用Atlas示例数据集中的 sample_mflix.movies
集合。要学习;了解如何创建免费的MongoDB Atlas 群集并加载示例数据集,请参阅 PyMongo入门。
创建 Atlas Search 索引
在对Atlas集合执行搜索之前,必须先在该集合上创建Atlas Search索引。 Atlas Search索引是一种以可搜索格式对数据进行分类的数据结构。要学习;了解如何创建Atlas Search索引,请参阅Atlas Search和 Vector Search 索引。
搜索您的数据
要使用 $search
聚合管道阶段,您必须指定Atlas Search查询运算符来指示要运行的查询类型。您还可以选择指定按值或范围对结果进行分组的收集器。要查看Atlas Search可用的所有操作符和收集器的表格,请参阅在Atlas Search查询中使用操作符和收集器。
以下示例使用 compound
操作符将多个操作符组合成一个查询。要学习;了解有关 compound
操作符的更多信息,请参阅MongoDB Atlas文档中的复合操作符指南。
该查询具有以下搜索条件:
genres
字段不得包含Comedy
。title
字段必须包含字符串New York
。
查询还包括以下阶段:
client = pymongo.MongoClient("<connection-string>") result = client["sample_mflix"]["movies"].aggregate([ { "$search": { "index": "pymongoindex", "compound": { "mustNot": [ { "text": { "query": [ "Comedy" ], "path": "genres" } } ], "must": [ { "text": { "query": [ "New York" ], "path": "title" } } ], } } }, { "$limit": 10 }, { "$project": { "_id": 0, "title": 1, "score": { "$meta": "searchScore" } } } ]) for i in result: print(i)
{'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文档。