[ElasticSearch] RestAPI

发布于:2025-06-06 ⋅ 阅读:(21) ⋅ 点赞:(0)

🌸个人主页:https://blog.csdn.net/2301_80050796?spm=1000.2115.3001.5343
🏵️热门专栏:
🧊 Java基本语法(97平均质量分)https://blog.csdn.net/2301_80050796/category_12615970.html?spm=1001.2014.3001.5482
🍕 Collection与数据结构 (93平均质量分)https://blog.csdn.net/2301_80050796/category_12621348.html?spm=1001.2014.3001.5482
🧀线程与网络(97平均质量分) https://blog.csdn.net/2301_80050796/category_12643370.html?spm=1001.2014.3001.5482
🍭MySql数据库(96平均质量分)https://blog.csdn.net/2301_80050796/category_12629890.html?spm=1001.2014.3001.5482
🍬算法(97平均质量分)https://blog.csdn.net/2301_80050796/category_12676091.html?spm=1001.2014.3001.5482
🍃 Spring(97平均质量分)https://blog.csdn.net/2301_80050796/category_12724152.html?spm=1001.2014.3001.5482
🎃Redis(97平均质量分)https://blog.csdn.net/2301_80050796/category_12777129.html?spm=1001.2014.3001.5482
🐰RabbitMQ(97平均质量分) https://blog.csdn.net/2301_80050796/category_12792900.html?spm=1001.2014.3001.5482
💻 项目总结(97平均质量分) https://blog.csdn.net/2301_80050796/category_12936070.html?spm=1001.2014.3001.5482
🎈JVM(97平均质量分) https://blog.csdn.net/2301_80050796/category_12976744.html?spm=1001.2014.3001.5482
🔍ElasticSearch(96平均质量分) https://blog.csdn.net/2301_80050796/category_12978995.html?spm=1001.2014.3001.5482
感谢点赞与关注~~~

在这里插入图片描述

1. RestAPI

ES官方提供了各种不同语言的客户端,用来操作ES。这些客户端的本质就是组装DSL语句,通过http请求发送给ES
由于ES目前最新版本是8.8,提供了全新版本的客户端,老版本的客户端已经被标记为过时.而我们采用的是7.12版本,因此只能使用老版本的客户端:
在这里插入图片描述
选择7.12版本,HighLevelRestClient版本:
在这里插入图片描述

1.1 初始化RestClient

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

  1. 在item-service模块中引入es的RestHighLevelClient依赖:
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
</dependency>
  1. 因为SpringBoot默认的版本是7.17.10,所以我们需要覆盖默认的es版本:
<properties>
    <maven.compiler.source>11</maven.compiler.source>
    <maven.compiler.target>11</maven.compiler.target>
    <elasticsearch.version>7.12.1</elasticsearch.version>
</properties>
  1. 初始化RestHighLevelClient:
    初始化的代码如下,也就是与本地的es服务器建立连接.
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
        HttpHost.create("http://192.168.150.101:9200")
));

这里为了单元测试方便,我们创建一个测试类IndexTest,然后将初始化的代码编写在@BeforeEach方法中:

package com.hmall.item.es;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.io.IOException;

public class IndexTest {

    private RestHighLevelClient client;

    @BeforeEach
    void setUp() {
        this.client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://192.168.150.101:9200")
        ));
    }

    @Test
    void testConnect() {
        System.out.println(client);
    }

    @AfterEach
    void tearDown() throws IOException {
        this.client.close();
    }
}

1.2 创建索引库

由于要实现对商品搜索,所以我们需要将商品添加到Elasticsearch中,不过需要根据搜索业务的需求来设定索引库结构,而不是一股脑把MySQL的数据写入es.

1.2.1 Mapping映射

搜索页面的效果如图所示:
在这里插入图片描述
实现搜索功能需要的字段包括三大部分:

  • 搜索过滤字段
    • 分类
    • 品牌
    • 价格
  • 排序字段
    • 默认: 按照更新时间降序排序
    • 销量
    • 价格
  • 展示字段
    • 商品id:用于点击后跳转
    • 图片地址
    • 是否是广告推广商品
    • 名称
    • 价格
    • 评价数量
    • 销量

对应的商品表结构如下,索引库无关字段已经划掉:
在这里插入图片描述
结合数据库表结构,以上字段对应的Mapping字段映射属性如下,主要需要关注,该字段的类型,是否参与搜索(是否建立索引),是否需要分词(需要使用哪种分词器).

因此,最终我们的索引库文档结构应该是这样的:

