Skip to content

Instantly share code, notes, and snippets.

@zpoint
Last active August 29, 2020 02:42
Show Gist options
  • Save zpoint/b65a377ca842997e4d7d8278a32f1d49 to your computer and use it in GitHub Desktop.
Save zpoint/b65a377ca842997e4d7d8278a32f1d49 to your computer and use it in GitHub Desktop.
es painless script with timezone/getDayOfMonth

It's easy to filter by a date range with specific timezone

  {
    "range": {
      "c_birthday": {
        "time_zone": "+08:00",
        "gte": "2019-08-27"
      }
    }
  }

What if I need to search day of month ? If you don't carry the timezone information in your scripts, you will have 8 hours bias if the query does not inculde timezone information(GTM+8)

Solutions

  1. substract 8 hours in my conditions before make the query
  2. add timezone info in my scripts

query example for 2:

"query": {
    "bool": {
      "must": [
        {
          "script": {
            "script": {
              "source": "if (!doc.containsKey('c_birthday') || doc['c_birthday'].size() == 0) {return false;} else {def birthday = LocalDateTime.ofInstant(Instant.ofEpochMilli(doc['c_birthday'].value.toInstant().toEpochMilli()), ZoneId.of('UTC+8')); def min_cond = birthday.getMonthValue() >= params.min_month; if (params.min_day != 0) {min_cond = min_cond && birthday.getDayOfMonth() >= params.min_day;} def max_cond = birthday.getMonthValue() <= params.max_month; if(params.max_day != 0) {max_cond = max_cond && birthday.getDayOfMonth() <= params.max_day;} return min_cond && max_cond; }",
              "lang": "painless",
              "params": {
                "min_month": 2,
                "min_day": 17,
                "max_month": 2,
                "max_day": 27
              }
            }
          }
        }
      ]
    }
  }

image title

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment