ES时间查询报错 - “caused_by“:{“type“:“illegal_argument_exception“,“reason“:“failed to parse date field

项目场景:

在ES的使用过程中,用到了时间范围的查询功能,出现时间解析错误的报错信息:“caused_by”:{“type”:“illegal_argument_exception”,“reason”:"failed to parse date field …


问题描述

查询query对象部分字段描述

    @ApiModelProperty(value = "开始时间")
    @JsonFormat(locale="zh", timezone="GMT+8", pattern="yyyy-MM-dd HH:mm:ss")
    private Date searchStartTime;

    @ApiModelProperty(value = "结束时间")
    @JsonFormat(locale="zh", timezone="GMT+8", pattern="yyyy-MM-dd HH:mm:ss")
    private Date searchEndTime;

查询时间范围错误java代码

        //时间范围
        if (query.getSearchStartTime()!=null  && query.getSearchEndTime()!=null){
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("createTime");
            rangeQuery.from(query.getSearchStartTime());
            rangeQuery.to(query.getSearchEndTime());
            //因为filter比query快,也可以将rangeQuery放入sourceBuilder
            boolQueryBuilder.filter(rangeQuery);
        }

报错信息


Suppressed: org.elasticsearch.client.ResponseException: method [POST], host [http://192.168.9.194:9200], URI [/upload-file/_search?pre_filter_shard_size=128&typed_keys=true&max_cothrottled=true&search_type=query_then_fetch&batched_reduce_size=512&ccs_minimize_roundtrips=true], status line [HTTP/1.1 400 Bad Request]
{"error":{"root_cause":
[{"type":"parse_exception",
"reason":"failed to parse date field [2022-02-28T16:00:00.000Z] with format [yyyy-MM-dd HH:mm:ss || yyyy-MM-dd || yyyy/MM/dd HH:m-dd HH:mm:ss || yyyy-MM-dd || yyyy/MM/dd HH:mm:ss|| yyyy/MM/dd ||epoch_millis]]"}],
"type":"search_phase_execution_exception",
"reason":"all shards failed",
"phase":"query",
"grouped"e_exception",
"reason":"failed to parse date field [2022-02-28T16:00:00.000Z] with format [yyyy-MM-dd HH:mm:ss || yyyy-MM-dd || yyyy/MM/dd HH:mm:ss|| yyyy/MM/dd ||epoch_millis]: [f/dd HH:mm:ss|| yyyy/MM/dd ||epoch_millis]]",
"caused_by":{"type":"illegal_argument_exception",
"reason":"failed to parse date field [2022-02-28T16:00:00.000Z] with format [yyyy-MM-darse_exception","reason":"Failed to parse with all enclosed parsers"}}}}]},"status":400}


原因分析:

es和mysql不同,mysql传入date后经过解析可以直接作为参数进行sql拼写,但是es貌似不行,需要转为时间戳


解决方案:

将时间参数转为时间戳进行查询

        //时间范围
        if (query.getSearchStartTime()!=null  && query.getSearchEndTime()!=null){
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("createTime");
            rangeQuery.from(query.getSearchStartTime().getTime());
            rangeQuery.to(query.getSearchEndTime().getTime());
            //因为filter比query快,也可以将rangeQuery放入sourceBuilder
            boolQueryBuilder.filter(rangeQuery);
        }

建议

我试过localdatetime类型的时间,但是没有date类型好用

你可能感兴趣的:(springboot,es,elasticsearch,java,搜索引擎)