PUT /items
{
  "mappings": {
    "properties": {
      "id": {
        "type": "keyword"
      },
      "name":{
        "type": "text",
        "analyzer": "ik_max_word"
      },
      "price":{
        "type": "integer"
      },
      "stock":{
        "type": "integer"
      },
      "image":{
        "type": "keyword",
        "index": false
      },
      "category":{
        "type": "keyword"
      },
      "brand":{
        "type": "keyword"
      },
      "sold":{
        "type": "integer"
      },
      "commentCount":{
        "type": "integer",
        "index": false
      },
      "isAD":{
        "type": "boolean"
      },
      "updateTime":{
        "type": "date"
      }
    }
  }
}

这里需要注意一下几点:

  • es中的id字段一般不建议用long,而是使用keyword,因为keyword虽然是字符串的一种,但是他代表的是精确匹配值,id字段通常就是用来精确匹配的,而long数据类型更适合范围查询.
  • 需要分词的字符串的数据类型为text,代表可分词的文本.

1.2.2 创建索引

创建索引库的API如下:
在这里插入图片描述
代码分为三步:

  1. 创建Request对象.因为是创建索引库的操作,因此Request是CreateIndexRequest.
  2. 添加请求参数.其实就是json格式的Mapping映射参数,因为json字符串很长,这里值定义了静态字符串常量MAPPING_TEMPLATE,让代码看起来更加优雅.
  3. 发送请求.client.indices()方法的返回值是IndicesClient类型,封装了所有索引库操作有关的方法,例如创建索引,删除索引,判断索引是否存在.

在Item-service中的IndexTest测试类中,具体代码如下:

@Test
void testCreateIndex() throws IOException {
    // 1.创建Request对象
    CreateIndexRequest request = new CreateIndexRequest("items");
    // 2.准备请求参数
    request.source(MAPPING_TEMPLATE, XContentType.JSON);
    // 3.发送请求
    client.indices().create(request, RequestOptions.DEFAULT);
}

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" +
            "      },\n" +
            "      \"price\":{\n" +
            "        \"type\": \"integer\"\n" +
            "      },\n" +
            "      \"stock\":{\n" +
            "        \"type\": \"integer\"\n" +
            "      },\n" +
            "      \"image\":{\n" +
            "        \"type\": \"keyword\",\n" +
            "        \"index\": false\n" +
            "      },\n" +
            "      \"category\":{\n" +
            "        \"type\": \"keyword\"\n" +
            "      },\n" +
            "      \"brand\":{\n" +
            "        \"type\": \"keyword\"\n" +
            "      },\n" +
            "      \"sold\":{\n" +
            "        \"type\": \"integer\"\n" +
            "      },\n" +
            "      \"commentCount\":{\n" +
            "        \"type\": \"integer\"\n" +
            "      },\n" +
            "      \"isAD\":{\n" +
            "        \"type\": \"boolean\"\n" +
            "      },\n" +
            "      \"updateTime\":{\n" +
            "        \"type\": \"date\"\n" +
            "      }\n" +
            "    }\n" +
            "  }\n" +
            "}";

1.3 删除索引库

删除索引库的请求非常简单

DELETE /hotel

与创建索引库相比:

  • 请求方式动put变成了delete
  • 请求路径不变
  • 无请求参数

所以代码的差异,注意体现在Request对象上,流程号如下:

  • 创建Request对象,这次deleteIndexRequest对象
  • 准备参数,这里是无参,因此省略
  • 发送请求,改用delete方法.
@Test
void testDeleteIndex() throws IOException {
    // 1.创建Request对象
    DeleteIndexRequest request = new DeleteIndexRequest("items");
    // 2.发送请求
    client.indices().delete(request, RequestOptions.DEFAULT);
}

1.4 判断索引库是否存在

判断索引库是否存在,本质就是查询,对应的请求语句是:

GET /hotel

因此与删除的java代码流程是类似的,流程如下:

  • 创建Request对象,这次是getIndexRequest对象
  • 准备参数,这里是无参,可以直接省略
  • 发送请求,改用exists方法
@Test
void testExistsIndex() throws IOException {
    // 1.创建Request对象
    GetIndexRequest request = new GetIndexRequest("items");
    // 2.发送请求
    boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
    // 3.输出
    System.err.println(exists ? "索引库已经存在!" : "索引库不存在!");
}

1.5 总结

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

  • 初始化RestHighLevelClient
  • 创建XxxIndexReques.XXX是Create,get,delete
  • 准备请求参数(Create时需要,其他是无参,可以省略).
  • 发送请求,调用RestHighLevelClient.indices().xxx()方法,xxx是createexistsdelete.

