How to count documents in Elasticsearch with exclusive name-value attribute filters of nested type?

`Require a solution to count the number of documents in Elasticsearch that match a given set of exclusive name-value attribute pairs, where the attribute field is of nested type. The output should show the count of documents that satisfy each attribute filter separately. If a document satisfies one filter but not another, it should still be considered for the count of the satisfied filter.

Example Data in Elasticsearch:

{
  "took": 1,
  "timed_out": false,
  "_shards": {
    "total": 1,
    "successful": 1,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": {
      "value": 9,
      "relation": "eq"
    },
    "max_score": 1.0020497,
    "hits": [
      {
        "_index": "INDEX",
        "_type": "_doc",
        "_id": "DOC_1",
        "_score": 1.0020497,
        "_source": {
          "doc": {
            "attributes": [
              {
                "name": "NAME_1",
                "value": "VALUE_1"
              },
              {
                "name": "NAME_2",
                "value": "VALUE_2"
              },
              {
                "name": "NAME_3",
                "value": "VALUE_3"
              }
            ],
            "unique_doc_id": "DOC_1"
          }
        }
      }
        {
        "_index": "INDEX",
        "_type": "_doc",
        "_id": "DOC_2",
        "_score": 1.0020497,
        "_source": {
          "doc": {
            "attributes": [
              {
                "name": "NAME_1",
                "value": "VALUE_1"
              },
              {
                "name": "NAME_2",
                "value": "VALUE_7"
              },
              {
                "name": "NAME_4",
                "value": "VALUE_6"
              }
            ],
            "unique_doc_id": "DOC_2"
          }
        }
      }
    ]
  }
}

Example Input:

{
  "attributes": [
    {
      "name": "NAME_1",
      "value": "VALUE_1"
    },
    {
      "name": "NAME_2",
      "value": "VALUE_7"
    },
    {
      "name": "NAME_3",
      "value": "VALUE_30"
    }
  ]
}

Expected Output:

[
  {
    "attribute_name": "NAME_1",
    "count": 2
  },
  {
    "attribute_name": "NAME_2",
    "count": 1
  },
  {
    "attribute_name": "NAME_3",
    "count": 0
  }
]

Tried to write the script using painless script. The main problem in this was having a global variable which could store and increase the count whenever a filter got satisfied. `

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.