IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Java知识库 -> ElasticSearch 7.14.0 集成SpringBoot(CURD) -> 正文阅读

[Java知识库]ElasticSearch 7.14.0 集成SpringBoot(CURD)

ES集成SpringBoot入门

环境:
jdk1.8
maven
es7.14.0
elasticsearch-head

添加需要依赖

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.2</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.elasticsearch/elasticsearch -->
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>7.14.0</version>
        </dependency>

        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>7.14.0</version>
        </dependency>
        <!-- junit单元测试 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <version>2.5.3</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.75</version>
        </dependency>
    </dependencies>

添加YAML文件

#当前 ES 配置信息
ESConfig:
  hostName: 127.0.0.1
  port: 9200
  scheme: http

创建配置类ESConfig

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

@Configuration
public class ESConfig {
    @Value("${ESConfig.hostName}")
    private String hostName;

    @Value("${ESConfig.port}")
    private Integer port;

    @Value("${ESConfig.scheme}")
    private String scheme;

    //给容器中注入一个RestHighLevelClient
    @Bean
    public RestHighLevelClient restHighLevelClient() {
        RestClientBuilder builder = RestClient.builder(
                new HttpHost(hostName, port, scheme)
                //能够加入多个实现集群配置
        );
        return new RestHighLevelClient(builder);
    }
}

创建实体类

public class User {
    //id
    private Integer uuid;
    //名称
    private String name;
    //年龄
    private String age;
    //分组
    private String group;
    //部门
    private String department;
    //简介
    private String synopsis;

    public Integer getUuid() {
        return uuid;
    }

    public void setUuid(Integer uuid) {
        this.uuid = uuid;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public String getGroup() {
        return group;
    }

    public void setGroup(String group) {
        this.group = group;
    }

    public String getDepartment() {
        return department;
    }

    public void setDepartment(String department) {
        this.department = department;
    }

    public String getSynopsis() {
        return synopsis;
    }

    public void setSynopsis(String synopsis) {
        this.synopsis = synopsis;
    }

    @Override
    public String toString() {
        return "User{" +
                "uuid=" + uuid +
                ", name='" + name + '\'' +
                ", age='" + age + '\'' +
                ", group='" + group + '\'' +
                ", department='" + department + '\'' +
                ", synopsis='" + synopsis + '\'' +
                '}';
    }
}

基本环境已经搭建完成了
测试

创建索引/创建文档

    @Autowired
    private RestHighLevelClient restHighLevelClient;
    
    /**
     * 创建索引
     */
    @Test
    public void testCreateIndex() throws IOException {
        IndexRequest request = new IndexRequest();
        //索引名称
        request.index("user_info");
        //为索引添加文档   (能够直接创建索引,也能创建索引的同时为索引创建文档)

        User user = new User() {{
            setUuid(1);
            setGroup("group_1");
            setDepartment("department_1");
            setName("张三");
            setSynopsis("我是: 张三 用户");
        }};
        request.source(JSON.toJSONString(user), XContentType.JSON);
        //创建索引
        restHighLevelClient.index(request, RequestOptions.DEFAULT);
    }

这时候我们es(后面统一使用es代替elasticsearch)-head中就已经创建好了
数据也同时插入进来了
在这里插入图片描述
在这里插入图片描述
查看文档

    /**
     * 查看文档
     */
    @Test
    public void testFindIndexData() throws IOException {
        GetRequest request = new GetRequest("user_info");
        //可以自己添加一个id值,不然的话es中会自己给你设置
        request.id("qxsZVHsBEQL2UMQUpBFa");
        GetResponse getResponse = restHighLevelClient.get(request, RequestOptions.DEFAULT);
        User user = JSON.parseObject(getResponse.getSourceAsString(), User.class);
        System.out.println(user);
    }

这时候我们就能够在控制台看到我们插入的数据
在这里插入图片描述

删除文档

    /**
     * 删除文档
     * @throws
     */
    @Test
    public void testDeleteIndexData() throws IOException {
        DeleteRequest request = new DeleteRequest("user_info");
        request.id("qxsZVHsBEQL2UMQUpBFa");
        restHighLevelClient.delete(request, RequestOptions.DEFAULT);
    }

当执行删除文档后,在调用上面查询的test会发现为空

ES集成SpringBoot查询

根据条件查询索引中数据

