依赖
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>7.13.3</version>
</dependency>
配置
@Configuration
public class ESConfig {
@Bean
public TransportClient getTransportClient() {
Settings settings = Settings.builder()
.put("cluster.name", "elasticsearch").build();
try {
TransportClient client = new PreBuiltTransportClient(settings)
.addTransportAddress(new TransportAddress(InetAddress.getByName("localhost"), 9300))
.addTransportAddress(new TransportAddress(InetAddress.getByName("localhost"), 9301));
return client;
} catch (UnknownHostException e) {
e.printStackTrace();
}
return null;
}
}
@Autowired
private TransportClient transportClient;
public void aggQuery() throws Exception {
SearchResponse response = transportClient
.prepareSearch("myindex")
.setQuery(QueryBuilders.matchQuery("name","aa"))
.setPostFilter(QueryBuilders.rangeQuery("age").from(18).to(22))
.setFrom(0).setSize(2).setExplain(true)
.addAggregation(AggregationBuilders
.avg("avg_age")
.field("age")
).execute().actionGet();
Aggregations aggregations = response.getAggregations();
Map<String, Aggregation> stringAggregationMap = aggregations.asMap();
System.out.println(stringAggregationMap);
}
|