Muhammet Can TONBUL
Muhammet Can TONBUL

Reputation: 3538

Elasticsearch Subfield Query

Data:

{
  "name": "John",
  "surname": "Brown",
  "email": "[email protected]",
  "address": [
    {
      "id": "1",
      "city": "London"
    }
  ]
}

This query working.

GET db
{
  "query": {
    "bool": {
      "must": [
        {
          "query_string": {
            "query": "*Brown* OR *@gmail.com*",
            "fields": [
              "surname",
              "email",
              "address.city"
            ]
          }
        }
      ],
      "filter": [
        {
          "bool": {
            "filter": [
              {
                "regexp": {
                  "name": {
                    "value": ".*John.*"
                  }
                }
              }
            ]
          }
        }
      ]
    }
  }
}

But when i change query string like this its not working.(By not working, I mean 0 results are returned.)

"query_string": {
  "query": "*London*",
  "fields": [
    "surname",
    "email",
    "address.city"
  ]
}

Also this query working.

"query_string": {
  "query": "*Brown*",
  "fields": [
    "surname",
    "email",
    "address.city"
  ]
}

As far as I understand it cannot find the value in address.city. But why?

Upvotes: 1

Views: 69

Answers (1)

Bhavya
Bhavya

Reputation: 16172

Based on the comments below, OP has created the index where address is of nested type

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

Index Mapping:

{
  "mappings": {
    "properties": {
      "address": {
        "type": "nested"
      }
    }
  }
}

Search Query:

    {
  "query": {
    "bool": {
      "should": [
        {
          "query_string": {
            "query": "*London*",
            "fields": [
              "surname",
              "email"
            ]
          }
        },
        {
          "nested": {
            "path": "address",
            "query": {
              "query_string": {
                "query": "*London*",
                "fields": [
                  "address.city"
                ]
              }
            }
          }
        }
      ],
      "minimum_should_match": 1
    }
  }
}

Search Result:

"hits": [
      {
        "_index": "64908538",
        "_type": "_doc",
        "_id": "1",
        "_score": 1.0,
        "_source": {
          "name": "John",
          "surname": "Brown",
          "email": "[email protected]",
          "address": [
            {
              "id": "1",
              "city": "London"
            }
          ]
        }
      }
    ]

Upvotes: 1

Related Questions