# Distance query with grouping and sorting

**URL:** <https://discuss.elastic.co/t/distance-query-with-grouping-and-sorting/320272>\
**Category:** Elasticsearch\
**Created:** [December 1, 2022, 4:44pm UTC](https://discuss.elastic.co/t/distance-query-with-grouping-and-sorting/320272 "2022-12-01T16:44:33Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![dthomas](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/dthomas/32/114109_2.png) [@dthomas](https://discuss.elastic.co/u/dthomas)\
**Post date:** [December 1, 2022, 4:44pm UTC](https://discuss.elastic.co/t/distance-query-with-grouping-and-sorting/320272/1 "2022-12-01T16:44:33Z")

</div>

I have a single index that represents the locations of buildings in the United States. Each buildings is owned by a company (hence the **CompanyId** property). The index looks something like this: (fake geo-coordinates).

```auto
{
  Id: 1
  CompanyId: 10,
  Coordinates: (20, 4)
},
{
  Id: 2
  CompanyId: 10,
  Coordinates: (30, 33)
},
{
  Id: 3
  CompanyId: 5,
  Coordinates: (2, 10)
},
{
  Id: 4
  CompanyId: 5,
  Coordinates: (33, 66)
},

```

Business requirement is to be able to do a query such as:

Given a target geo coordinate in the United States, return a list of results in the following format:

1. The list of buildings are grouped by CompanyId.
2. Within the groups for each company, the buildings need to be ordered by nearest distance to the target.
3. The groups of companies should be ordered by each company's nearest building to the Target.
4. Paging needs to be supported.

## Things I've Tried

- I've tried doing a Terms Aggregation on the CompanyId, but I'm then unsure how to sort the inner groups by the calculated distance field, and then sort the company groups themselves by each company's nearest building so I could page over the results.

- I've also looked into composite aggregations, but I'm not sure that would work with what I'm trying to do.

It seems that the problem with this is that I have to look at every location every time to do the calculation, and this could be expensive.

Any guidance here would be appreciated!

Thanks!

---

<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:** [December 29, 2022, 4:44pm UTC](https://discuss.elastic.co/t/distance-query-with-grouping-and-sorting/320272/2 "2022-12-29T16:44:36Z")

</div>

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