简体   繁体   中英

PyMongo Atlas Search not returning anything

I'm trying to do a full text search using Atlas for MongoDB. I'm doing this through the PyMongo driver in Python. I'm using the aggregate pipeline, and doing a $search but it seems to return nothing.

cursor = db.collection.aggregate([
    {"$search": {"text": {"query": "hello", "path": "text_here"}}},
    {"$project": {"file_name": 1}}
])

for x in cursor:
    print(x)

What I'm trying to achieve with this code is to search through a field in the collection called "text_here", and I'm searching for a term "hello" and returning all the results that contain that term and listing them by their "file_name". However, it returns nothing and I'm quite confused as this is almost identical to the example code on the documentation website. The only thing I could think of right now is that possible the path isn't correct and it can't access the field I've specified. Also, this code returns no errors, simply just returns nothing as I've tested by looping through cursor.

I had the same issue. I solved it by also passing the name of the index in the query. For example:

{ 
  index: "name_of_the_index",
  text: {
    query: 'john doe',
    path: 'name'
  }
}

I followed the tutorials but couldn't get any result back without specifying the "index" name. I wish this was mentioned in the documentation as mandatory.

If you are only doing a find and project, you don't need an aggregate query, just a find() . The syntax you want is:

db.collection.find({'$text': {'$search': 'hello'}}, {'file_name': 1})

Equivalent using aggregate:

cursor = db.collection.aggregate([
    {'$match': {'$text': {'$search': 'hello'}}},
    {'$project': {'file_name': 1}}])

Worked example:

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)

prints:

{'_id': ObjectId('5fc81ce9a4a46710459de610'), 'file_name': 'foo.bar'}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM