2

I have a field indexed as String in elasticsearch 5
For example 20090219 , 20100416 etc

I can make a aggregation this data, But I want to aggregate on substring. that is on
2009,2010

I don't want to convert to date. I want to get first 4 characters and get the count. This is my current code.Very new to Elasticsearch

$params['body']["aggs"]["Year"]["terms"]["field"] = "PublicationDate.keyword";
$params['body']["aggs"]["Year"]["terms"]["size"]  = 10;
$params['body']["aggs"]["Year"]["terms"]["order"]["_count"] = "desc";

2 Answers 2

3

You can use elasticsearch script feature to achieve this.

GET my-index/_search
{
    "aggs" : {
        "my-agg" : {
            "terms" : {
                "script": {
                  "inline": "doc['PublicationDate.keyword'].getValue().substring(0,4)"
                }, 
                "size": 10, 
                "order" : { "_count" : "desc" }
            }
        }
    }
}

I don't know equivalent php script for above command, but believe you will able to make it work in php.

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

4 Comments

this code gives this error Fielddata is disabled on text fields by default. Set fielddata=true on [PublicationDate.keyword] in order to load fielddata in memory by uninverting the inverted index. Note that this can however use significant memory.
Make sure you are using PublicationDate.keyword field for aggregations which will have mapping of type keyword.
I did not understand, can you please elaborate
You need define mapping for PublicationDate.keyword as keyword type. btw can you share current mapping for PublicationDate.keyword field?
1

this did the task

$params['body']["aggs"]["PublicationYear"]["terms"]["script"] = "_value.substring(0,4)";

Comments

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.