Does elastic search allow aggregations within a document? Or is there another way to do same

I am new to elastic search, I have a elastic search index example as follows: Category is my index and insight is field having array of elements.

"category":
{
"insight":
{
[
{
"topic":"xyz",
"id":"10"
} ,
{
"topic":"xyz",
"id":"14"
}
,{
"topic":"ihn",
"id":"19"
}
]
}
}

I want to find the count of those elements within this document that have topic as "xyz". Is this possible using elastic search aggregation or does it work only with multiple documents.

I am not 100% sure what you mean. If you want to query all documents with the topic xyz you should set the topic as a keyword and use a terms query. It will give you back all your documents with xyz.

GET /_search
{
    "query" : {
        "terms" : {
            "topic" : ["xyz"]
        }
    }
}

Will this terms query or any other elastic search aggregation look for values within 1 document? If 1 document itself has topic xyz mentioned 10 times, will it count that as 10 ?

Index is as follows:

PUT /data_level/_doc/1?pretty

{
"category_id": 1,
"category_name": "yogurt",
"insights": [
{
"insight_id": 1,
"insight_min_date": "11-12-2019",
"insight_max_date": "31-12-2019",
"topic": [
"Meal Replacement",
"Sustainable"
},
{
"insight_id": 2,
"insight_min_date": "1-12-2019",
"insight_max_date": "30-12-2019",
"topic": [
"Meal Replacement"
}
]

I want to result as:

Meal Replacement: 2
Sustainable:1

This is all within 1 document. No separate documents here.

Not familiar with this type of query. Sorry

Aggregations work across documents, not within them.

You will probably need to split your documents out so that you have one for each topic for a given time range. So in your last example, you'd actually have 3 documents, that you'd then aggregate across/

1 Like

Yes, that's correct. I already did that and it worked correctly. Thanks for clarifying.

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.