Home > Blockchain >  Is there a way to return the geo distance when NOT sorting with _geo_distance?
Is there a way to return the geo distance when NOT sorting with _geo_distance?

Time:12-13

I need to return the computing distance in the result for the geo location.but not using the sort currently I'm using sorting but it ignores the exist field

here is my query:

"query": {
    "bool": {
        "filter": [
            {
                "match": {
                    "field 1": "value"
                }
            },
            {
                "match": {
                    "field2": "A"
                }
            },
            {
                "geo_distance": {
                    "distance": "20km",
                    "location": "34,-2.99"
                }
            }
        ], "should": [
            {
                "exists": {
                    "field": "field3",
                    "boost": 10000
                }
            }
        ]
    }
},
"size": 500,
"sort": [
    {
        "_geo_distance": {
            "location": {
                "lat": 34,
                "lon": 2.99
            },
            "order": "asc",
            "unit": "km",
            "mode": "min",
            "distance_type": "arc",
            "ignore_unmapped": "true"
        }
    }
]

I need if the field3 exist it gets higher ranking

CodePudding user response:

If I understand your problem correctly. This query should work:

"query": {
    "bool": {
        "filter": [
            {
                "match": {
                    "field 1": "value"
                }
            },
            {
                "match": {
                    "field2": "A"
                }
            },
            {
                "geo_distance": {
                    "distance": "20km",
                    "location": "34,-2.99"
                }
            }
        ]
    }
},
"size": 500,
"sort": [
    {
        "_script": {
            "type": "number",
            "script": {
                "source": "doc['field3'].size() > 0 ? 10000 : 0"
            },
            "order": "asc"
        }
    },
    {
        "_geo_distance": {
            "location": {
                "lat": 34,
                "lon": 2.99
            },
            "order": "asc",
            "unit": "km",
            "mode": "min",
            "distance_type": "arc",
            "ignore_unmapped": "true"
        }
    }
]

I am checking if field exist and boosting it's score

  • Related