ElasticSearch High Level REST API【4】多搜索

1、Multi-Search多搜索请求

Multi-Search可同时添加多个search搜索请求,并行地在一个http请求中执行多个搜索请求,相较多次单请求查询可提升查询效率。ES客户掉通过mget方法实现多请求搜索:

public void multiSearch(){
        RestHighLevelClient client = elasticClient.getRestHighLevelClient();
        MultiSearchRequest request = new MultiSearchRequest();
        SearchRequest firstSearchRequest = new SearchRequest();
        SearchSourceBuilder firstBuilder = new SearchSourceBuilder();
        firstBuilder.query(matchQuery("name","潇潇"));
        firstSearchRequest.source(firstBuilder);
        request.add(firstSearchRequest);
        SearchRequest secondRequest = new SearchRequest();
        SearchSourceBuilder secondBuild = new SearchSourceBuilder();
        secondBuild.query(matchQuery("position","建筑师"));
        secondRequest.source(secondBuild);
        request.add(secondRequest);
        try {
            MultiSearchResponse multiResponse = client.msearch(request, RequestOptions.DEFAULT);
            MultiSearchResponse.Item firstItem  = multiResponse.getResponses()[0];
            if (firstItem.getFailure() != null) {
                System.out.println("第一个请求失败!");
            }
            SearchResponse firstResponse = firstItem.getResponse();
            for (SearchHit documentFields : firstResponse.getHits().getHits()) {
                System.out.println("第一个查询请求返回:"+documentFields.getSourceAsString());
            }
            MultiSearchResponse.Item seconditem = multiResponse.getResponses()[1];
            if (seconditem.getFailure() != null) {
                System.out.println("第二个请求失败!");
            }
            SearchResponse secondResponse = seconditem.getResponse();
            for (SearchHit documentFields : secondResponse.getHits().getHits()) {
                System.out.println("第二的查询请求返回:" + documentFields.getSourceAsString());
            }
            client.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

模板搜索

posted @ 2019-01-20 22:45  有追求的程序员  阅读(786)  评论(0编辑  收藏  举报