Aggregation logic

i have products collection(index) with following documents :slight_smile:

{ name : 'test1',
attributes : [ {name :"color" , value : 'red'}, {name : 'size' , value : 's'}, {name : 'type' , value : 'simple'}]
}

{ name : 'test2',
attributes : [{name : 'size' , value : 'm'}]
}

{ name : 'test3',
attributes : [ {name :"color" , value : 'green'}, {name : 'size' , value : 's'}]
}

{ name : 'test4',
attributes : [ {name :"color" , value : 'red'}]
}

How can i get output like below using elastic search aggregation ?
Output :

{
attributes : {
color : [ {value : 'red', count : 2}, {value : 'green', count : 1} ],
size : [ { value : 's', count : 2}, {value : 'm', count : 1}],
type : [ {value : 'simple', count : 1}]
}

}

You may need to change the model to the format below to make it work

{ "name": "test1", "color": "red", "size: "s", "type": "simple"}

Here is the trade-off

  • your aggregation path will be straightforward and it helps the performance when dealing with lots of documents in the index.

  • you kind of lose the flexibility to have more attributes, in reality you do not because your original date model allows you to generate the model above before indexing it with ES. You can add an additional step to convert the original model to the model I'm proposing above before indexing the data. Otherwise, you may find many bumps in achieving the output you want.

Others may have a different suggestion.