0

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 Answers 2

1

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"
            }
         }
      ]
    }
           ) 
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.