Group by that returns only groups that match a condition inside each group

Hello,

My project has an elasticsearch dataset with lots of products that contain a group id, a price and a flag that indicates if the product is original or not:

[
 {
  id: 456,
  group_id: 1000,
  is_original: true,
  price: 99.99,
 },
 {
  id: 567,
  group_id: 1000,
  is_original: false,
  price: 109.99
 },
 {
  id: 678,
  group_id: 1000,
  is_original: false,
  price: 49.99
 },
 {
  id: 789,
  group_id: 2000,
  is_original: true,
  price: 79.99
 },
 {
  id: 898,
  group_id: 2000,
  is_original: false,
  price: 39.99
 },
 {
  id: 978,
  group_id: 2000,
  is_original: false,
  price: 29.99
 },
 ... more products
]

My requirement is to write a query with the following result:

Order by group_id and return the first 10 groups - can be random - where a product, that is not original is more expensive than the original:

[
 [
  {
   id: 567,
   group_id: 1000,
   is_original: false,
   price: 109.99
  },
  {
   id: 456,
   group_id: 1000,
   is_original: true,
   price: 99.99,
  },
  {
   id: 678,
   group_id: 1000,
   is_original: false,
   price: 49.99
  }
 ],
  ... more groups where an original is not the most expensive product
]

I have read about aggregations and filters but I do not know how to place a condition on every bucket that compares values inside a group like: is the most expensive product inside a group an original product or not.
Any help appreciated.

nvano

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