Amir Afianian
Amir Afianian

Reputation: 2795

Elasticsearch: I want to count how many times a particular value has appeared in particular field

I have a simple question that is becoming a dilemma. I want to count how many times a particular value has appeared in a particular field of my elasticseach index.

let's say I have product.name and I want to know how many times the exact word "Shampoo" has appeared inside it.

I know there's the terms aggregation that provides all the unique values along with the number of their occurrences. But, given that I have billions of records, that's not good for me. I don't want an extra step to find my desired value among the keys.

Upvotes: 2

Views: 2660

Answers (1)

jaspreet chahal
jaspreet chahal

Reputation: 9099

Filter aggregation

Defines a single bucket of all the documents in the current document set context that match a specified filter. Often this will be used to narrow down the current aggregation context to a specific set of documents.

An aggregation like value_count can be applied to the bucket returned in filter aggregation to get total count of documents.

I have taken product to be of type object, if it is of nested datatype then nested query needs to be used in place of simple term query.

Mapping

{
  "index92" : {
    "mappings" : {
      "properties" : {
        "product" : {
          "properties" : {
            "name" : {
              "type" : "text",
              "fields" : {
                "keyword" : {
                  "type" : "keyword",
                  "ignore_above" : 256
                }
              }
            }
          }
        }
      }
    }
  }
}

Query:

{
  "size": 0, 
  "aggs": {
    "shampoo": {
      "filter": {
        "term": {
          "product.name.keyword": "shampoo"
        }
      },"aggs": {
        "count": {
          "value_count": {
            "field": "product.name.keyword"
          }
        }
      }
    }
  }
}

Result:

 "aggregations" : {
    "shampoo" : {
      "doc_count" : 2,
      "count" : {
        "value" : 2
      }
    }
  }

Upvotes: 2

Related Questions