0

What I need to do is boost documents by location (closer is better). locations is nested type.

Works fine except Elasticsearch does not return documents if locations is missing in document. If fields is missing, Elasticsearch should treat document as perfect hit. Any idea how to achieve this?

My query:

{
   "sort": [
      {
         "_score": "desc"
      }
   ],
   "query": {
      "function_score": {
         "query": {
            "bool": {
               "must_not": [],
               "should": [
                  {
                     "nested": {
                        "path": "locations",
                        "query": {
                           "function_score": {
                              "score_mode": "sum",
                              "functions": [
                                 {
                                    "gauss": {
                                       "locations.coordinates": {
                                          "origin": {
                                             "lat": "50.1078852",
                                             "lon": "15.0385376"
                                          },
                                          "scale": "100km",
                                          "offset": "20km",
                                          "decay": "0.5"
                                       }
                                    }
                                 }
                              ]
                           }
                        }
                     }
                  }
               ]
            }
         }
      }
   }
}

BTW: I'm using Elasticsearch 5.0

Bald
  • 2,156
  • 3
  • 24
  • 33

1 Answers1

1

Add one more function into the functions section with high boost (like 1000) for missing locations, something like this:

{
    "query": {
        "bool": {
            "must_not": {
                "exists": {
                    "field": "locations"
                }
            }
        },
    },
    "weight": 1000
}

So records with missing locations will come first because of high weight.

Syntax can differ a little. More information on queries here:
https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-exists-query.html
https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-function-score-query.html

  • Hmm, I will try. I don't understand one thing: Why does Elasticsearch skip documents without `locations` field? I put my query inside `should` section - not `must`. – Bald Feb 17 '17 at 13:41