RestHighLevelClient一次查询多个条件

2022-03-29 14:43:10 浏览数 (1)

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

代码语言:javascript复制
	@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中依赖为:

代码语言:javascript复制
          <dependency>
             <groupId>org.elasticsearch</groupId>
             <artifactId>elasticsearch</artifactId>
             <version>6.8.0</version>
         </dependency>
         <!-- elasticsearch high level -->    
         <dependency>
             <groupId>org.elasticsearch.client</groupId>
             <artifactId>elasticsearch-rest-high-level-client</artifactId>
             <exclusions>
                 <exclusion>
                     <groupId>org.elasticsearch</groupId>
                     <artifactId>elasticsearch</artifactId>                
                 </exclusion>
             </exclusions>
             <version>6.8.0</version>
         </dependency>

0 人点赞