前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >SpringBoot2.2.X整合ElasricSearch7.8

SpringBoot2.2.X整合ElasricSearch7.8

作者头像
暴躁的程序猿
发布2022-07-12 16:51:13
2600
发布2022-07-12 16:51:13
举报
文章被收录于专栏:阿飞的学习记录

这里默认大家已经掌握es基础语法 es版本为7.8 pom

代码语言:javascript
复制
 <!--引入es-high-level-client的坐标-->
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>7.8.0</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-client</artifactId>
            <version>7.8.0</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>7.8.0</version>
        </dependency>
        <!--ElasticSearch相关结束-->

properties配置文件

代码语言:javascript
复制
# 应用名称
spring.application.name=search
# 应用服务 WEB 访问端口
server.port=12000
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848

配置类

代码语言:javascript
复制
/**
 * @create: 2022/7/2
 * @author: Tony Stark
 */
@Configuration
public class StaticSearchConfig {

    public static final RequestOptions COMMOM_OPTIONS;
    static {
        RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();
        COMMOM_OPTIONS=builder.build();
    }

    @Bean
    public RestHighLevelClient esRestClient(){
        return new RestHighLevelClient(RestClient.builder(
                new HttpHost("localhost",1001,"http")
        ));
    }

}

单元测试

添加数据

代码语言:javascript
复制
    @Autowired
    private RestHighLevelClient esRestClient;
     @Test
    public void testEsClient() throws IOException {
        IndexRequest indexRequest = new IndexRequest();
        indexRequest.id("1");
        indexRequest.index("bank");
        indexRequest.source("username","zhangsan","age",19);
        //添加数据     请求参数使用默认的
        esRestClient.index(indexRequest, RequestOptions.DEFAULT);
    }

检索数据

代码语言:javascript
复制
 /**
     * 检索测试
     * @throws IOException
     */
    @Test
    public void testEsSearch() throws IOException {
        SearchRequest searchRequest = new SearchRequest();
        //指定查询索引
        searchRequest.indices("bank");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        //查询所有address中带有mill的
        builder.query(QueryBuilders.matchQuery("address","mill"));

        //构造聚合条件 terms为聚合条件的名字  根据age聚合  size 显示多少条
        TermsAggregationBuilder aggregationBuilder1 = AggregationBuilders.terms("aggAgg").field("age").size(10);
        //添加聚合条件
        builder.aggregation(aggregationBuilder1);
        //聚合条件二  聚合名称为balanceAvg   根据balance求平均值
        AvgAggregationBuilder aggregationBuilder2 = AggregationBuilders.avg("balanceAvg").field("balance");
        //添加聚合条件二
        builder.aggregation(aggregationBuilder2);
        System.out.println(builder.toString());
        searchRequest.source(builder);
        //执行检索
        SearchResponse searchResponse = esRestClient.search(searchRequest,     StaticSearchConfig.COMMOM_OPTIONS);
        System.out.println(searchResponse);
        //分析结果
            //获取所有查到的数据   所有命中数据  最外层
        SearchHits hits = searchResponse.getHits();
            //获取所有响应数据中的命中数据  内层hits
        SearchHit[] hitsHits = hits.getHits();
        for (SearchHit hitsHit : hitsHits) {
            //遍历每条数据   获取索引
            String index = hitsHit.getIndex();
            long primaryTerm = hitsHit.getPrimaryTerm();
            System.out.println(index +" " +primaryTerm);
//            Map<String, Object> sourceAsMap = hitsHit.getSourceAsMap();
//            Set<Map.Entry<String, Object>> entries = sourceAsMap.entrySet();
//            for (Map.Entry<String, Object> entry : entries) {
//                System.out.println(entry.getKey());
//                System.out.println(entry.getValue());
//            }
            String sourceAsString = hitsHit.getSourceAsString();
           	//Account类为自己创建pojo类
            Account account = JSON.parseObject(sourceAsString, Account.class);
            System.out.println(account);
            //分析聚合结果  获取所有聚合数据
            Aggregations aggregations = searchResponse.getAggregations();
              //根据聚合的名字取出聚合信息
            Terms aggAgg = aggregations.get("aggAgg");
            Avg balanceAvg = aggregations.get("balanceAvg");
            for (Terms.Bucket bucket : aggAgg.getBuckets()) {
                System.out.println("年龄:"+bucket.getKey()+"------->人数:"+bucket.getDocCount());
            }
            System.out.println(balanceAvg.getName()+"平均工资---->"+balanceAvg.getValue());
        }

    }

部分结果

代码语言:javascript
复制
MallSearchApplicationTests.Account(account_number=472, balance=25571, firstname=Lee, lastname=Long, age=32, gender=F, address=288 Mill Street, employer=Comverges, email=leelong@comverges.com, city=Movico, state=MT)
年龄:38------->人数:2
年龄:28------->人数:1
年龄:32------->人数:1
balanceAvg平均工资---->25208.0
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-07-03,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
Elasticsearch Service
腾讯云 Elasticsearch Service(ES)是云端全托管海量数据检索分析服务,拥有高性能自研内核,集成X-Pack。ES 支持通过自治索引、存算分离、集群巡检等特性轻松管理集群,也支持免运维、自动弹性、按需使用的 Serverless 模式。使用 ES 您可以高效构建信息检索、日志分析、运维监控等服务,它独特的向量检索还可助您构建基于语义、图像的AI深度应用。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档