0

Is there a way in elasticsearch to get a field from a document containing the maximum value? (Basically working similarly to maxBy from scala)

For example (mocked):

{
    "aggregations": {
        "grouped": {
            "terms": {
                "field": "grouping",
                "order": {
                    "docWithMin": "asc"
                }
            },
            "aggregations": {
                "withMax": {
                    "max": {
                        "maxByField": "a",
                        "field": "b"
                    }
                }
            }
        }
    }
}

For which {"grouping":1,"a":2,"b":5},{"grouping":1,"a":1,"b":10} would return (something like): {"grouped":1,"withMax":5}, where the max comes from the first object due to "a" being higher there.

Timofey Stolbov
  • 4,501
  • 3
  • 40
  • 45
Bomaz
  • 1,871
  • 1
  • 17
  • 22
  • 1
    What would happen if you had `{"grouping":1,"a":2,"b":5}` and `{"grouping":1,"a":2,"b":4}` ? i.e. with same `grouping`, same `a`, which value of `b` should be returned? – Val Oct 27 '15 at 09:18
  • Either would be acceptable – Bomaz Oct 27 '15 at 11:51

1 Answers1

0

Assuming you just want the document back for which a is maximum, you can do this:

{
  "size": 0,
  "aggs": {
    "grouped": {
      "terms": {
        "field": "grouping"
      },
      "aggs": {
          "maxByA": {
            "top_hits": {
            "sort": [
             {"a": {"order": "desc"}}
            ],
            "size": 1
          }
        }
      }
    }
  }
}
Sarwar Bhuiyan
  • 344
  • 1
  • 7