• 7 SpringBoot与Elasticsearch


    目录

    1 Elasticsearch 介绍

    使⽤场景

    相关概念

    详细说明

    2 安装与启动

    启动服务器 

    3 ES基本使⽤

    创建索引

    查询索引

    删除索引

    创建索引并指定分词器

    操作⽂档 

    添加⽂档,有三种⽅式

    查询⽂档 

    条件查询 

    删除⽂档

    修改⽂档(全量更新)

     修改⽂档(部分更新)

     4 springBoot整合ES

    springBoot与⽼版本ES整合步骤

    1.导⼊springboot整合ES的starter坐标

    2.进⾏基础配置 yml

    3.使⽤

    springBoot与新版本ES整合

    1.导⼊springboot整合ES⾼级别客户端的坐标

     2.使⽤编程的形式设置连接的ES服务器,并获取客户端对象

    创建索引(IK分词器)

    添加⽂档:

    批量添加⽂档:

    按id查询⽂档:

    按条件查询⽂档:


    1 Elasticsearch 介绍

    Elaticsearch简称为es,是⼀个开源的可扩展的分布式全⽂检索引擎服务器,它可以近乎实时的存储、检索数据;本身扩展性很好,可以扩展到上百台服务器,处理PB级别的数据。es使⽤Java开发并使⽤Lucene作为其核⼼来实现索引和搜索的功能,它通过简单的RestfulAPI和javaAPI来隐藏Lucene的复杂性,从⽽让全⽂搜索变得简单。

    Elasticsearch官⽹:https://www.elastic.co/cn/products/elasticsearch

    使⽤场景

    • 分布式的搜索引擎

    分布式:Elasticsearch⾃动将海量数据分散到多台服务器上去存储和检索
    搜索:百度、⾕歌,站内搜索

    • 全⽂检索

    提供模糊搜索等⾃动度很⾼的查询⽅式,并进⾏相关性排名,⾼亮等功能

    • 数据分析引擎(分组聚合)

    电商⽹站,最近⼀周笔记本电脑这种商品销量排名top10的商家有哪些?新闻⽹站,最近1个⽉访问量排名top3的新闻板块是哪些

    • 对海量数据进⾏近实时的处理

    海量数据的处理:因为是分布式架构,Elasticsearch可以采⽤⼤量的服务器去存储和检索数据,⾃然⽽然就可以实现海量数据的处理
    近实时:Elasticsearch可以实现秒级别的数据搜索和分析

    相关概念

    索引库[index]-----------------------------------Database 数据库
    类型[type]----------------------------------Table 数据表
    ⽂档[Document]--------------------------Row ⾏
    字段[Field]-------------------------Column 列
    映射[mapping]-------------------表结构

    详细说明

    2 安装与启动

    windows版安装包下载地址:https:// www.elastic.co/cn/downloads/elasticsearch

    下载的安装包是解压缩就能使⽤的zip⽂件,解压缩完毕后会得到如下⽂件

    •  bin⽬录:包含所有的可执⾏命令
    • config⽬录:包含ES服务器使⽤的配置⽂件
    • jdk⽬录:此⽬录中包含了⼀个完整的jdk⼯具包,版本17,当ES升级时,使⽤最新版本的jdk确保不会出现版本⽀持性不⾜的问题
    • lib⽬录:包含ES运⾏的依赖jar⽂件
    • logs⽬录:包含ES运⾏后产⽣的所有⽇志⽂件
    • modules⽬录:包含ES软件中所有的功能模块,也是⼀个⼀个的jar包。和jar⽬录不同,jar⽬录是ES运⾏期间依赖的jar包,modules是ES软件⾃⼰的功能jar包
    • plugins⽬录:包含ES软件安装的插件,默认为空

    启动服务器 

    双击bin目录下的elasticsearch.bat⽂件即可启动ES服务器,默认服务端⼝9200。通过浏览器
    访问http://localhost:9200看到如下信息视为ES服务器正常启动

    8.1及以上版本开启安全验证,访问后会在控制台出现如下问题

    [WARN ][o.e.x.s.t.n.SecurityNetty4HttpServerTransport] [DESKTOP-E5MROJA] received plaintext http traffic on an https channel, closing connection Netty4HttpChannel{localAddress=/[0:0:0:0:0:0:0:1]:9200, remoteAddress=/[0:0:0:0:0:0:0:1]:62537}
    解决方法:

    1.可输入https://127.0.0.1:9200/访问并输入用户名和密码

    2.修改config/elasticsearch.yml文件

    找到:

            xpack.security.enabled: true

            

            xpack.security.http.ssl:
              enabled: true
              keystore.path: certs/http.p12

    修改为false

    并在文件末尾添加以下两句

            http.cors.enabled: true
            http.cors.allow-origin: "*"

    3 ES基本使⽤

            在ES中我们要先创建索引,这个索引的功能⼜点类似于数据库的表,然后将数据添
    加到倒排索引中,添加的数据称为⽂档。所以要进⾏ES的操作要先创建索引,再添
    加⽂档,这样才能进⾏后续的查询操作。
            要操作ES可以通过Rest⻛格的请求来进⾏,也就是说发送⼀个请求就可以执⾏
    ⼀个操作。⽐如新建索引,删除索引这些操作都可以使⽤发送请求的形式来进⾏。        

    创建索引

    使用postman发送put请求,products是索引名称(body里不能有任何数据否则报错)

    http://localhost:9200/products

    发送请求后,看到如下信息即索引创建成功

     {
    "acknowledged": true,
    "shards_acknowledged": true,
    "index": "products"
    }

    重复创建已经存在的索引会出现错误信息,reason属性中描述错误原因 

    查询索引

    使用postman发送get请求,products是索引名称

    http://localhost:9200/products

    查询索引得到索引相关信息,如下 

     如果查询了不存在的索引,会返回错误信息

    删除索引

    使用postman发送delete请求,products是索引名称

    http://localhost:9200/products

     删除所有后,给出删除结果。如果重复删除,会给出错误信息

    创建索引并指定分词器

            前⾯创建的索引是未指定分词器的,可以在创建索引时添加请求参数,设置分词器。⽬前国内较为流⾏的分词器是IK分词器,使⽤前先在下对应的分词器,然后使⽤。IK分词器下载地址:https://github.com/medcl/elasticsearch-analysis-ik/releases
            分词器下载后解压到ES安装⽬录的plugins⽬录中即可,安装分词器后需要重新启动ES服务器。使⽤IK分词器创建索引格式:PUT请求 http://localhost:9200/products

    请求参数如下(注意是json格式的参数)

    {
        "mappings":{                        #定义mappings属性,替换创建索引时对应的mappings属性
            "properties":{                        #定义索引中包含的属性设置
                "id":{                                #设置索引中包含id属性
                    "type":"keyword"                #当前属性可以被直接搜索
                },
                "name":{                        #设置索引中包含name属性
                    "type":"text",                        #当前属性是⽂本信息,参与分词
                    "analyzer":"ik_max_word",                #使⽤IK分词器进⾏分词
                    "copy_to":"all"                                #分词结果拷⻉到all属性中
                },
                "type":{
                    "type":"keyword"
                },
                "description":{
                    "type":"text",
                    "analyzer":"ik_max_word",
                    "copy_to":"all"
                },
                "all":{          #定义属性,⽤来描述多个字段的分词结果集合,当前属性可以参与查询
                    "type":"text",
                    "analyzer":"ik_max_word"
                }
            }
        }
    }

    操作⽂档 

    ⽬前我们已经有了索引了,但是索引中还没有数据,所以要先添加数据,ES中称数据为⽂档,下⾯进⾏⽂档操作。

    添加⽂档,有三种⽅式

    POST请求 http://localhost:9200/products/_doc #使⽤系统⽣成id
    POST请求 http://localhost:9200/products/_create/1 #使⽤指定id
    POST请求 http://localhost:9200/products/_doc/1 #使⽤指定id,不存在创建,存在更新(版本递增)

    ⽂档通过请求参数传递,数据格式json

    查询⽂档 

    GET请求 http://localhost:9200/products/_doc/1 #查询单个⽂档
    GET请求 http://localhost:9200/products/_search #查询全部⽂档

    条件查询 

    GET请求 http://localhost:9200/products/_search?q=name:springboot# q=查询属性名:查询属性值 

    删除⽂档

     DELETE请求 http://localhost:9200/products/_doc/1

    修改⽂档(全量更新)

     PUT请求 http://localhost:9200/products/_doc/1

    ⽂档通过请求参数传递,数据格式json

     修改⽂档(部分更新)

    POST请求 http://localhost:9200/products/_update/1
    ⽂档通过请求参数传递,数据格式json
    {
    "doc":{ #部分更新并不是对原始⽂档进⾏更新,⽽是对原始⽂档
    对象中的doc属性中的指定属性更新
    "name":"springboot" #仅更新提供的属性值,未提供的属性值不参
    与更新操作
    }
    }

     4 springBoot整合ES

    springBoot整合ES的模式有两种,第⼀种模式springBoot收录了ES,但是随着ES版本迭代,新版的ES在springBoot中是没有收录的,需要我们⼿动的整合。

    springBoot与⽼版本ES整合步骤

    1.导⼊springboot整合ES的starter坐标

    
        org.springframework.boot
        spring-boot-starter-data-elasticsearch
    

    2.进⾏基础配置 yml

    配置ES服务器地址,端⼝9200

    spring:
      elasticsearch:
        uris: localhost:9200

    3.使⽤

    springboot整合ES的专⽤客户端接⼝ElasticsearchRestTemplate来进⾏操作 

    1. @SpringBootTest
    2. class Demo10SpringbootEsApplicationTests {
    3. @Autowired
    4. private ElasticsearchRestTemplate template;
    5. @Test
    6. void contextLoads() {
    7. System.out.println(template);
    8. }
    9. }

    上述操作形式是ES早期的操作⽅式,使⽤的客户端被称为Low Level Client,这种客户端操作⽅式性能⽅⾯略显不⾜,于是ES开发了全新的客户端操作⽅式,称为High Level Client。⾼级别客户端与ES版本同步更新,但是springboot最初整合ES的时候使⽤的是低级别客户端,所以企业开发需要更换成⾼级别的客户端模式。

    springBoot与新版本ES整合

     操作步骤如下:

    1.导⼊springboot整合ES⾼级别客户端的坐标

    
        org.elasticsearch.client
        elasticsearch-rest-high-level-client
    
    
        org.projectlombok
        lombok
    
    
    
        com.alibaba
        fastjson
        2.0.9
    

     2.使⽤编程的形式设置连接的ES服务器,并获取客户端对象

    1. @SpringBootTest
    2. class EsApplicationTests {
    3. //声明客户端
    4. private RestHighLevelClient client;
    5. @Test
    6. void contextLoads() {
    7. //初始化客户端
    8. HttpHost host = HttpHost.create("http://localhost:9200");
    9. RestClientBuilder builder = RestClient.builder(host);
    10. client = new RestHighLevelClient(builder);
    11. //创建索引
    12. CreateIndexRequest request = new CreateIndexRequest("products");
    13. try {
    14. client.indices().create(request, RequestOptions.DEFAULT);
    15. client.close();
    16. } catch (IOException e) {
    17. e.printStackTrace();
    18. }
    19. }
    20. }

            ⾼级别客户端操作是通过发送请求的⽅式完成所有操作的,ES针对各种不同的操作,设定了各式各样的请求对象,上例中创建索引的对象是CreateIndexRequest,其他操作也会有⾃⼰专⽤的Request对象。

            当前操作我们发现,⽆论进⾏ES何种操作,第⼀步永远是获取RestHighLevelClient对象,最后⼀步永远是关闭该对象的连接。在测试中可以使⽤测试类的特性去帮助开发者⼀次性的完成上述操作,但是在业务书写时,还需要⾃⾏管理。将上述代码格式转换成使⽤测试类的初始化⽅法和销毁⽅法进⾏客户端对象的维护。

    1. @SpringBootTest
    2. class EsApplicationTests {
    3. //声明客户端
    4. private RestHighLevelClient client;
    5. @BeforeEach//在测试类中每个操作运⾏前运⾏的⽅法
    6. void setUp() {
    7. //初始化客户端
    8. HttpHost host = HttpHost.create("http://localhost:9200");
    9. RestClientBuilder builder = RestClient.builder(host);
    10. client = new RestHighLevelClient(builder);
    11. }
    12. @AfterEach//在测试类中每个操作运⾏后运⾏的⽅法
    13. void tearDown() {
    14. try {
    15. client.close();
    16. } catch (IOException e) {
    17. e.printStackTrace();
    18. }
    19. }
    20. @Test
    21. void contextLoads() {
    22. //创建索引
    23. CreateIndexRequest request = new CreateIndexRequest("products");
    24. try {
    25. client.indices().create(request, RequestOptions.DEFAULT);
    26. } catch (IOException e) {
    27. e.printStackTrace();
    28. }
    29. }
    30. }

    创建索引(IK分词器)

    1. @SpringBootTest
    2. class EsApplicationTests {
    3. //声明客户端
    4. private RestHighLevelClient client;
    5. @BeforeEach//在测试类中每个操作运⾏前运⾏的⽅法
    6. void setUp() {
    7. //初始化客户端
    8. HttpHost host = HttpHost.create("http://localhost:9200");
    9. RestClientBuilder builder = RestClient.builder(host);
    10. client = new RestHighLevelClient(builder);
    11. }
    12. @AfterEach//在测试类中每个操作运⾏后运⾏的⽅法
    13. void tearDown() {
    14. try {
    15. client.close();
    16. } catch (IOException e) {
    17. e.printStackTrace();
    18. }
    19. }
    20. /**
    21. * 使用IK分词器创建索引
    22. */
    23. @Test
    24. void testIK(){
    25. //创建索引
    26. CreateIndexRequest request = new CreateIndexRequest("products");
    27. String jsonStr = "{\n" +
    28. " \"mappings\":{\n" +
    29. " \"properties\":{\n" +
    30. " \"id\":{\n" +
    31. " \"type\":\"keyword\"\n" +
    32. " },\n" +
    33. " \"name\":{\n" +
    34. " \"type\":\"text\",\n" +
    35. " \"analyzer\":\"ik_max_word\",\n" +
    36. " \"copy_to\":\"all\"\n" +
    37. " },\n" +
    38. " \"type\":{\n" +
    39. " \"type\":\"keyword\"\n" +
    40. " },\n" +
    41. " \"description\":{\n" +
    42. " \"type\":\"text\",\n" +
    43. " \"analyzer\":\"ik_max_word\",\n" +
    44. " \"copy_to\":\"all\"\n" +
    45. " },\n" +
    46. " \"all\":{\n" +
    47. " \"type\":\"text\",\n" +
    48. " \"analyzer\":\"ik_max_word\"\n" +
    49. " }\n" +
    50. " }\n" +
    51. " }\n" +
    52. "}";
    53. //给请求对象设置参数
    54. request.source(jsonStr, XContentType.JSON);
    55. try {
    56. client.indices().create(request, RequestOptions.DEFAULT);
    57. } catch (IOException e) {
    58. e.printStackTrace();
    59. }
    60. }
    61. }

    IK分词器是通过请求参数的形式进⾏设置的,设置请求参数使⽤request对象中的source⽅法进⾏设置,⾄于参数是什么,取决于你的操作种类。当请求中需要参数时,均可使⽤当前形式进⾏参数设置。 

    添加⽂档:

    1. @SpringBootTest
    2. class EsApplicationTests {
    3. //声明客户端
    4. private RestHighLevelClient client;
    5. @BeforeEach//在测试类中每个操作运⾏前运⾏的⽅法
    6. void setUp() {
    7. //初始化客户端
    8. HttpHost host = HttpHost.create("http://localhost:9200");
    9. RestClientBuilder builder = RestClient.builder(host);
    10. client = new RestHighLevelClient(builder);
    11. }
    12. @AfterEach//在测试类中每个操作运⾏后运⾏的⽅法
    13. void tearDown() {
    14. try {
    15. client.close();
    16. } catch (IOException e) {
    17. e.printStackTrace();
    18. }
    19. }
    20. /**
    21. * 创建一个文档
    22. */
    23. @Test
    24. void testDoc() throws IOException {
    25. IndexRequest request = new IndexRequest("products").id("5");
    26. String json = "{\n" +
    27. " \"name\":\"goods\",\n" +
    28. " \"type\":\"goods\",\n" +
    29. " \"description\":\"goods\"\n" +
    30. "}";
    31. request.source(json, XContentType.JSON);
    32. client.index(request, RequestOptions.DEFAULT);
    33. }
    34. }

    添加⽂档使⽤的请求对象是IndexRequest,与创建索引使⽤的请求对象不同。 

    批量添加⽂档:

    创建一个实体类

    1. @Data
    2. @AllArgsConstructor
    3. @NoArgsConstructor
    4. public class Products {
    5. private String id;
    6. private String type;
    7. private String name;
    8. private String description;
    9. }

    在测试类

    1. /**
    2. * 批量添加文档
    3. */
    4. @Test
    5. void testBulk() throws IOException {
    6. //模拟数据
    7. List list = new ArrayList<>();
    8. list.add(new Products("6","aaa","bbbb","cccc"));
    9. list.add(new Products("7","ddd","eeee","ffff"));
    10. list.add(new Products("8","ggg","hhhh","iiii"));
    11. //创建一个批量请求对象
    12. BulkRequest bulk = new BulkRequest();
    13. for(Products products:list){
    14. IndexRequest request = new IndexRequest("products").id(products.getId());
    15. String json = JSON.toJSONString(products);
    16. request.source(json,XContentType.JSON);
    17. bulk.add(request);
    18. }
    19. client.bulk(bulk,RequestOptions.DEFAULT);
    20. }

    批量做时,先创建⼀个BulkRequest的对象,可以将该对象理解为是⼀个保存request对象的容器,将所有的请求都初始化好后,添加到BulkRequest对象中,再使⽤BulkRequest对象的bulk⽅法,⼀次性执⾏完毕。

    按id查询⽂档:

    1. /**
    2. * 根据id查询文档
    3. */
    4. @Test
    5. void testById() throws IOException {
    6. GetRequest request = new GetRequest("products","5");
    7. GetResponse response = client.get(request, RequestOptions.DEFAULT);
    8. String json = response.getSourceAsString();
    9. System.out.println(json);
    10. }

    根据id查询⽂档使⽤的请求对象是GetRequest。

    按条件查询⽂档:

    1. /**
    2. * 根据条件查询文档
    3. */
    4. @Test
    5. void testSearch() throws IOException {
    6. //获取条件对象
    7. SearchRequest request = new SearchRequest("products");
    8. //设置文档查询条件
    9. SearchSourceBuilder builder = new SearchSourceBuilder();
    10. builder.query(QueryBuilders.termQuery("name","goods"));
    11. request.source(builder);
    12. //查询操作
    13. SearchResponse response = client.search(request, RequestOptions.DEFAULT);
    14. SearchHits hits = response.getHits();
    15. for(SearchHit hit : hits){
    16. String source = hit.getSourceAsString();
    17. System.out.println(source);
    18. }
    19. }

            按条件查询⽂档使⽤的请求对象是SearchRequest,查询时调⽤SearchRequest对象的termQuery⽅法,需要给出查询属性名,此处⽀持使⽤合并字段,也就是前⾯定义索引属性时添加的all属性。
            与前期进⾏springboot整合redis和mongodb的差别还是蛮⼤的,主要原始就是我们没有使⽤springboot整合ES的客户端对象。⾄于操作,由于ES操作种类过多,所以显得操作略微有点复杂。

    总结

    springboot整合ES步骤
    1. 导⼊springboot整合ES的High Level Client坐标
    2. ⼿⼯管理客户端对象,包括初始化和关闭操作
    3. 使⽤High Level Client根据操作的种类不同,选择不同的Request对象完成
    对应操作

  • 相关阅读:
    第六章:函数(中)
    DHCP的interface(接口),global(全局)配置以及DHCP relay(中继),DHCP snooping,DHCP option
    斯坦福小镇升级版——AI-Town搭建指南
    Base64隐写
    vue3的params传参失效的解决方案state
    LeetCode233数字1的个数-容易理解的组合数学方法
    基于Springboot的数据库初始化工具
    超适合练手的一套JavaWeb项目 (超市后台管理系统)
    连接Google PaLM API, 503错误解决
    linux服务端c++开发工具介绍(vscode版)
  • 原文地址:https://blog.csdn.net/m0_62520968/article/details/126763649