x__dos
x__dos

Reputation: 1823

Elasticsearch: Passing params for runtime field script

Given docs example: 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"}
    }
  }
}

How can I provide timestamp value with the query (and how can I access it from script)?

Upvotes: 0

Views: 1046

Answers (1)

rabbitbr
rabbitbr

Reputation: 3261

The current_date parameter is the current date in timestamp. There is a script that makes the difference between the document field date and the current date that is passed by parameter.

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
        }
      }
    }
  }
}

Upvotes: 1

Related Questions