room13
room13

Reputation: 1013

Elasticsearch Percentile Aggregation on two fields

I would like to retrieve the Q1 and Q2 from a set of values that is distributed in two fields.

My documents look like:

{
   amount: 100,
   type: "CREDIT"
}
{
   amount: 80,
   type: "DEBIT"
}

Those amounts represent actually values of 100 and -80 respectively.

Let's say my all the values of my collection are [100, -80, 20, -30, 50], so my percentiles would be Q1=-30 and Q3=-50.

How can I write a query that tells elasticsearhc that documents with type: "DEBIT" need to be taken into account as negative values and then performe the percentile aggregation?

Upvotes: 0

Views: 293

Answers (1)

jaspreet chahal
jaspreet chahal

Reputation: 9099

You can use script to perform percentile aggregation. Below script checks if type is debit then return negative value else return positive value

"aggs": {
    "percentile_val": {
      "percentiles": {
        "script": {
          "lang": "painless",
          "source": "if( doc['type.keyword'].value=='DEBIT') { return -doc['amount'].value;} else {doc['amount'].value}"
        }
      }
    }
  }

Upvotes: 1

Related Questions