使用java api进行Elasticsearch多条件查询

时间:2017-01-03 09:36:49

标签: java elasticsearch elasticsearch-java-api

有多个文档,每个文档包含大约100个字段。我想通过elasticsearch Java API 5.x执行以下搜索:

我想在此搜索中使用3个字段,即

department
job
name

我希望搜索与" department:D1"," department:D2"," job:J1" ,"工作:J2" "名称:N1"

我一直试图这样做

String[] departments = ["d1","d2","d3"];
String[] jobs = ["j1","j2","j3"];
String[] names = ["n1"];

MultiSearchRequestBuilder requestbuilder; 

requestBuilder.add(client.prepareSearch().setQuery(QueryBuilders.termsQuery("department", departments)));
requestBuilder.add(client.prepareSearch().setQuery(QueryBuilders.termsQuery("job", jobs)));
requestBuilder.add(client.prepareSearch().setQuery(QueryBuilders.termsQuery("name", names)));

MultiSearchResponse response = requestBuilder.get();

然而,执行查询就好像每个查询都是一个单独的查询,即在这个例子中,当d4中存在j3时,带有d4的文档将被匹配以及

如何以我提到的方式进行搜索?我一直在尝试各种不同的查询,似乎没有任何工作,我有什么遗漏吗?

2 个答案:

答案 0 :(得分:5)

您不想使用MultiSearchRequestBuilder,只需在bool/filter查询中合并三个约束:

BoolQueryBuilder query = QueryBuilders.boolQuery()
   .filter(QueryBuilders.termsQuery("department", departments))
   .filter(QueryBuilders.termsQuery("job", jobs))
   .filter(QueryBuilders.termsQuery("name", names));
SearchResponse resp = client.prepareSearch().setQuery(query).get();

答案 1 :(得分:0)

对于使用HighRestClient的Elasticsearch 5.6.4,添加所需数量的sourcebuilder ...

static RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
public static void multisearch() throws IOException{
    SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); 
    sourceBuilder.query(QueryBuilders.termQuery("name", "vijay1"));
    SearchSourceBuilder sourceBuilder1 = new SearchSourceBuilder(); 
    sourceBuilder.query(QueryBuilders.termQuery("name", "vijay"));
    SearchRequest searchRequest = new SearchRequest();
    searchRequest.indices("posts-1","posts-2").source(sourceBuilder).source(sourceBuilder1);
    SearchResponse searchResponse = client.search(searchRequest);
    RestStatus status = searchResponse.status();
    System.out.println(searchResponse.toString());