Search code examples
elasticsearchkibanaelasticsearch-queryaws-elasticsearch

Elastic search query for name / value pair columns pull


We have one document in elastic search with multiple sections of name/value pair and we want to fetch value's only based on name column value.

"envelopeData": {
  "envelopeName": "Bills",
  "details": {
    "detail": [
      {
        "name": "UC_CORP",
        "value": "76483"
      },
      {
        "name": "UC_CYCLE",
        "value": "V"
      }    

We are expecting only 76483 as result based on name equals to UC_CORP


Solution

  • If the field envelopeData.details.detail is nested type then you can perform a match query for the desired name on the nested path and can use inner_hits to get just the value.

    Map the field envelopeData.details.detail as nested(if not nested):

    PUT stackoverflow
    {
      "mappings": {
        "_doc": {
          "properties": {
            "envelopeData.details.detail": {
              "type": "nested" 
            }
          }
        }
      }
    }
    

    then you can perform the following query to get value using inner_hits:

    GET stackoverflow/_search
    {
      "_source": "false", 
      "query": {
        "nested": {
          "path": "envelopeData.details.detail",
          "query": {
            "match": {
              "envelopeData.details.detail.name.keyword": "UC_CORP"
            }
          }, 
          "inner_hits": {
            "_source": "envelopeData.details.detail.value"
          }
        }
      }
    }
    

    which outputs:

    {
      "_index": "stackoverflow",
      "_type": "_doc",
      "_id": "W5GUW2gB3GnGVyg-Sf4T",
      "_score": 0.6931472,
      "_source": {},
      "inner_hits": {
        "envelopeData.details.detail": {
          "hits": {
            "total": 1,
            "max_score": 0.6931472,
            "hits": [
              {
                "_index": "stackoverflow",
                "_type": "_doc",
                "_id": "W5GUW2gB3GnGVyg-Sf4T",
                "_nested": {
                  "field": "envelopeData.details.detail",
                  "offset": 0
                },
                "_score": 0.6931472,
                "_source": {
                  "value": "76483"  -> Outputs value only
                }
              }
            ]
          }
        }
      }
    }