通过SearchSourceBuilder BoolQueryBuilder TermQueryBuilder RangeQueryBuilder 来实现java代码查询Elasticsearch 的多条件 代码案列
时间: 2024-05-08 07:20:40 浏览: 197
下面是一个使用 SearchSourceBuilder 和 BoolQueryBuilder 实现多条件查询 Elasticsearch 的 Java 代码示例:
```java
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
public class ElasticsearchMultiQuery {
public void multiQuery(RestHighLevelClient client) throws IOException {
SearchRequest searchRequest = new SearchRequest("my_index");
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
// 创建 BoolQueryBuilder
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
// 添加 TermQueryBuilder
TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("field1", "value1");
boolQueryBuilder.must(termQueryBuilder);
// 添加 RangeQueryBuilder
RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("field2");
rangeQueryBuilder.gte("2021-01-01T00:00:00.000Z");
rangeQueryBuilder.lte("2021-01-31T23:59:59.999Z");
boolQueryBuilder.must(rangeQueryBuilder);
// 将 BoolQueryBuilder 添加到 SearchSourceBuilder
sourceBuilder.query(boolQueryBuilder);
// 设置超时时间
sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
searchRequest.source(sourceBuilder);
// 执行查询
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
// 处理查询结果
SearchHits hits = searchResponse.getHits();
SearchHit[] searchHits = hits.getHits();
for (SearchHit hit : searchHits) {
String sourceAsString = hit.getSourceAsString();
System.out.println(sourceAsString);
}
}
}
```
这个示例中,我们创建了一个 SearchRequest 对象,用于指定要查询的索引名称。然后,我们创建了一个 SearchSourceBuilder 对象,并使用 BoolQueryBuilder 来添加多个查询条件,包括 TermQueryBuilder 和 RangeQueryBuilder。最后,我们将 BoolQueryBuilder 添加到 SearchSourceBuilder 中,并设置了查询超时时间。最后,我们执行查询并处理查询结果。
注意:示例中的代码并没有完整的异常处理和连接 Elasticsearch 的代码,需要根据实际情况进行补充。
阅读全文