2. RestClient操作文档

索引库准备好以后,就可以操作文档了,为了与索引库操作分离,我们再次创建了一个测试类,做两件事情:

  • 初始化RestHighLevelClient
  • 我们的商品数据在数据库,需要利用IHotelService去查询,所以注入这个接口
package com.hmall.item.es;

import com.hmall.item.service.IItemService;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;

@SpringBootTest(properties = "spring.profiles.active=local")
public class DocumentTest {

    private RestHighLevelClient client;
    @Autowired
    private IItemService itemService;

    @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();
    }
}

2.1 新增文档

我们需要将数据库中的商品信息导入elasticSearch中,而不是造假数据.

2.1.1 实体类

索引库结构与数据库结构还存在一些差异,因此我们要定义一个索引库结构对应的实体.
service模块的com.mall.item.domain.dto包中定义一个新的DTO.在我们向es中插入文档的时候,使用的就是这个实体类来进行插入的.

package com.hmall.item.domain.po;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.time.LocalDateTime;

@Data
@ApiModel(description = "索引库实体")
public class ItemDoc{

    @ApiModelProperty("商品id")
    private String id;

    @ApiModelProperty("商品名称")
    private String name;

    @ApiModelProperty("价格(分)")
    private Integer price;

    @ApiModelProperty("商品图片")
    private String image;

    @ApiModelProperty("类目名称")
    private String category;

    @ApiModelProperty("品牌名称")
    private String brand;

    @ApiModelProperty("销量")
    private Integer sold;

    @ApiModelProperty("评论数")
    private Integer commentCount;

    @ApiModelProperty("是否是推广广告,true/false")
    private Boolean isAD;

    @ApiModelProperty("更新时间")
    private LocalDateTime updateTime;
}

2.1.2 API语法

新增文档的请求语法如下:

POST /{索引库名}/_doc/1
{
    "name": "Jack",
    "age": 21
}

对应的javaAPI如下:
在这里插入图片描述
可以看到与索引库操作的API非常类似,同样是三步走:

  • 创建Request对象,这里是IndexRequest,因为添加文档就是创建倒排索引的过程.
  • 准备请求参数,本例中就是json文档
  • 发送请求

变化的地方在于,这里直接使用client.xxx()的API,不在需要client.indices()了.其中上面的新增数据使用的是Index方法.

2.1.3 完整代码

我们导入商品数据,除了参考API模版"三步走"以外,还需要做几点准备工作:

  • 商品数据来自于数据库,我们需要先查询出来,得到Item对象
  • Item对象需要转为itemDoc对象.
  • ItemDTO需要序列化为json格式.

因此,代码整体步骤如下:

  • 根据id查询商品数据item
  • 将item封装为itemDoc
  • 将itemDoc序列化为json
  • 创建IndexRequest,指定索引库名和id
  • 准备请求参数,也就是json文档
  • 发送请求

item-servicedocumentTest测试类中,编写单元测试:

@Test
void testAddDocument() throws IOException {
    // 1.根据id查询商品数据
    Item item = itemService.getById(100002644680L);
    // 2.转换为文档类型
    ItemDoc itemDoc = BeanUtil.copyProperties(item, ItemDoc.class);
    // 3.将ItemDTO转json
    String doc = JSONUtil.toJsonStr(itemDoc);

    // 1.准备Request对象
    IndexRequest request = new IndexRequest("items").id(itemDoc.getId());
    // 2.准备Json文档
    request.source(doc, XContentType.JSON);
    // 3.发送请求
    client.index(request, RequestOptions.DEFAULT);
}

2.2 查询文档

我们以根据id查询文档为例

2.2.1 语法说明

查询的请求语法如下:

GET /{索引库名}/_doc/{id}

与之前的流程类似,代码大概分为2步:

  • 创建Request对象
  • 准备请求参数,这里是无参,直接省略
  • 发送请求

不过查询的目的是得到结果,解析为ItemDTO,还需要加一部对结果的解析.示例如下:
在这里插入图片描述
可以看到,响应结果是一个json,其中文档放在一个_source属性中,因此解析就是拿到_source,反序列化为java对象即可.

其他的代码与之前类似,流程如下:

  • 准备Request对象,这次是查询,所以是GetRequest
  • 发送请求,得到结果,因为是查询,这里调用client.get()方法
  • 解析结果,就是对json做反序列化

2.2.2 完整代码

Item_serviceDocumentTest测试类中,编写单元测试:

