2

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

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

department
job
name

我想搜索与“部门:D1”、“部门:D2”、“工作: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();

然而,查询的执行就像每个查询都是单独的查询一样,即在此示例中,当 j3 存在于 d4 中时,具有 d4 的文档也将被匹配

如何按照我提到的方式执行搜索?我一直在尝试许多不同的查询,但似乎没有任何效果,我有什么遗漏吗?

4

2 回答 2

11

您不想使用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();
于 2017-01-03T09:41:25.907 回答
-1

对于使用 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"));
    SearchRequest searchRequest = new SearchRequest();
    searchRequest.indices("posts-1","posts-2").source(sourceBuilder);
    SearchResponse searchResponse = client.search(searchRequest);
    RestStatus status = searchResponse.status();
    System.out.println(searchResponse.toString());
于 2018-01-10T11:51:41.997 回答