0
votes

A newbie question on elasticsearch-py api. I built an index of records of name, address, phone number etc and I can query using the python client eg.

`elasticsearch.search(index = "index_name", q= 'first_name:"JOHN"')` 

and get the appropriate results However, I want to make the queries as string parameter

first_name = "JOHN"
qu = "first_name:".join(first_name)
elasticsearch.search(index = 'index_name', q = qu)

and the query fails. Is there a better way to make these type of dynamic queries?

2

2 Answers

1
votes

I will typically build out the search query as a request body search. https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-body.html

Example below:

searchdata = essearch.search(index=indexname, body= {
    "query": {
        "filtered": {
          "query": {
            "query_string": {
              "query": "name:fred"
            }
          },
          "filter": {
            "bool": {
              "must": [

                {
                  "exists": {
                    "field": "fieldname"
                  }
                },
                {
                  "exists": {
                    "field": "secondfieldname"
                  }
                }

              ]
            }
          }
        }
      },
      "size": 5000,
      "sort": [
         {
            "loggeddate": {
               "order": "desc"
            }
         }
      ]
    }
           ) 
0
votes

Did you try unpacking a dict like:

mydict={"firstname ":firstname} elasticsearch.search(index = 'index_name ", **mydict)

Or even :

mydict={"index": "index_name ","firstname ":firstname} elasticsearch.search( **mydict)

mydict can have any key - value pair you need

Worth the try