Search code examples
pythonelasticsearchelasticsearch-8

BadRequestError: BadRequestError(400, 'x_content_parse_exception', '[1:34] [bool] failed to parse field [must]') in Elastic Search (8.9.0)


Following is the semantic search code using elastic search. The code is supposed to return all the records matching the given input:

INPUT = input("Enter the Input Query ")
token_vector = token_instance.get_token(INPUT)

query  ={
  "_source": ["title", "job_description"], 
   "size":50,
   "query":{
      "bool":{
         "must":[
            {
               "knn":{
                  "vector":{
                     "vector":token_vector,
                     "k":20
                  }
               }
            }
         ]
      }
   }
}


res = es.search(index='posting1',
                body=query,
                request_timeout=55)

title = [x['_source']  for x in res['hits']['hits']] 
title

Error: BadRequestError: BadRequestError(400, 'x_content_parse_exception', '[1:34] [bool] failed to parse field [must]')

How to fix this error? I'm using Elasticsearch 8.9.0. I tried the existing solutions to this error, but they don't work.


Solution

  • There is no body parameter in the search() function, you need to call it like this:

    query  ={
       "bool":{
          "must":[
             {
                "knn":{
                   "vector":{
                      "vector":token_vector,
                      "k":20
                   }
                }
             }
          ]
       }
    }
    res = es.search(index='posting1',
                    size=50,
                    source=["title", "job_description"],
                    query=query,
                    request_timeout=55)