微服务 分布式搜索引擎 Elastic Search RestAPI
作者:mmseoamin日期:2024-02-22

文章目录

  • ⛄引言
  • 一、RestAPI
    • ⛅导入数据
    • ⏰mapping映射分析
    • ⚡初始化RestClient
    • 二、索引库操作
      • ⌚创建索引库
      • ✒️删除索引库
      • ⚡判断索引库是否存在
      • ⛵小结

        ⛄引言

        本文参考黑马 分布式Elastic search

        Elasticsearch是一款非常强大的开源搜索引擎,具备非常多强大功能,可以帮助我们从海量数据中快速找到需要的内容

        一、RestAPI

        ES官方提供了各种不同语言的客户端,用来操作ES。这些客户端的本质就是组装DSL语句,通过http请求发送给ES。官方文档地址:https://www.elastic.co/guide/en/elasticsearch/client/index.html

        微服务 分布式搜索引擎 Elastic Search RestAPI,在这里插入图片描述,第1张

        ⛅导入数据

        数据结构如下

        CREATE TABLE `tb_hotel` (
            `id` bigint(20) NOT NULL COMMENT '酒店id',
            `name` varchar(255) NOT NULL COMMENT '酒店名称;例:7天酒店',
            `address` varchar(255) NOT NULL COMMENT '酒店地址;例:航头路',
            `price` int(10) NOT NULL COMMENT '酒店价格;例:329',
            `score` int(2) NOT NULL COMMENT '酒店评分;例:45,就是4.5分',
            `brand` varchar(32) NOT NULL COMMENT '酒店品牌;例:如家',
            `city` varchar(32) NOT NULL COMMENT '所在城市;例:上海',
            `star_name` varchar(16) DEFAULT NULL COMMENT '酒店星级,从低到高分别是:1星到5星,1钻到5钻',
            `business` varchar(255) DEFAULT NULL COMMENT '商圈;例:虹桥',
            `latitude` varchar(32) NOT NULL COMMENT '纬度;例:31.2497',
            `longitude` varchar(32) NOT NULL COMMENT '经度;例:120.3925',
            `pic` varchar(255) DEFAULT NULL COMMENT '酒店图片;例:/img/1.jpg',
            PRIMARY KEY (`id`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
        

        数据我放到网盘了,大家可自行获取

        ⏰mapping映射分析

        创建索引库,最关键的是mapping映射,而mapping映射要考虑的信息包括:

        • 字段名
        • 字段数据类型
        • 是否参与搜索
        • 是否需要分词
        • 如果分词,分词器是什么?

          其中:

          • 字段名、字段数据类型,可以参考数据表结构的名称和类型
          • 是否参与搜索要分析业务来判断,例如图片地址,文件地址 就无需参与搜索
          • 是否分词呢要看内容,内容如果是一个整体就无需分词,反之则要分词
          • 分词器,我们可以统一使用 ik_max_word ik分词器最大分词

            以下是酒店的索引库结构

            PUT /hotel
            {
              "mappings": {
                "properties": {
                  "id": {
                    "type": "keyword"
                  },
                  "name":{
                    "type": "text",
                    "analyzer": "ik_max_word",
                    "copy_to": "all"
                  },
                  "address":{
                    "type": "keyword",
                    "index": false
                  },
                  "price":{
                    "type": "integer"
                  },
                  "score":{
                    "type": "integer"
                  },
                  "brand":{
                    "type": "keyword",
                    "copy_to": "all"
                  },
                  "city":{
                    "type": "keyword",
                    "copy_to": "all"
                  },
                  "starName":{
                    "type": "keyword"
                  },
                  "business":{
                    "type": "keyword"
                  },
                  "location":{
                    "type": "geo_point"
                  },
                  "pic":{
                    "type": "keyword",
                    "index": false
                  },
                  "all":{
                    "type": "text",
                    "analyzer": "ik_max_word"
                  }
                }
              }
            }
            

            几个特殊字段说明:

            • location:地理坐标,里面包含精度、纬度
            • all:一个组合字段,其目的是将多字段的值 利用copy_to合并,提供给用户搜索

              地理坐标 说明:

              微服务 分布式搜索引擎 Elastic Search RestAPI,在这里插入图片描述,第2张

              copy_to说明:

              =微服务 分布式搜索引擎 Elastic Search RestAPI,在这里插入图片描述,第3张

              ⚡初始化RestClient

              在 Elasticsearch 提供的API中,与 Elasticsearch 一切交互都封装在一个名为RestHighLevelClient的类中,必须先完成这个对象的初始化,建立与 Elasticsearch 的连接。

              大概分为3步

              引入ES的RestHighLevelClient依赖

              
                  org.elasticsearch.client
                  elasticsearch-rest-high-level-client
              
              

              SpringBoot 的默认ES版本为7.6.2,覆盖默认的ES版本

              
                  1.8
                  7.12.1
              
              

              初始化RestHighLevelClient

              RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
                      HttpHost.create("http://ip地址:9200")
              ));
              

              为了测试方便,我们新建单元测试进行初始化

              import org.apache.http.HttpHost;
              import org.elasticsearch.client.RestHighLevelClient;
              import org.junit.jupiter.api.AfterEach;
              import org.junit.jupiter.api.BeforeEach;
              import org.junit.jupiter.api.Test;
              public class HoteTest {
                  private RestHighLevelClient client;
                  @BeforeEach
                  void setUp() {
                      this.client = new RestHighLevelClient(RestClient.builder(
                              HttpHost.create("http://192.168.150.101:9200")
                      ));
                  }
                  @AfterEach
                  void tearDown() throws IOException {
                      this.client.close();
                  }
              }
              

              二、索引库操作

              ⌚创建索引库

              创建索引库的API如下:

              微服务 分布式搜索引擎 Elastic Search RestAPI,在这里插入图片描述,第4张

              代码分为三步:

              • 创建Request对象。因为是创建索引库的操作,因此Request是CreateIndexRequest。
              • 添加请求参数,其实就是DSL的JSON参数部分。因为json字符串很长,这里是定义了静态字符串常量MAPPING_TEMPLATE,让代码看起来更加优雅。
              • 发送请求,client.indices()方法的返回值是IndicesClient类型,封装了所有与索引库操作有关的方法。

                创建一个类,定义mapping映射的JSON字符串常量:

                public class HotelEnum {
                    public static final String MAPPING_TEMPLATE = "{\n" +
                            "  \"mappings\": {\n" +
                            "    \"properties\": {\n" +
                            "      \"id\": {\n" +
                            "        \"type\": \"keyword\"\n" +
                            "      },\n" +
                            "      \"name\":{\n" +
                            "        \"type\": \"text\",\n" +
                            "        \"analyzer\": \"ik_max_word\",\n" +
                            "        \"copy_to\": \"all\"\n" +
                            "      },\n" +
                            "      \"address\":{\n" +
                            "        \"type\": \"keyword\",\n" +
                            "        \"index\": false\n" +
                            "      },\n" +
                            "      \"price\":{\n" +
                            "        \"type\": \"integer\"\n" +
                            "      },\n" +
                            "      \"score\":{\n" +
                            "        \"type\": \"integer\"\n" +
                            "      },\n" +
                            "      \"brand\":{\n" +
                            "        \"type\": \"keyword\",\n" +
                            "        \"copy_to\": \"all\"\n" +
                            "      },\n" +
                            "      \"city\":{\n" +
                            "        \"type\": \"keyword\",\n" +
                            "        \"copy_to\": \"all\"\n" +
                            "      },\n" +
                            "      \"starName\":{\n" +
                            "        \"type\": \"keyword\"\n" +
                            "      },\n" +
                            "      \"business\":{\n" +
                            "        \"type\": \"keyword\"\n" +
                            "      },\n" +
                            "      \"location\":{\n" +
                            "        \"type\": \"geo_point\"\n" +
                            "      },\n" +
                            "      \"pic\":{\n" +
                            "        \"type\": \"keyword\",\n" +
                            "        \"index\": false\n" +
                            "      },\n" +
                            "      \"all\":{\n" +
                            "        \"type\": \"text\",\n" +
                            "        \"analyzer\": \"ik_max_word\"\n" +
                            "      }\n" +
                            "    }\n" +
                            "  }\n" +
                            "}";
                }
                

                在hotel-demo中的HotelIndexTest测试类中,编写单元测试,实现创建索引:

                import org.elasticsearch.client.indices.CreateIndexRequest;
                @Test
                void createHotelIndex() throws IOException {
                    // 1.创建Request对象
                    CreateIndexRequest request = new CreateIndexRequest("hotel");
                    // 2.准备请求的参数:DSL语句
                    request.source(MAPPING_TEMPLATE, XContentType.JSON);
                    // 3.发送请求
                    restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
                }
                

                ✒️删除索引库

                删除索引库的DSL语句非常简单:

                DELETE /hotel
                

                与创建索引库相比:

                • 请求方式从PUT变为DELTE
                • 请求路径不变
                • 无请求参数

                  所以代码的差异,注意体现在Request对象上。依然是三步走:

                  • 创建Request对象。这次是DeleteIndexRequest对象
                  • 准备参数。这里是无参
                  • 发送请求。改用delete方法

                    在hotel-demo中的HotelIndexTest测试类中,编写单元测试,实现删除索引:

                    import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
                    @Test
                    void testDeleteHotelIndex() throws IOException {
                        // 1.创建Request对象
                        DeleteIndexRequest request = new DeleteIndexRequest("hotel");
                        // 2.发送请求
                        restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT);
                    }
                    

                    ⚡判断索引库是否存在

                    判断索引库是否存在,本质就是查询,对应的DSL是:

                    GET /hotel
                    

                    DSL查看如下

                    微服务 分布式搜索引擎 Elastic Search RestAPI,在这里插入图片描述,第5张

                    因此与删除的Java代码流程是类似的。依然是三步走:

                    • 创建Request对象。这次是GetIndexRequest对象
                    • 准备参数。这里是无参
                    • 发送请求。改用exists方法
                      import org.elasticsearch.client.indices.GetIndexRequest;
                      @Test
                      void testExistsHotelIndex() throws IOException {
                          // 1.创建Request对象
                          GetIndexRequest request = new GetIndexRequest("hotel");
                          // 2.发送请求
                          boolean exists = restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
                          // 3.输出
                          System.out.println(exists ? "索引库已经存在!" : "索引库不存在!");
                      }
                      

                      小结

                      JavaRestClient操作elasticsearch的流程基本类似。核心是client.indices()方法来获取索引库的操作对象。

                      索引库操作的基本步骤:

                      • 初始化RestHighLevelClient
                      • 创建XxxIndexRequest。XXX是Create、Get、Delete
                      • 准备DSL( Create时需要,其它是无参)
                      • 发送请求。调用RestHighLevelClient#indices().xxx()方法,xxx是create、exists、delete

                        ⛵小结

                        以上就是【Bug 终结者】对 微服务 分布式搜索引擎 Elastic Search RestAPI 的简单介绍,ES搜索引擎无疑是最优秀的分布式搜索引擎,使用它,可大大提高项目的灵活、高效性! 技术改变世界!!!

                        如果这篇【文章】有帮助到你,希望可以给【Bug 终结者】点个赞👍,创作不易,如果有对【后端技术】、【前端领域】感兴趣的小可爱,也欢迎关注❤️❤️❤️ 【Bug 终结者】❤️❤️❤️,我将会给你带来巨大的【收获与惊喜】💝💝💝!