time的类型为:
1 2 3 4 | "time" : { "type" : "date", "format" : "date_hour_minute_second" } |
Kibana的开发工具中:
1 2 3 4 5 6 7 8 9 10 11 12 | GET /es_info/_search { "query": { "script": { "script": { "source": "doc['time'].value.getHour() >= 0 && doc['time'].value.getHour() <= 6", "lang": "painless" }, "boost": 1.0 } } } |
Java代码(依赖: spring-data-elasticsearch):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder().withFields("id", "time"); BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery(); // 判断时间范围. Map<String, Object> paramMap = new HashMap<>(2); paramMap.put("startHour", 0); paramMap.put("endHour", 6); Script script = new Script( ScriptType.INLINE, Script.DEFAULT_SCRIPT_LANG, "doc['time'].value.getHour() >= params.startHour && doc['time'].value.getHour() <= params.endHour", paramMap); queryBuilder.must(QueryBuilders.scriptQuery(script)); Query query = nativeSearchQueryBuilder .withQuery(queryBuilder) .build(); |