Count of a particular item in array


(Sangeeth S Menon) #1

There are 5 documents each with a field "fruits" which is of type array.
#1 fruits = ["apple","apple","orange"]
#2 fruits = ["orange","grapes","mango"]
#3 fruits = ["mango","apple","apple"]
#4 fruits = ["apple","mango"]
#5 fruits = ["apple"]

I want to get the total number of occurrences of "apple" in fruits from all documents. Kindly help


(Byron Voorbach) #2

One way could be:

GET _search
{
  "size": 0,
  "aggs": {
    "amount_of_apples": {
      "terms": {
        "include": "apple", 
        "field": "fruit"
      }
    }
  }
}

(Sangeeth S Menon) #3

Hi there,

I tried as per your suggestion but instead of returning the number of apples(which is 5) , it is returning the number of documents containing apple( i.e. 3 ) . How to get the former answer i.e . the number of apples