RestHighLevelClient一次查询多个条件

就像bulk在多文档索引时提高效率一样,msearch也能提升多个查询的执行效率,这里主要考虑到网络消耗,使用search查询可能要循环执行N遍,但是使用msearch一次从客户端一次客户请求即可。下面给出实例代码:

	@Test
	public void testMultiSearch(){
		MultiSearchRequest request = new MultiSearchRequest();    
		SearchRequest firstSearchRequest = new SearchRequest();   
		SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
		searchSourceBuilder.query(QueryBuilders.matchQuery("cityId", "410500"));
		firstSearchRequest.source(searchSourceBuilder);
		firstSearchRequest.indices("sub_bank1031");
		request.add(firstSearchRequest);                          
		SearchRequest secondSearchRequest = new SearchRequest();  
		searchSourceBuilder = new SearchSourceBuilder();
		searchSourceBuilder.query(QueryBuilders.matchQuery("cityId", "511000"));
		secondSearchRequest.source(searchSourceBuilder);
		secondSearchRequest.indices("sub_bank1031");
		request.add(secondSearchRequest);
        try {
        	MultiSearchResponse response = highLevelClient.msearch(request, RequestOptions.DEFAULT);
        	response.forEach(t->{
        		SearchResponse resp = t.getResponse();
        		
                Arrays.stream(resp.getHits().getHits())
                .forEach(i -> {
                	System.out.println(i.getId());
                    System.out.println(i.getIndex());
                    System.out.println(i.getSourceAsString());
                    System.out.println(i.getShard());
                });
                System.out.println(resp.getHits().totalHits);
        	});
        } catch (IOException e) {
            e.printStackTrace();
        }		
	}

pom中依赖为:

          
            org.elasticsearch
            elasticsearch
            6.8.0
       

            
        
            org.elasticsearch.client
            elasticsearch-rest-high-level-client
            
                
                    org.elasticsearch
                    elasticsearch                
                

            

            6.8.0
        

你可能感兴趣的:(elk)