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

**URL:** <https://discuss.elastic.co/t/group-by-that-returns-only-groups-that-match-a-condition-inside-each-group/270674>\
**Category:** Elasticsearch\
**Created:** [April 20, 2021, 8:59am UTC](https://discuss.elastic.co/t/group-by-that-returns-only-groups-that-match-a-condition-inside-each-group/270674 "2021-04-20T08:59:17Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![nvano](https://avatars.discourse-cdn.com/v4/letter/n/b9e5f3/32.png) [@nvano](https://discuss.elastic.co/u/nvano)\
**Post date:** [April 20, 2021, 8:59am UTC](https://discuss.elastic.co/t/group-by-that-returns-only-groups-that-match-a-condition-inside-each-group/270674/1 "2021-04-20T08:59:17Z")

</div>

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:

```auto
[
 {
  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:**

```auto
[
 [
  {
   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

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [May 18, 2021, 8:59am UTC](https://discuss.elastic.co/t/group-by-that-returns-only-groups-that-match-a-condition-inside-each-group/270674/2 "2021-05-18T08:59:25Z")

</div>

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