1. 程式人生 > >ElasticSearch教程-關於Elasticsearch MultiSearch 查詢

ElasticSearch教程-關於Elasticsearch MultiSearch 查詢

關於Elasticsearch  MultiSearch 查詢,一個請求可同時支援多個查詢

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.lucene.queryparser.flexible.core.builders.QueryBuilder;
import org.elasticsearch.action.search.MultiSearchRequestBuilder;
import org.elasticsearch.action.search.MultiSearchResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.index.query.QueryBuilders;


import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author :PENG.ZHANG
 * @Description :
 * @Date : Create in 15:22 2018/6/4
 * Created by Administrator on 2018/6/4.
 */
public class MultiSearch {
private static final Logger logger = LogManager.getLogger(MultiSearch.class);

    public static void main(String[] args) {
try {

            Settings settings = Settings.settingsBuilder()
                    .put("cluster.name", "elasticsearch").build();
// 建立客戶端
Client client =  TransportClient.builder().settings(settings).build()
                    .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.0.81"), 9300));
// 初始化兩個查詢
SearchRequestBuilder srb1 =client
                    .prepareSearch().setQuery(QueryBuilders.boolQuery()
                            .must(QueryBuilders.boolQuery().should(QueryBuilders.termQuery("idNumb","2028"))))
                    .setExplain(true);

SearchRequestBuilder srb2 = client
                    .prepareSearch().setQuery(QueryBuilders.boolQuery()
                            .must(QueryBuilders.boolQuery().should(QueryBuilders.termQuery("idNumb","2035"))))
                    .setExplain(true);
//將query物件放入集合中模仿傳參
List<SearchRequestBuilder> arrList = new ArrayList<>();
arrList.add(srb1);
arrList.add(srb2);
//MultiSearch查詢
MultiSearchRequestBuilder sr = null;
            for (SearchRequestBuilder ss : arrList){
                 sr = client.prepareMultiSearch().add(ss);
}
            MultiSearchResponse ss = sr.execute().actionGet();
            long nbHits = 0;
            for (MultiSearchResponse.Item item : ss.getResponses()) {
                SearchResponse response = item.getResponse();
nbHits += response.getHits().getTotalHits();
System.out.println("print result :"+nbHits);
}
        } catch (Exception e) {
logger.error("exception:", e);
}
    }

}