Home > database >  Pass each matched record value to filter in Elasticsearch
Pass each matched record value to filter in Elasticsearch

Time:03-08

For geo_distance query I'm using a constant value for distance. I need to make it dynamic. So I want to pass the above matched record radius value to distance.

Here's the code:

let searchRadius = '12KM'
        query: {
            bool: {
                must: {
                    match: {
                        companyName: {
                            query: req.text
                        }
                    }
                },
                filter: {
                    geo_distance: {
                        distance: searchRadius,//here I want to pass doc['radius']
                        location: {
                            lat: parseFloat(req.lat),
                            lon: parseFloat(req.lon)
                        }
                    }
                },
            }
        }

For each record, I have a different radius value. I want to pass doc['radius'] instead of constant searchRadius value.

I can hit two queries then iterate the values but it's not optimal. Can anyone suggest how can I pass each record value to geo_distance filter?

CodePudding user response:

I have resolved from this answer.

Heres the code

query: {
              bool: {
                must: [
                  {
                    match: {
                      companyName: {
                        query: req.text
                      }
                    }
                  },
                  {
                    script: {
                      script: {
                        params: {
                          lat: parseFloat(req.lat),
                          lon: parseFloat(req.lon)
                        },
                        source: "doc['location'].arcDistance(params.lat, params.lon) / 1000 < doc['searchRadius'].value",
                        lang: "painless"
                      }
                    }
                  }
                ]
              }
            },

Using script Query, from more details:

https://www.elastic.co/guide/en/elasticsearch/reference/6.1/query-dsl-script-query.html

  • Related