Home > Back-end >  Count the number of times a filed value is shared between the documents in ElasticSearch
Count the number of times a filed value is shared between the documents in ElasticSearch

Time:01-14

How can I count the number of times where one field with a certain value appears in TWO documents where another field takes two values in ElasticSearch?

For example, if my document looks like this:

{
“Id”: 6000,

“customerName”: CN,

“customerValue”: 10
}
{
“Id”: 6001,

“customerName”: MX,

“customerValue”: 10
}

I want to count by DSL query that customerValue field of value 10 appeared once in BOTH the first document where customerName = CN and the second document where customerName = MX. I basically want to count the number of times customerValue is SHARED between the documents where customerName is CN and MX.

CodePudding user response:

The query below filter docs with customer name CN or MX. The aggs groups customerValue and the results show number docs with value equals 10.

{
  "size": 0, 
  "query": {
    "bool": {
      "should": [
        {
          "match": {
            "customerName": "CN"
          }
        },
        {
          "match": {
            "customerName": "MX"
          }
        }
      ]
    }
  },
  "aggs": {
    "agg_customer_name": {
      "terms": {
        "field": "customerValue",
        "size": 10
      }
    }
  }
}

Results:

  "aggregations": {
"agg_customer_name": {
  "doc_count_error_upper_bound": 0,
  "sum_other_doc_count": 0,
  "buckets": [
    {
      "key": 10,
      "doc_count": 2
    }
  ]
}

}

  • Related