简体   繁体   中英

Pymongo $text search with multiple filter

I am doing a multiple search with Pymongo, I would like to use various keywords to search them but it does not work.

My query here:
(this will show all of the "ABC" and "JKL" results, but I only want to search the results containing both "ABC" and "JKL".

# multiple search (one ADD one , show all one, and two keyword results)
         searchQuery = {
            
         '$text': {
             '$search': "ABC JKL",
            
         }}

I also tried this but it said "too many text expressions"

searchQuery = {
            "$and":[
             {'$text': {'$search': 'ABC'}},
             {'$text': {'$search': 'JKL'}},

        ]}

Solved and find the answer here:
MongoDB Text Search AND multiple search words

Finally, my solution is here

(with Flask example)

# multiple filter
@app.route("/multisearch", methods=["GET"])
def post_multisearch():


    if request.method =="GET":
        # Get parameter from URL (/multisearch?tags=ABC%20JKL)
        # %20 equal space
        getUrlQuery  = request.args.get('tags', type=str ,default='')
        # print(getUrlQuery) # "ABC JKL"

        getUrlArray =getUrlQuery.split(" ")
        # print(getUrlArray) # ["ABC","JKL"]

        keywordArray =[]
        
        # Text search "include" expression \"Keyword\"
        for i in getUrlArray:
            keywordArray.append(f"\"{i}\"")

        #  For loop in search query
        searchQuery = {
             '$text': {'$search': str([ele for ele in keywordArray])},
        }

        searchResults = list(post_collection.find(searchQuery))
        json_data = dumps(searchResults, indent = 4) 
        return json_data

reference here:
MongoDB Text Search AND multiple search words

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