java 连接 Elasticsearch 使用 TransportClient 进行聚合查询

依赖

<!-- org.elasticsearch.client/transport -->
<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)
                    //        TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
                    .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"))
            //18<age<22
            .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);
}
posted @ 2022-03-07 18:04  叕叕666  阅读(92)  评论(0)    收藏  举报