Atlas Search
Overview
在本指南中,您将学习如何在 PyMongo 应用程序中查询 Atlas Search 索引并使用高级全文搜索功能。您可以使用 $search
聚合管道阶段查询搜索索引。
要了解有关 $search
管道阶段的更多信息,请参阅 MongoDB Server 手册中的 $search 指南。
注意
仅适用于 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 和向量搜索索引。
搜索您的数据
要使用 $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 文档。