NativeSearchQueryBuilder多条件查询方法

百度了很多方法都是

    NativeSearchQuery nativeSearchQuery = searchQuery.withIndices("prod-webapi*")
                .withQuery(QueryBuilders.rangeQuery("@timestamp").gte(startTime.getTime()).lte(endTime.getTime()))
                .withQuery(QueryBuilders.queryStringQuery("ERROR").field("message"))
                .withSort(SortBuilders.fieldSort("@timestamp").order(SortOrder.ASC))
                .withPageable(page)
                .build();

调用多个withQuery,但是请看看底层代码。底层方法是

    public NativeSearchQueryBuilder withQuery(QueryBuilder queryBuilder) {
        this.queryBuilder = queryBuilder;
        return this;
    }

会覆盖掉之前的一个查询条件。

 

正确的方法

        NativeSearchQuery nativeSearchQuery = searchQuery.withIndices("prod-webapi*")
                .withQuery(QueryBuilders.boolQuery().must((QueryBuilders.rangeQuery("@timestamp").gte(startTime.getTime()).lte(endTime.getTime())))
                        .must(QueryBuilders.queryStringQuery("ERROR").field("message")))
                .withSort(SortBuilders.fieldSort("@timestamp").order(SortOrder.ASC))
                .withPageable(page)
                .build();

 

你可能感兴趣的:(elasticsearch)