Java操作elasticsearch进行桶聚合查询

我爱海鲸 2020-03-16 21:29:14 暂无标签

简介桶聚合查询

//分组聚合

@Test

public void test17() throws IOException, InterruptedException, ExecutionException {

//指定ES集群

Settings settings = Settings.builder().put("cluster.name","haijines").build();

//创建访问es服务器的客户端

TransportClient client = new PreBuiltTransportClient(settings)

.addTransportAddress(new TransportAddress(InetAddress.getByName("192.168.42.160"),9300));

AggregationBuilder agg = AggregationBuilders.terms("terms").field("age");

SearchResponse response = client.prepareSearch("lib3")

.addAggregation(agg)

.execute().actionGet();

Terms terms = response.getAggregations().get("terms"); 

for(Terms.Bucket entry : terms.getBuckets()) {

System.out.println(entry.getKey()+":"+entry.getDocCount());

}


}

//filter聚合

@Test

public void test18() throws IOException, InterruptedException, ExecutionException {

//指定ES集群

Settings settings = Settings.builder().put("cluster.name","haijines").build();

//创建访问es服务器的客户端

TransportClient client = new PreBuiltTransportClient(settings)

.addTransportAddress(new TransportAddress(InetAddress.getByName("192.168.42.160"),9300));

QueryBuilder query = QueryBuilders.termQuery("age", 20);

AggregationBuilder agg = AggregationBuilders.filter("filter", query);

SearchResponse response = client.prepareSearch("lib3")

.addAggregation(agg)

.execute().actionGet();

Filter filter = response.getAggregations().get("filter"); 

System.out.println(filter.getDocCount());


}

//range聚合

@Test

public void testRange() throws IOException, InterruptedException, ExecutionException {

//指定ES集群

Settings settings = Settings.builder().put("cluster.name","haijines").build();

//创建访问es服务器的客户端

TransportClient client = new PreBuiltTransportClient(settings)

.addTransportAddress(new TransportAddress(InetAddress.getByName("192.168.42.160"),9300));

AggregationBuilder agg = AggregationBuilders

.range("range")

.field("age")

.addUnboundedTo(50)

.addRange(25,50)

.addUnboundedFrom(25);

SearchResponse response = client.prepareSearch("lib3")

.addAggregation(agg)

.execute().actionGet();

Range r = response.getAggregations().get("range"); 

for(Range.Bucket entry : r.getBuckets()) {

System.out.println(entry.getKey()+":"+entry.getDocCount());

}

}

//missing聚合

@Test

public void testmissing() throws IOException, InterruptedException, ExecutionException {

//指定ES集群

Settings settings = Settings.builder().put("cluster.name","haijines").build();

//创建访问es服务器的客户端

TransportClient client = new PreBuiltTransportClient(settings)

.addTransportAddress(new TransportAddress(InetAddress.getByName("192.168.42.160"),9300));

AggregationBuilder agg = AggregationBuilders

.missing("missing")

.field("price");

SearchResponse response = client.prepareSearch("lib3")

.addAggregation(agg)

.execute().actionGet();

Aggregation aggregation = response.getAggregations().get("missing");

System.out.println(aggregation.toString());

}

你好:我的2025