使⽤java实现elasticsearch中的聚合求最⼤值
1.启动elasticsearch
2.启动logstash.由于要计算最⼤值,所以elasticsearch中的second必须是数值类型的,需要在logstash中转换类型:
3.启动kibana
看⼀下之前已经建好的index(wyh-apache-log):
4.使⽤java实现聚合查询得到second最⼤值
4.1创建maven项⽬,pom⽂件:
<dependencies>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>6.6.0</version><!-- 版本号与⾃⼰的elasticsearch版本号⼀致 -->
</dependency>
</dependencies>
4.2编写代码:
package test;
import java.InetAddress;
import java.UnknownHostException;
import java.util.Map;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.ansport.TransportClient;
import org.elasticsearchmon.settings.Settings;
import ansport.TransportAddress;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.s.StringTerms;
import org.elasticsearch.search.s.Terms;
import org.elasticsearch.search.s.TermsAggregationBuilder;
import org.elasticsearch.ics.max.InternalMax;
import org.elasticsearch.ics.max.Max;
import org.elasticsearch.ics.max.MaxAggregationBuilder;
import ansport.client.PreBuiltTransportClient;
public class EsQuery {
public static void main(String[] args) throws UnknownHostException {
//对elasticsearch设置属性,此处只设置了集名称,如果有对个属性,就继续在后⾯.put()添加即可
Settings settings = Settings.builder().put("cluster.name", "wyh-cluster").build();
TransportClient client = new PreBuiltTransportClient(settings)
//配置elasticsearch服务ip及端⼝号。客户端连接的端⼝号是9300
.addTransportAddress(new ByName("192.168.184.128"), 9300));
java中index是什么意思
System.out.println(client);
//由于是聚合,这⾥使⽤的是AggregationBuilder。maxSecond是⾃⼰定义的给查询出来的最⼤值起的名字,second是elasticsearch中的index⾥⾯我们放进去的数据  AggregationBuilder builder = AggregationBuilders.max("maxSecond").field("second");
//prepareSearch()传⼊要查询的index
SearchResponse response = client.prepareSearch("wyh-apache-log").addAggregation(builder).get();
//从查询结果中获取刚才定义的最⼤值的名称
Max max = Aggregations().get("maxSecond");
System.out.Value());
}
}
4.3运⾏结果:
查看elasticsearch中的数据确实是second最⼤值为180。计算正确。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。