1

I added to my elastic query a scripted filed, called "age", which is define like this:

  "script_fields" : {
    "age" : {
      "script" : "DateTime.now().year - doc['date_of_birth'].date.year"
    }
  }

Now, i also have other field for each person, called "myscore". I'm trying to aggreagte on myscore, and create a sub-aggregation of age. the result i should want to see is something like:

key: 25
buckets: [
     67,
     70,
     74
]
key: 62
buckets: [
    45
]

I added this aggregation:

{
    "myagg": {
        "terms": {
            "field": "myscore",
            "size": 1000,
            "order": {
                "_count": "desc"
            }
        },
        "aggregations": {
            "inner": {
                "terms": {
                    "field": "age",
                    "size": 1000
                }
            }
        }
    }
}

but the inner buckets of the age returns empty (In the hits itself i can see the age field)...

any ideas?

1 Answer 1

3

You need to use script in aggregation:

"aggs" : {
"myagg": {
    "terms": {
        "field": "myscore",
        "order": {
            "_count": "desc"
        }
    },
    "aggregations": {
        "group by age": {
            "terms": {
                "script": "DateTime.now().year - doc['dateCreated'].date.year"

            }
         }
      }
   }
 }

Hope this will help you..

Sign up to request clarification or add additional context in comments.

2 Comments

that was the first thing I did, but becasue of the fact that I already retreive the "age" field from the query (so i use a script_field), i thought it will make sense to aggregate on it without writing the script all over again...
I am not sure if you can use scripted fields in aggregations or queries

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.