2017-01-03 117 views
1

有多個文檔每個包含大約100個字段。我想執行下列搜索槽elasticsearch的Java API 5.x的:Elasticsearch使用java api進行多條件查詢

有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(); 

但是,查詢是執行ED,如同各自被一個單獨的查詢,即在當J3存在於D4本例中,D4該文件將被藏漢匹配

如何執行搜索我提到的方法是什麼?我一直在嘗試許多不同的查詢,似乎沒有任何工作,有什麼我失蹤?

回答

3

你不想使用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(); 
+0

使用您提供的代碼我根本沒有得到任何結果,甚至試圖縮小它只按部門過濾,但仍然是命中列表爲空。如果你的代碼是正確的,那麼你知道可能是什麼原因嗎? – Zerg

+0

是否分析了您的字段?術語查詢是完全匹配的查詢,因此您的術語需要與您嘗試匹配的字段中已編入索引的術語完全相同 – Val

+0

我必須使用.setSize()作爲響應,並且它位於錯誤的位置的鏈條。它現在有效。 – Zerg

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()); 
相關問題