1

Suppose I've a very simple index. Blog post and blog categories. One blog belong to one or more categories.

I want to find for each category the last 3 posts. How can I do this ? I've read about "Field collapsing" here https://www.elastic.co/guide/en/elasticsearch/guide/current/top-hits.html but the example refers to a scalar field, I've a collection.

A document could be:

{ "title" : "My post",
  "categories" : [{ "tech" => "Technology", "professional" => "Professional"]
},
{ "title" : "My secondo post",
  "categories" : [{ "professional" => "Professional"]
},
Community
  • 1
  • 1
Hpatoio
  • 1,785
  • 1
  • 15
  • 22

1 Answers1

1

You can only aggregate values, not keys, so the first step is to simplify your categories field.

If you can index categories simply as a list of strings (e.g. your category slugs only, instead of slug => slug_title pairs), then you can use a Terms Aggregation to show you all of the categories present in your result-set, and then a nested Top Hits Aggregation to expose the top three posts sorted by date.

I believe this example on the Top Hits Aggregation page is doing exactly what you want (provided you can index categories as a list of strings).

Peter Dixon-Moses
  • 3,169
  • 14
  • 18