@Test
void testGetDocumentById() throws IOException {
    // 1.准备Request对象
    GetRequest request = new GetRequest("items").id("100002644680");
    // 2.发送请求
    GetResponse response = client.get(request, RequestOptions.DEFAULT);
    // 3.获取响应结果中的source
    String json = response.getSourceAsString();
    
    ItemDoc itemDoc = JSONUtil.toBean(json, ItemDoc.class);
    System.out.println("itemDoc= " + ItemDoc);
}

2.3 删除文档

删除的请求语句如下:

DELETE /hotel/_doc/{id}

与查询相比,仅仅是请求方式从delete变成get,可以想象java代码应该依然是2步走:

  • 准备Request对象,因为是删除,这次是deleteRequest对象,要指定索引库名和id
  • 准备参数,无参,直接省略
  • 发送请求,因为是删除,所以是client.delete()方法.

item-serviceDocumentTest测试类中,编写单元测试:

@Test
void testDeleteDocument() throws IOException {
    // 1.准备Request,两个参数,第一个是索引库名,第二个是文档id
    DeleteRequest request = new DeleteRequest("item", "100002644680");
    // 2.发送请求
    client.delete(request, RequestOptions.DEFAULT);
}

2.4 修改文档

修改我们讲过两种方式:

  • 全量修改: 本质是先根据id删除,再新增
  • 局部修改: 修改文档中的指定字段值

在RestClient的API中,全量修改与新增的API完全一致,判断依据是ID:

  • 如果新增时,ID已经存在,则修改.
  • 如果新增时,ID不存在,则新增.

这里不再赘述,我们主要关注局部修改的API即可.

2.4.1 语法说明

局部修改的请求语法如下:

POST /{索引库名}/_update/{id}
{
  "doc": {
    "字段名": "字段值",
    "字段名": "字段值"
  }
}

代码示例如图:
在这里插入图片描述
与之前类似,也是三步走:

  • 准备Request对象,这次是修改,所以是updateRequest
  • 准备参数,也就是json文档,里面包含要修改的字段
  • 更新文档,这里调用client.update()方法.

2.4.2 完整代码

item-serviceDocumentTest测试类中,编写单元测试:

@Test
void testUpdateDocument() throws IOException {
    // 1.准备Request
    UpdateRequest request = new UpdateRequest("items", "100002644680");
    // 2.准备请求参数
    request.doc(
            "price", 58800,
            "commentCount", 1
    );
    // 3.发送请求
    client.update(request, RequestOptions.DEFAULT);
}

需要注意的一点是,doc方法中的参数之间用,隔开.

2.5 批量导入文档

在之前的案例中,我们都是操作单个文档,而数据库中的商品数据实际会达到数十万条, 某些项目可能达到数百万条.
我们如果要将这些数据导入索引库,肯定不能逐条插入,而是采用批处理的方式,我们一般利用javaAPI实现批量导入.

2.5.1 语法说明

批处理与前面将的文档的CRUD步骤基本一致:

  • 创建Request,但是这次用的是BulkRequest
  • 准备请求参数
  • 发送请求,这次要用到client.bulk()方法.

BulkRequest本身其实并没有请求参数,其本质就是将多个普通的CRUD请求组合在一起发送,例如:

  • 批量新增文档,就是给每个文档创建一个IndexRequest请求,然后封装到BulkRequest中,一起发出.
  • 批量删除,就是创建N个DeleteRequest请求,然后封装到BulkRequest一起发出.

因此BulkRequest中提供了add方法,用以添加其他的CRUD的请求:
在这里插入图片描述
可以看到,能添加的请求有:

  • IndexRequest,也就是新增
  • UpdateRequest,也就是修改
  • DeletRequest,也就是删除

因此Bulk中添加了多个IndexRequest,就是批量新增功能了,示例:

@Test
void testBulk() throws IOException {
    // 1.创建Request
    BulkRequest request = new BulkRequest();
    // 2.准备请求参数
    request.add(new IndexRequest("items").id("1").source("json doc1", XContentType.JSON));
    request.add(new IndexRequest("items").id("2").source("json doc2", XContentType.JSON));
    // 3.发送请求
    client.bulk(request, RequestOptions.DEFAULT);
}

2.6 小结

文档操作的基本步骤:

  • 初始化RestHighLevelClient
  • 创建XxxRequest
    • XXX是Index、Get、Update、Delete、Bulk
  • 准备参数
  • 发送请求
    • 调用RestHighLevelClient#.xxx()方法,xxx是index、get、update、delete、bulk
  • 解析结果(get时需要)