Trying to create a search that will bring back results of location that are about 500m away from certain geo point.
I need to filter results from this search based on if location is empty in the source, or not.
I tried things like this:
"filtered" : {
    "filter": {
        "missing" : { "field" : "location" }
    }
}
This is the search JSON I got:
 {"query": {
        "function_score": {
            "query": {
                "bool": {
                    "must": [
                        {
                            "match": {"fieldA": "value"}
                        },
                        {
                            "match": { "fieldB": "value"}
                        }
                    ]
                }
            },
            "functions": [{
                    "gauss": {
                        "location": {
                            "origin": "'.$lat.','.$lon.'",
                            "scale": "500m",
                            "offset": "0km",
                            "decay": 0.33
                        }
                    }
                }]
        }
    }
}
I tried putting the filter in different places in the query but it didn't work for me, so I know I'm doing something fundamentally wrong with how the query is structured. In the future I want to add more scoring logic and other filters, but can't find a good example of such queries.
What I should do to make it work?
You can use filtered query with geo_distance to filter out the results first. You can also use "weight" in function_score to explicit boost the distance over the "match" queries:
{
   "query": {
      "function_score": {
         "query": {
            "filtered": {
               "query": {
                  "bool": {
                     "must": [
                        {
                           "match": {
                              "fieldA": "value"
                           }
                        },
                        {
                           "match": {
                              "fieldB": "value"
                           }
                        }
                     ]
                  }
               },
               "filter": {
                  "geo_distance" : {
                        "distance" : "500m",
                        "location" : "'.$lat.','.$lon.'"
                    }
               }
            }
         },
         "functions": [
            {
               "gauss": {
                  "location": {
                     "origin": "'.$lat.','.$lon.'",
                     "scale": "500m",
                     "offset": "0km",
                     "decay": 0.33
                  }
               },
               "weight": "3"
            }
         ]
      }
   }
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With