[英]PyMongo Atlas Search not returning anything
我正在尝试使用 Atlas 对 MongoDB 进行全文搜索。我正在通过 Python 中的 PyMongo 驱动程序执行此操作。我正在使用聚合管道,并执行 $search 但它似乎没有返回任何内容。
cursor = db.collection.aggregate([
{"$search": {"text": {"query": "hello", "path": "text_here"}}},
{"$project": {"file_name": 1}}
])
for x in cursor:
print(x)
我试图用这段代码实现的是搜索集合中名为“text_here”的字段,我正在搜索术语“hello”并返回包含该术语的所有结果并按“文件名”。 但是,它什么也不返回,我很困惑,因为这与文档网站上的示例代码几乎相同。 我现在唯一能想到的是可能路径不正确,它无法访问我指定的字段。 此外,此代码不返回任何错误,只是不返回任何内容,正如我通过循环 cursor 测试的那样。
我遇到过同样的问题。 我通过在查询中传递索引名称来解决它。 例如:
{
index: "name_of_the_index",
text: {
query: 'john doe',
path: 'name'
}
}
我按照教程进行操作,但在不指定“索引”名称的情况下无法获得任何结果。 我希望在文档中提到这是强制性的。
如果你只是在做一个查找和项目,你不需要聚合查询,只需要一个find()
。 你想要的语法是:
db.collection.find({'$text': {'$search': 'hello'}}, {'file_name': 1})
等价于使用聚合:
cursor = db.collection.aggregate([
{'$match': {'$text': {'$search': 'hello'}}},
{'$project': {'file_name': 1}}])
工作示例:
from pymongo import MongoClient, TEXT
db = MongoClient()['mydatabase']
db.collection.create_index([('text_here', TEXT)])
db.collection.insert_one({"text_here": "hello, is it me you're looking for", "file_name": "foo.bar"})
cursor = db.collection.find({'$text': {'$search': 'hello'}}, {'file_name': 1})
for item in cursor:
print(item)
印刷:
{'_id': ObjectId('5fc81ce9a4a46710459de610'), 'file_name': 'foo.bar'}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.