欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Elasticsearch Java REST高级客户端 MultiSearch Api

程序员文章站 2022-07-05 14:19:31
...

Elasticsearch Java REST高级客户端 MultiSearch Api

使用 MultiSearch Api 在一个http请求中并行执行多个Search请求。

public static void multiSearch() {
		var client = getClient();
		
		MultiSearchRequest msRequest = new MultiSearchRequest();
		
		SearchRequest request1 = new SearchRequest("movies");
		SearchSourceBuilder builder1 = new SearchSourceBuilder();
		builder1.query(QueryBuilders.matchQuery("title", "you"));
		request1.source(builder1);
		msRequest.add(request1);
		
		SearchRequest request2 = new SearchRequest("movies");
		SearchSourceBuilder builder2 = new SearchSourceBuilder();
		builder2.query(QueryBuilders.matchQuery("title", "life"));
		request2.source(builder2);
		msRequest.add(request2);
		
		try {
			MultiSearchResponse responses = client.msearch(msRequest, RequestOptions.DEFAULT);
			Arrays.asList(responses.getResponses()).stream()
			.map(item -> item.getResponse())
			.map(response -> response.getHits())
			.filter(hit -> hit != null)
			.forEach(hit -> hit.forEach(System.out::println));
			
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			close(client);
		}
	}
	
	/**

	 * 关闭客户端
	 * 
	 * @param client
	 */
	private static void close(RestHighLevelClient client) {
		try {
			client.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取客户端
	 * 
	 * @return
	 */
	private static RestHighLevelClient getClient() {
		RestHighLevelClient client = new RestHighLevelClient(
				RestClient.builder(new HttpHost("elk-node01", 9200, "http"), new HttpHost("elk-node02", 9200, "http"),
						new HttpHost("elk-node03", 9200, "http")));
		return client;
	}