Distance query with grouping and sorting

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

{
  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!

1 Like

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