# Optimization: fetching documents as per geo distance

**URL:** <https://discuss.elastic.co/t/optimization-fetching-documents-as-per-geo-distance/119251>\
**Category:** Elasticsearch\
**Created:** [February 9, 2018, 2:14pm UTC](https://discuss.elastic.co/t/optimization-fetching-documents-as-per-geo-distance/119251 "2018-02-09T14:14:23Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![bhagat95](https://avatars.discourse-cdn.com/v4/letter/b/5daacb/32.png) [@bhagat95](https://discuss.elastic.co/u/bhagat95)\
**Post date:** [February 9, 2018, 2:14pm UTC](https://discuss.elastic.co/t/optimization-fetching-documents-as-per-geo-distance/119251/1 "2018-02-09T14:14:23Z")

</div>

I need to fetch list of stocks sorted by a sort\_score in buckets of 10x km distance from a given location.  
1 : [0-10] km  
2 : [10-20] km  
3 : [20-30] km  
.  
.

Stocks in bucket p should appear before bucket q for all p\<q. All stocks in bucket q should be sorted as per sort score. Also I must have facility of "from" and "size" for pagination.

To achieve this I have written the following query which is working fine to the best of my knowledge but I see a lot of room for improvement in terms of optimizations:

```
GET stocks/_search
{
   "from": 0,
   "size": 25,
   "_source": false,
   "docvalue_fields": [
      "sort_score",
      "location"
   ],
   
   "sort": [
      {
         "_script": {
            "type": "number",
            "script": {
               "lang": "painless",
               "inline": "double diff = doc['location'].planeDistance(params.targetLat, params.targetLong) ; return (int)((diff)/params.distance_bucket);",
               "params": {
                  "targetLat": 91.0678637,
                  "targetLong": 72.9991898,
                  "distance_bucket" : 10000
               }
            },
            "order": "asc"
         }
      },
      "sort_score"
   ]
}

```

Is it the best way to implement this?

---

<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:** [March 9, 2018, 2:14pm UTC](https://discuss.elastic.co/t/optimization-fetching-documents-as-per-geo-distance/119251/2 "2018-03-09T14:14:27Z")

</div>

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