springboot集成ElasticSearch的查询添加demo

elasticsearch 同时被 2 个专栏收录
5 篇文章 0 订阅
9 篇文章 0 订阅

springBoot集成elasticsearch(下面简称es)有2种实现方案, 一种是基于Jest, 另一种是基于springDataElasticsearch, 我们此次整合采用后者实现。简单实现对es搜索引擎, 添加索引数据, 查询数据等操作。

1、pom中elasticsearch依赖

springboot版本是2.1.8,此本版内部依赖的ES客户端版本是6.4.3,由于前面的安装是7.4.2版本,所以demo依赖的包是7.4.2。

自定义ES版本号,指定下就行:

    <properties>
        <elasticsearch.version>7.4.2</elasticsearch.version>
    </properties>

    <dependencies>
        <!--导入es的elasticsearch-rest-high-level-client 注意查看版本 -->
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>${elasticsearch.version}</version>
        </dependency>
    </dependencies>

导入7.4.2成功


2、ElasticSearch配置


import org.apache.http.HttpHost;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @DESCRIPTION es配置
 * @Author lst
 * @Date 2020-07-25
 * 1、导入依赖
 * 2、编写配置,给容器中注入一个RestHighLevelClient
 * 3、参考文档   https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-high-document-index.html
 */
@Configuration
public class SearchConfig {

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

    @Bean
    public RestHighLevelClient esRestClient() {
        RestClientBuilder builder = RestClient.builder(new HttpHost("127.0.0.1", 9200, "http"));
        return new RestHighLevelClient(builder);
    }
}

3、测试添加数据

 /**
      * 测试存储数据到es,更新也可以
      * @author lst
      * @date 2020-7-25 20:36
      * @param
      * @return void
     */
    @Test
    void addData() throws IOException {
        IndexRequest indexRequest = new IndexRequest("users");
        indexRequest.id("1");
//		indexRequest.source("username", "lubancantfly","age",18,"gender","M");

        User user = new User();
        user.setUsername("lst");
        user.setGender("M");
        user.setAge(18);
        String json = JSON.toJSONString(user);
        //保存的内容
        indexRequest.source(json, XContentType.JSON);

        // 执行操作
        IndexResponse index = client.index(indexRequest, SearchConfig.COMMON_OPTIONS);

        System.out.println(index);
    }

    @Data
    class User{
        private String username;
        private String gender;
        private Integer age;
    }

执行后查看控制台:

在通过kibana控制台查询

4、测试查询数据

由于前面我们已经导入过数据(es批量导入数据),我们做一个聚合分析查询统计,代码如下

 /**
     * 测试给es索引数据
     * #搜索 address中包含mil的所有人的年龄分布以及平均薪资,但不显示这些人的详情。
     */
    @Test
    public void searchData() throws IOException {

        // 创建检索请求
        SearchRequest searchRequest = new SearchRequest();
        // 指定索引
        searchRequest.indices("bank");
        // 构造查询条件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

//		searchSourceBuilder.query();
//		searchSourceBuilder.from();
//		searchSourceBuilder.size();
//		searchSourceBuilder.aggregation();

        searchSourceBuilder.query(QueryBuilders.matchQuery("address", "mill"));

        TermsAggregationBuilder ageAgg = AggregationBuilders.terms("ageAgg").field("age").size(10);
        searchSourceBuilder.aggregation(ageAgg);

        AvgAggregationBuilder avgAgg = AggregationBuilders.avg("avgAgg").field("balance");
        searchSourceBuilder.aggregation(avgAgg);

        System.out.println("检索条件:" +searchSourceBuilder.toString());

        searchRequest.source(searchSourceBuilder);

        // 执行检索
        SearchResponse searchResponse = client.search(searchRequest, SearchConfig.COMMON_OPTIONS);

        // 分析结果
        System.out.println(searchResponse.toString());

//		Map map = JSON.parseObject(searchRequest.toString(), Map.class);

        SearchHits hits = searchResponse.getHits();

        SearchHit[] searchHits = hits.getHits();

        for (SearchHit searchHit : searchHits) {

            String asString = searchHit.getSourceAsString();
            //解析返回数据
            Accout accout = JSON.parseObject(asString, Accout.class);
            System.out.println("当前检索到的数据信息:" + accout);
        }

        // 获取聚合的分析信息
        Aggregations aggregations = searchResponse.getAggregations();

        Terms terms = aggregations.get("ageAgg");

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

            String keyAsString = bucket.getKeyAsString();
            System.out.println("年龄" + keyAsString);
        }

        Avg avg = aggregations.get("avgAgg");
        System.out.println("平均薪资" + avg.getValue());

//		for (Aggregation aggregation : aggregations.asList()) {
//			System.out.println("当前聚合的名字:" + aggregation.getName());
//
//		}
    }

    @Data
    @ToString
    static class Accout {
        private int account_number;
        private int balance;
        private String firstname;
        private String lastname;
        private int age;
        private String gender;
        private String address;
        private String employer;
        private String email;
        private String city;
        private String state;
    }

运行结果

在通过kibana控制台查询

 

 

  • 0
    点赞
  • 3
    评论
  • 1
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

相关推荐
©️2020 CSDN 皮肤主题: 终极编程指南 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值