簡體   English   中英

Elasticsearch 自定義評分腳本——檢查字段是否存在?

[英]Elasticsearch custom scoring script -- check if field exists?

在 elasticsearch 中搜索時,我想檢查我的自定義評分腳本中是否存在字段。

此搜索有效:

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

如果 region 字段值為 1,它將結果為 1。

但是,此查詢將不起作用:如果文檔中不存在 region 字段,它將不會將文檔評分為 1:

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

如何檢查腳本中的缺失值?

如果此字段具有數字類型(包括索引為long的日期),則缺失值由0表示。

這篇文章解決了一個類似的問題。 長話短說,您應該使用doc['fieldName'].size() == 0檢查 Elasticsearch 腳本中是否存在字段。 這是一個示例實現,我正在努力僅在填充該字段時將高斯 function 應用於日期字段:

GET /items/_search
{
    "size": 10,
    "from": 0,
    "query": {
        "function_score": {
            "_name": "favorNewItems",
            "query": {
                "bool": {
                    "must": [
                        "match": {"color": "blue"}
                    ]
                }
            },
            "functions": [
                {
                    "gauss": {
                        "firstReceivedDate": {
                            "origin": "now",
                            "scale": "180d"
                        }
                    },
                    "weight": 2
                },
                {
                    "script_score": {
                        "script": "if (doc['publishDate'].size() == 0) return 0; return 1;"
                    }
                }
            ],
            "score_mode": "multiply",
            "boost_mode": "sum"
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM