user13963926
user13963926

Reputation:

Calculating distance between two points in elastic search

I am trying to return the distance between two points provided as latitude and longitude values. Here's what i have tried doing.

await this.esService.search({
            index: IndexName,
            body: {
                sort: [{ avg_rating: { order: "desc" } }],
                "script_fields" : {
                    "distance" : {
                        "lang": "painless",
                        "params" : {
                           "lat" : 47.1,
                           "lon" : 8.1
                        },
                        "script" : "doc[\u0027user.userAddresses[0].location\u0027].distanceInKm(lat,lon)"
                     }
                 },
                from: offset,
                size: take,
                query: finalQuery
            }
        })

I am recieving this error parsing_exception: [parsing_exception] Reason: Unknown key for a VALUE_STRING in [lang]. Is there anything wrong going on here ?

Upvotes: 0

Views: 473

Answers (1)

Val
Val

Reputation: 217334

You're almost there, you're just missing the script declaration

            "script_fields" : {
                "distance": {                  
                  "script" : {             <--- add this
                    "lang": "painless",
                    "params" : {
                       "lat" : 47.1,
                       "lon" : 8.1
                    },
                    "source" : "doc[\u0027user.userAddresses[0].location\u0027].distanceInKm(lat,lon)"
                       ^
                  }    |
                }      |
             },  also change this

Upvotes: 1

Related Questions