Evo_x Evo_x - 1 month ago 7
PHP Question

Elasticsearch - query string or simply query string and how

I have a list of cities as array in PHP, let's say ["Munich", "New York", Chicago"].

I want to produce a query in elastic search which basically says

"SELECT * FROM job_ads WHERE city = Munich OR city = New York OR city = Chicago"


What is the best way to do this?

So far https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-simple-query-string-query.html seems the best for this job. But if it is, I could need some help with the syntax, I'm very new to elasticsearch.

Answer

A simple way would be to use query string query like this.

{
  "query": {
    "query_string": {
      "fields": ["city"],
      "query": "Munich OR \"New York\" OR Chicago"
    }
  }
}

You would have to use \" for exact phrase match or else you would get results which contains any of those two words.

Now if you are in control of the data, best way to write this kind of query would be to use terms filter which can also be cached but you would have to make sure that city field is not analyzed. You can read more about implications of analyzed and not analyzed fields here(scroll down to Why doesn’t the term query match my document?)

After that you could use terms query like this

{
  "query": {
    "terms": {
      "city": [
        "New York",
        "Chicago",
        "Munich"
      ]
    }
  }
}