Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elasticsearch custom scoring script -- check if field exists?

I'd like check if a field exists in my custom scoring script when searching in elasticsearch.

This search works:

{
  "query": {
    "custom_score": {
      "script": "((doc['region'].value == '1') ? 1 : 0)",
      "query": {
        "constant_score": {
          "filter": {
            "and": [
              {
                "term": {
                  "id": "100"
                }
              }
            ]
          }
        }
      }
    }
  },
  "size": 1
}

It will score the result as 1 if the region field value is 1.

However this query will not work: it will not score the document as 1 if the region field does not exist in the document:

{
  "query": {
    "custom_score": {
      "script": "((doc['region'].value == null) ? 1 : 0)",
      "query": {
        "constant_score": {
          "filter": {
            "and": [
              {
                "term": {
                  "id": "100"
                }
              }
            ]
          }
        }
      }
    }
  },
  "size": 1
}

How do I check for missing values in a script?

like image 395
user697547 Avatar asked Dec 09 '22 20:12

user697547


1 Answers

If this field has a numeric type, which includes dates that are indexed as long, the missing value is represented by 0.

like image 113
imotov Avatar answered May 25 '23 00:05

imotov