0
{
   "query":
   {
      "query_string" :
      {
         "query" : "((name:the_search_phrase) OR (keywords:the_search_phrase)) AND (city:Sydney, Australia)"
      }
   }
}

New to elasticsearch. Building the JSON as per the documentation here: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-query-string-query.html

The query runs, however, results with city other that Sydney, Australia are returned too. Why the AND part is not working?

I want the search phrase to match against either or both name, keywords but the city should be strictly Sydney.

Mr Cathode
  • 73
  • 14

1 Answers1

0

What you are doing is a full text query. city:Sydney, Australia seems to be a filter query. Like a WHERE clause in a SQL. You are better off using a filter query for that.

Look at the boolean query for examples,

Something like this perhaps,

    {
  "query": {
    "bool": {
      "must": [
        {
          "query_string": {
            "query": "the_search_term",
            "fields": [
              "name",
              "keywords"
            ]
          }
        }
      ],
      "filter": [
        {
          "match": {
            "city": "Sydney, Australia"
          }
        }
      ]
    }
  }
}
aswath86
  • 551
  • 5
  • 14
  • `{ "query": { "bool" : { "should": [ {"match" : {"name" : "The search Phrase"}}, {"match" : {"keywords" : "The search Phrase"}} ], "filter" : { "term" : { "city" : "Melbourne, Australia" } } } } }` I rewrote as this, but no results for whatever **search phrase** and **city**. – Mr Cathode Feb 17 '20 at 10:46
  • Any mistake in my understanding? – Mr Cathode Feb 17 '20 at 10:47
  • Updated with an example. – aswath86 Feb 17 '20 at 11:45
  • Thanks for the example. But, this also gets results with city other than Sydney, Australia. – Mr Cathode Feb 17 '20 at 12:26
  • What do you see when you try `http://your-ES-host:es-port/you-index/_search?q=city:"Sydney, Australia"` Do you see records from other cities as well? Does your "city" field have multiple values in them for same records, like an array? – aswath86 Feb 17 '20 at 13:09
  • Melbourne, Australia is also returned. But when I filter with other parameters, where it does not have common phrases among it, the results are fine. Example: `type:website`, `type:app` filter results fine. Please note filter for `Chennai, India` also shows other cities from India, but not from Australia. I think, instead of exact match ES is matching phrases. I tried replacing `match` with `term`, but no results are returned for whatever city entered. – Mr Cathode Feb 17 '20 at 13:30
  • What does the result of this query look like? Does it show Sydney and Australia in different buckets? `GET /your-index/_search?size=0 { "aggs" : { "city" : { "terms" : { "field" : "city" } } } }` – aswath86 Feb 17 '20 at 14:11