ElasticSearch:为运行时字段脚本传递参数

fzwojiic  于 2022-11-22  发布在  ElasticSearch
关注(0)|答案(1)|浏览(186)

给定文档示例:https://www.elastic.co/guide/en/elasticsearch/reference/current/runtime-mapping-fields.html

PUT my-index-000001/
{
  "mappings": {
    "runtime": {
      "day_of_week": {
        "type": "keyword",
        "script": {
          "source": "emit(doc['@timestamp'].value.dayOfWeekEnum.getDisplayName(TextStyle.FULL, Locale.ROOT))"
        }
      }
    },
    "properties": {
      "@timestamp": {"type": "date"}
    }
  }
}

如何为查询提供timestamp值(以及如何从脚本访问它)?

myzjeezk

myzjeezk1#

current_date参数是timestamp中的当前日期。有一个脚本可以计算文档字段日期和参数传递的当前日期之间的差异。

POST index_002/_doc
{
  "name":"title B",
  "create_date": 1650430237000
}

GET index_002/_search
{
  "_source": [
    "name", "create_date"
  ],
  "query": {
    "match_all": {}
  },
  "script_fields": {
    "diff_dates": {
      "script": {
        "source": """
        Instant instant = Instant.ofEpochMilli(params.current_date);
        ZonedDateTime now = ZonedDateTime.ofInstant(instant, ZoneId.of('Z'));
        return doc['create_date'].value.until(now, ChronoUnit.DAYS);
        """,       
        "params": {
          "current_date": 1650516960000
        }
      }
    }
  }
}

相关问题