# Single query to sort documents by geodistance based on another documents id

**URL:** https://discuss.elastic.co/t/single-query-to-sort-documents-by-geodistance-based-on-another-documents-id/125780
**Category:** Elasticsearch
**Created:** [March 27, 2018, 3:10pm UTC](https://discuss.elastic.co/t/single-query-to-sort-documents-by-geodistance-based-on-another-documents-id/125780 "2018-03-27T15:10:03Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![ftaran](https://avatars.discourse-cdn.com/v4/letter/f/c77e96/32.png) [@ftaran](https://discuss.elastic.co/u/ftaran)
#### Post date: [March 27, 2018, 3:10pm UTC](https://discuss.elastic.co/t/single-query-to-sort-documents-by-geodistance-based-on-another-documents-id/125780/1 "2018-03-27T15:10:04Z")

</div>

I have an index in elasticsearch which contains a Id field and a geopoint.

right now in order to get the nearest documents I have to make two queries, one to get the original document by its id and after that use its coordinates to do a geosort. I was wondering if there is anyway to execute this as a single query.

```
public IEnumerable<RestaurantSearchItem> GetNearbyRestaurants(double latitude, double longitude)
        {
            var query = _elasticClient.Search<RestaurantSearchItem>(s =>
                s.Index(RestaurantSearchItem.IndexName)
                .Sort(
                    ss =>ss.GeoDistance(
                        g => g
                            .Field(p => p.Location)
                            .DistanceType(GeoDistanceType.Plane)
                            .Unit(DistanceUnit.Meters)
                            .Order(SortOrder.Ascending)
                            .Points(new GeoLocation(latitude,longitude)))));

            var nearByRestaurants = query.Documents;

            foreach (var restaurant in nearByRestaurants)
            {
                restaurant.Distance = Convert.ToDouble(query.Hits.Single(x => x.Id == restaurant.Id).Sorts.Single());
            }

            return nearByRestaurants;
        }
```

---

<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: [April 24, 2018, 3:10pm UTC](https://discuss.elastic.co/t/single-query-to-sort-documents-by-geodistance-based-on-another-documents-id/125780/2 "2018-04-24T15:10:23Z")

</div>

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