JavaRestClient 客户端初始化+索引库操作

1. 介绍

ES官方提供了各种不同语言的客户端 ,用来操作ES。这些客户端的本质就是组装DSL语句,通过http请求发送给ES。

Elasticsearch目前最新版本是8.0,其java客户端有很大变化。不过大多数企业使用的还是8以下版本


2. 客户端初始化

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

下面就使用黑马商城作为示例进行一个改造

2.1 步骤

2.1.1 导入依赖

在item-service商品模块导入该依赖

代码如下:

XML 复制代码
  <!--ElasticSearch-->
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
        </dependency>

2.1.2 覆盖SpringBoot默认的ES版本

父工程hmall 进行修改,由于SpringBoot 默认的ES版本是**7.17.10**,所以我们需要覆盖默认的ES版本

properties 标签中添加elasticsearch-version7.12.1版本


2.1.3 初始化RestHighLevelClient

写一个单元测试进行连接

写三个方法,分别是初始化、结束、测试连接方法

快捷键生成:按下Alt+Insert生成以上三个方法


启动测试连接方法


3. 索引库操作

在之前写的单元测试中进行索引库操作

代码如下:

java 复制代码
package com.hmall.item.es;

import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.io.IOException;

/*
RestHighLevelClient 客户端初始化  索引库操作 增删查测试
*/
public class ElasticIndexTest {
    private RestHighLevelClient client;

    // 测试连接
    @Test
    void testConnection() {
        System.out.println("client=" + client);
    }

    // 初始化方法
    @BeforeEach
    void setUp() {
        client = new RestHighLevelClient(RestClient.builder(HttpHost.create("http://192.168.115.15:9200")));
    }

    //结束方法
    @AfterEach
    void tearDown() throws IOException {
        if (client != null) {
            client.close();
        }
    }

    //创建索引库
    @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);
    }

    // 查询索引库是否存在
    @Test
    void testGetIndex() throws IOException {
        //1. 准备Request对象
        GetIndexRequest request = new GetIndexRequest("items");
        //2. 发送请求
        boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
        System.out.println("exists======================" + exists);
    }

    //删除索引库
    @Test
    void testDeleteIndex() throws IOException {
        //1. 准备Request对象
        DeleteIndexRequest request = new DeleteIndexRequest("items");
        //2. 发送请求
        AcknowledgedResponse delete = client.indices().delete(request, RequestOptions.DEFAULT);
        System.out.println("delete------------------------->" + delete.isAcknowledged());
    }


    // 索引库映射
    private static final String MAPPING_TEMPLATE = "{\n" +
            "  \"mappings\": {\n" +
            "    \"properties\": {\n" +
            "      \"id\": {\n" +
            "        \"type\": \"keyword\"\n" +
            "      },\n" +
            "      \"name\": {\n" +
            "        \"type\": \"text\",\n" +
            "        \"analyzer\": \"ik_smart\"\n" +
            "      },\n" +
            "      \"price\": {\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" +
            "        \"index\": false\n" +
            "      },\n" +
            "      \"isAD\": {\n" +
            "        \"type\": \"boolean\"\n" +
            "      },\n" +
            "      \"updateTime\": {\n" +
            "        \"type\": \"date\"\n" +
            "      }\n" +
            "    }\n" +
            "  }\n" +
            "}";
}
相关推荐
草莓熊Lotso16 小时前
GCC/G++ 编译器完全指南:从编译流程到进阶用法(附实操案例)
linux·运维·服务器·网络·c++·人工智能·自动化
鸠摩智首席音效师1 天前
linux 系统中 Shutting Down, Restarting, Halting 有什么区别 ?
linux·运维·服务器
CIb0la1 天前
Linux 将继续不支持 HDMI 2.1 实现
linux·运维·服务器
吕了了1 天前
85 微PE吕了了修改版--更新!
运维·windows·电脑·系统
鹿鸣天涯1 天前
Kali Linux 2025.4 发布:桌面环境增强,新增 3 款安全工具
linux·运维·安全
学习&笔记1 天前
MTK(系统篇)user版本无法使用setenforce 0命令关闭selinux权限
linux·运维·服务器
Bdygsl1 天前
Linux(8)—— 进程优先级与环境变量
linux·运维·服务器
吕了了1 天前
87 Windows 系统安装的本质是什么?
运维·windows·电脑·系统
阿里巴巴P8资深技术专家1 天前
docker容器启动报错
运维·docker·容器
杨云龙UP1 天前
MySQL 8.0.x InnoDB 写入链路优化:Redo Log 与 Buffer Pool 扩容与缓冲区调优实战记录-20251029
linux·运维·数据库·sql·mysql