Java之ES查询操作

下面继续来分享并记录ES查询相关:

具体实现如下所示:

/**
*	create by wxy_jdhk
*/
public class ElasticSearchUtils {
    //多条件
	public void getMultiSearchApi(TransportClient client) {
		SearchRequestBuilder srb1 = client.prepareSearch().setQuery(QueryBuilders.queryStringQuery("elasticsearch")).setSize(1);
		SearchRequestBuilder srb2 = client.prepareSearch().setQuery(QueryBuilders.matchQuery("name", "kimchy")).setSize(1);
		MultiSearchResponse sr = client.prepareMultiSearch()
				.add(srb1)
				.add(srb2)
				.get();
		//可通过getResponses()方法获取所有对象
		long nbHits = 0;
		for(MultiSearchResponse.Item item: sr.getResponses()) {
			SearchResponse response = item.getResponse();
			nbHits += response.getHits().getTotalHits();
		}
	}
	
	//使用聚合
	public void getUsingAggregations(TransportClient client) {
		SearchResponse sr = client.prepareSearch()
				.setQuery(QueryBuilders.matchAllQuery())
				.addAggregation(
						AggregationBuilders.terms("agg1").field("field")
				)
				.addAggregation(
						AggregationBuilders.dateHistogram("agg2")
							.field("birth")
							.dateHistogramInterval(DateHistogramInterval.YEAR)
				)
				.get();
		//在获取结果的基础上获取某类结果
		Terms agg1 = sr.getAggregations().get("agg1");
		Histogram agg2 = sr.getAggregations().get("agg2");
	}
}

你可能感兴趣的:(ElasticSearch)