当我们使用Java对Elasticsearch进行查询时,经常会涉及到in
和not in
这两种条件查询,本文将介绍如何使用Java实现这两种条件查询。
Elasticsearch in查询的实现
首先,我们需要导入相关的依赖库:
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.3.1</version>
</dependency>
然后,我们需要创建一个org.elasticsearch.index.query.TermsQueryBuilder
对象,并将它添加到org.elasticsearch.index.query.BoolQueryBuilder
对象中。具体实现代码如下:
List<String> values = Arrays.asList("value1", "value2", "value3");
TermsQueryBuilder termsQueryBuilder = QueryBuilders.termsQuery("field", values);
BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder().must(termsQueryBuilder);
SearchRequest searchRequest = new SearchRequest("index_name");
searchRequest.source(new SearchSourceBuilder().query(boolQueryBuilder));
其中,values
是一个包含需要查询的值的列表,field
是需要查询的字段名,index_name
是需要查询的索引名称。
下面是一个完整的示例代码,该示例从名为test_index
的索引中查询field_name
字段中有value1
、value2
或value3
的文档:
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
List<String> values = Arrays.asList("value1", "value2", "value3");
TermsQueryBuilder termsQueryBuilder = QueryBuilders.termsQuery("field_name", values);
BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder().must(termsQueryBuilder);
SearchRequest searchRequest = new SearchRequest("test_index");
searchRequest.source(new SearchSourceBuilder().query(boolQueryBuilder));
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
Elasticsearch not in查询的实现
要实现not in
查询,我们可以使用range
查询和相应的逻辑操作符。具体实现代码如下:
List<String> values = Arrays.asList("value1", "value2", "value3");
TermsQueryBuilder termsQueryBuilder = QueryBuilders.termsQuery("field", values);
BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder().mustNot(termsQueryBuilder);
SearchRequest searchRequest = new SearchRequest("index_name");
searchRequest.source(new SearchSourceBuilder().query(boolQueryBuilder));
其中,mustNot
方法用于构建一个not in的查询条件。
下面是一个完整的示例代码,该示例从名为test_index
的索引中查询field_name
字段中不包含value1
、value2
或value3
的文档:
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
List<String> values = Arrays.asList("value1", "value2", "value3");
TermsQueryBuilder termsQueryBuilder = QueryBuilders.termsQuery("field_name", values);
BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder().mustNot(termsQueryBuilder);
SearchRequest searchRequest = new SearchRequest("test_index");
searchRequest.source(new SearchSourceBuilder().query(boolQueryBuilder));
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
以上就是使用Java实现Elasticsearch in和not in查询的完整攻略,包含两条示例说明,希望对你有所帮助。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:JAVA使用ElasticSearch查询in和not in的实现方式 - Python技术站