Angels
Angels

Reputation: 345

Combine query_string and match together in Elasticsearch

I am trying to search a index in elastic search with the following body:

{
    "query": {
        "bool": {
            "must": [
                {
                    "query_string": {
                        "query": "a*",
                        "default_operator": "AND"
                },
                {
                    "match": {
                        "country": "Spain"
                    }
                },
                {
                    "match": {
                        "city": "Madrid"
                    }
                }
            ]
        }
    }
}

here is my indexed results:

 [
  {
    _id: "T__cU34BAF3zuzOUa7rD"
    _index: "es"
    _score: 1
    _source: {
      name: "Santiago",
      country: "Spain",
      city: "Madrid",
    }
    _type: "_doc"
  },
  ...
]

So this supposed to search for a word found in field city inside the country.

country and city are optional by the way and it should return all queries that start with a if city and country are empty.

Upvotes: 0

Views: 1146

Answers (1)

Bhavya
Bhavya

Reputation: 16172

According to your problem, you want to return documents that have values that start with supposing s. And, along with this, the country and city conditions are optional.

You can combine query string and match query using the boolean query. Here must clause, works as a logical AND operator, and the should clause works as a logical OR operator.

Adding a working example with index data, search query and search result

Index Data:

PUT <index-name>/_doc/1
{
  "name": "Santiago",
  "country": "Spain",
  "city": "Madrid"
}

PUT <index-name>/_doc/2
{
  "name": "San Franciscor",
  "country": "",
  "city": "Madrid"
}

Search Query:

POST <index-name>/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "query_string": {
            "query": "s*"
          }
        }
      ],
      "should": [
        {
          "match": {
            "country": "Spain"
          }
        },
        {
          "match": {
            "city": "Madrid"
          }
        }
      ]
    }
  }
}

Search Result:

 "hits" : [
      {
        "_index" : "<index-name>",
        "_type" : "_doc",
        "_id" : "1",
        "_score" : 1.4700036,
        "_source" : {
          "name" : "Santiago",
          "country" : "Spain",
          "city" : "Madrid"
        }
      },
      {
        "_index" : "<index-name>",
        "_type" : "_doc",
        "_id" : "2",
        "_score" : 1.1823215,
        "_source" : {
          "name" : "San Franciscor",
          "country" : "",
          "city" : "Madrid"
        }
      }
    ]

Upvotes: 2

Related Questions