用于N个查询的MultiSearch API

时间:2016-12-01 20:53:24

标签: java elasticsearch

我有以下示例代码,我发送的查询数量取决于我构建的SearchRequestBuilder的数量,并将它们添加到MultiSearchResponse。

public static void requestBuilder(ArrayList<String> formulae) {

        Client client = TransportClient.builder().build()
                .addTransportAddress(new InetSocketTransportAddress(new InetSocketAddress("localhost",9300)));

        SearchRequestBuilder srb1 = client
                .prepareSearch(index)
                .setSource(formulae.get(1));
        SearchRequestBuilder srb2 = client
                .prepareSearch(index)
                .setSource(formulae.get(2));

        MultiSearchResponse sr = client.prepareMultiSearch()
                .add(srb1)
                .add(srb2)
                .execute()
                .actionGet();

        long nbHits = 0;
        for (MultiSearchResponse.Item item : sr.getResponses()){
            SearchResponse response = item.getResponse();
            nbHits += response.getHits().getTotalHits();
            System.out.println(response);
        }
        System.out.println(nbHits); 
        System.out.println(formulae.size());


    client.close(); 


    }

有什么方法可以生成[公式大小]量的SearchRequestBuilder?所以我可以查询我的ArrayList的每个元素。

1 个答案:

答案 0 :(得分:1)

您可以简单地迭代公式并将它们逐个添加到多重搜索中,然后触发多重搜索请求。

MultiSearchRequestBuilder sr = client.prepareMultiSearch();
for (String formula : formulae) {
    SearchRequestBuilder srb = client
            .prepareSearch(index)
            .setSource(formula);
    sr.add(srb);
}
MultiSearchResponse resp = sr.execute().actionGet();