    /**
     * 获取user_info索引中数据
     */
    @Test
    public void testSearchData() throws IOException {
        SearchRequest searchRequest = new SearchRequest();
        searchRequest.indices("user_info");
        
        BoolQueryBuilder query = QueryBuilders.boolQuery();
        //查询所有数据
        query.filter(QueryBuilders.matchAllQuery());
        //查询condition中为value的数据	
		//query.filter(QueryBuilders.matchQuery("condition", "value"));
		//查询time中beginTime至endTime中的数据
		/*query.must(QueryBuilders.rangeQuery("time").format("strict_date_optional_time")
                .gte(beginTime).lte(endTime));*/
        //还有就不举例子了
		
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(query);
        
        searchRequest.source(sourceBuilder);
        SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        SearchHits hits = response.getHits();
        for (SearchHit hit : hits) {
            User user = JSON.parseObject(hit.getSourceAsString(), User.class);
            System.out.println(user);
        }
    }

根据条件匹配数据


    @Test
    public void testSearchData() throws IOException {
        SearchRequest searchRequest = new SearchRequest();
        searchRequest.indices("user_info");

        BoolQueryBuilder query = QueryBuilders.boolQuery();
        query.filter(QueryBuilders.matchAllQuery());

        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(query);

        searchRequest.source(sourceBuilder);
        SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        SearchHits hits = response.getHits();
        for (SearchHit hit : hits) {
            User user = JSON.parseObject(hit.getSourceAsString(), User.class);
            System.out.println(user);
        }
    }

ES集成SpringBoot聚合查询

先为接下来查询造点数据

    @Test
    public void testCreateData() throws IOException {
        //创建请求
        IndexRequest request = new IndexRequest("good_pig");
        String[] groups = {"le_1", "le_2", "le_3", "le_4", "le_5"};
        String[] group2s = {"lv_1", "lv_2", "lv_3", "lv_4", "lv_5"};
        for (int i = 1; i < 101; i++) {
            int ran1 = (int) (Math.random() * (5 - 1) + 1);
            int ran2 = (int) (Math.random() * (5 - 1) + 1);
            int finalI = i;
            User user = new User() {{
                setUuid(ran1);
                setGroup(groups[ran1]);
                setDepartment(group2s[ran2]);
                setName("user_" + finalI);
                setSynopsis("我是: " + finalI + " 用户");
            }};
            request.source(JSON.toJSONString(user), XContentType.JSON);
            restHighLevelClient.index(request, RequestOptions.DEFAULT);
        }
    }

实现统计各部门中各组人数

    /**
     * 统计各部门中各组人数
     */
    @Test
    public void testSearchDataT() throws IOException {
        String index = "good_pig";
        String aggregationNameOne = "departmentData";
        String aggregationNameTwo = "departmentData";
        int showSize = 100;

        BoolQueryBuilder query = QueryBuilders.boolQuery();
        query.filter(QueryBuilders.matchAllQuery());

        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(query);

        //添加聚合条件
        AggregationBuilder aggregationBuilder = AggregationBuilders.terms(aggregationNameOne).field("department.keyword")
                .subAggregation(AggregationBuilders.terms(aggregationNameTwo).field("group.keyword").size(showSize))
                .size(showSize);
        sourceBuilder.aggregation(aggregationBuilder);

        SearchRequest request = new SearchRequest();
        request.indices(index);
        request.source(sourceBuilder);

        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        Terms terms1 = response.getAggregations().get(aggregationNameOne);
        for (Terms.Bucket bucket1 : terms1.getBuckets()) {
            Terms terms2 = bucket1.getAggregations().get(aggregationNameTwo);
            for (Terms.Bucket bucket2 : terms2.getBuckets()) {
                System.out.println("部门:" + bucket1.getKeyAsString() + " " + "组:" + bucket2.getKeyAsString() + " " + "数量" + bucket2.getDocCount());
            }
        }
    }
  Java知识库 最新文章
计算距离春节还有多长时间
系统开发系列 之WebService(spring框架+ma
springBoot+Cache(自定义有效时间配置)
SpringBoot整合mybatis实现增删改查、分页查
spring教程
SpringBoot+Vue实现美食交流网站的设计与实
虚拟机内存结构以及虚拟机中销毁和新建对象
SpringMVC---原理
小李同学: Java如何按多个字段分组
打印票据--java
上一篇文章      下一篇文章      查看所有文章
加:2021-08-18 12:34:18  更:2021-08-18 12:35:34 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/23 10:13:10-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码