0

Suppose I have many documents like this:

{
    "foo": "Something",
    "bars":
    [
        {
            "identifier": 1,
            "content": "meh",
            "quantity": 2
        },
        {
            "identifier": 2,
            "content": "bah",
            "quantity": 1
        }
    ]
}

How would I query the top 10 most present bars[].identifier considering the formula times it appear * quantity ?

EDIT: I achieved something like this

{
   "size":0,
   "aggs":{
      "bars":{
         "nested":{
            "path":"bars"
         },
         "aggs":{
            "top-terms-aggregation":{
               "terms":{
                  "field":"bars.identifier",
                  "size":10
               }
            }
         }
      }
   }
}

But still cannot multiply by the quantity field.

Community
  • 1
  • 1
Luiz
  • 2,429
  • 8
  • 28
  • 43
  • You will probably need a script to do this: https://www.elastic.co/guide/en/elasticsearch/reference/master/modules-scripting-fields.html – Adonis Mar 19 '17 at 10:02

1 Answers1

1

I achieved this using a query similar to this one:

{
    "query": {
        "match_all": {}
    },
    "size": 0,
    "aggs": {
        "bars": {
            "nested": {
                "path": "bars"
            },
            "aggs": {
                "bars_group": {
                    "terms": {
                        "field": "bars.identifier",
                        "size": 10,
                        "order": {
                            "count_bars": "desc"
                        }
                    },
                    "aggs": {
                        "count_bars": {
                            "sum": {
                                "field": "bars.quantity"
                            }
                        }
                    }
                }
            }
        }
    }
}

I hope that this help you.

Daniel Asanome
  • 478
  • 5
  • 7