Search code examples
pythonelasticsearchelasticsearch-py

Elasticsearch build dynamic query - python


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?


Solution

  • 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"
                }
             }
          ]
        }
               )