Hpatoio
Hpatoio

Reputation: 1815

Field collapsing on collection

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"]
},

Upvotes: 1

Views: 1740

Answers (1)

Peter Dixon-Moses
Peter Dixon-Moses

Reputation: 3209

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).

Upvotes: 1

Related Questions