Home > Blockchain >  MongoDB PyMongo - create an index and make a case insensitive search in two fields
MongoDB PyMongo - create an index and make a case insensitive search in two fields

Time:11-23

Feels like hitting a brick wall, so help is really appreciated!

I got two fields in the database, both can contain various text. From what I've read up so far, I need to create an index first, but since I got two fields and not one.. How do I search in it? Plus it has to be case insensitive. Using MongoDB 4.4 Pymongo has it's own var for "text", as well as own create_index call, so this is correct?

collection.create_index([('author' , pymongo.TEXT), ('title' , pymongo.TEXT)])

How do I proceed from here and make a case-insensitive search for one search_string?

CodePudding user response:

This solution features case-insensitive, stop-word sensitive lookup on both author and title fields at the same time on the special $text index:

   rc = db.foo.create_index([('author' , pymongo.TEXT), ('title' , pymongo.TEXT)])

    r = [
    {"author":"Buzz","title":"Dangferous iewhf"}
    ,{"author":"Dave","title":"Corn"}
    ,{"author":"Dave","title":"The buzz about wheat"}
    ,{"author":"Chris","title":"Not in this film"}
    ,{"author":"Herbert","title":"Dune"}
    ,{"author":"Herbert","title":"Children of Dune"}
    ]
    db.foo.insert_many(r)


    searchstring = "Dune"                                       
   
    for doc in db.foo.find({"$text": { "$search": searchstring } } ):
        print(doc)

For more details on exact phrases, multiple words, word exclusion, etc. see the docs here: MongoDB $text index features

  • Related