【Elasticsearch】es基础入门-02.RestClient操作索引库

RestClient操作索引库

示例:

一.分析数据结构,写索引库

properties 复制代码
#酒店的mapper
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"
      },
      "star_name":{
        "type":"keyword"
      },
      "business":{
        "type":"keyword",
        "copy_to": "all"
      },
      "location":{
      	#地址坐标数据类型
        "type":"geo_point"
      },
      "pic":{
        "type":"keyword",
        "index": false
      },
      #字段拷贝
      "all":{
        "type": "text",
        "analyzer": "ik_max_word"
      }
    }
  }
}

小知识

(一)地址坐标数据类型

  • geo_point:由纬度(latitude)和经度(longitude)确定的一个点。例如:"32.8752345,120.2981576'

  • geo_shape"有多个geo_point组成的复杂几何图形。例如一条直线,"LINESTRING(-77.03653 38.897676,77.009051 38.889939)"

(二)数据拷贝

使用copy_to属性将当前字段拷贝到指定字段

二.初始化JavaRestClient

(一)引入es的RestHighLevelClient依赖

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

(二)因为SpringBoot默认的ES版本是7.6.2,所以我们需要覆盖默认的ES版本:

java 复制代码
<properties>
	<elasticsearch.version>7.17.21</elasticsearch.version>
</properties>

(三)新建一个测试类,初始化JavaRestClient

java 复制代码
public class HotelIndexTest {
    
    private RestHighLevelClient client;
    
    @Test
    void testInit(){
        System.out.println(client);
    }
    
    /**
     * 在每个测试方法执行前设置测试环境。
     * 该方法初始化一个指向本地Elasticsearch实例的RestHighLevelClient。
     * 这样做是为了确保每个测试都在一个干净的环境中运行,不会相互干扰。
     * 使用@BeforeEach注解确保这个方法在每个测试方法执行前被调用。
     */
    @BeforeEach
    void setUp() {
         // 创建一个新的RestHighLevelClient实例,配置为连接到本地Elasticsearch实例
        client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://192.168.174.129:9200")
        ));
    }
    /**
     * 在每个测试方法执行后关闭HTTP客户端。
     * <p>
     * 此方法使用了JUnit的@AfterEach注解,确保在每个测试方法执行完毕后调用。
     * 它的主要目的是关闭HttpClient实例,以释放资源并避免潜在的资源泄露。
     * 由于HttpClient在多个测试方法中被共享,确保其在每个测试之后正确关闭是很重要的。
     * <p>
     * 方法抛出的IOException被声明为被抛出,但在这个上下文中被忽略。
     * 这是因为关闭客户端可能引发IO异常,但在这个阶段,我们更关心的是确保客户端关闭,
     * 而不是处理可能的异常。如果需要处理这些异常,可以在方法中添加相应的异常处理逻辑。
     *
     * @throws IOException 如果关闭客户端时发生IO异常
     */
    @AfterEach
    void tearDown() throws IOException {
        client.close();
    }
}

运行后,出现如下图结果:

三.使用代码创建索引库

映射模板:MAPPING_TEMPLATE中的内容就是步骤一写的索引库中的内容

java 复制代码
public class HotelIndexConstants {
    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" +
            "      },\n" +
            "      \"starName\": {\n" +
            "        \"type\": \"keyword\"\n" +
            "      },\n" +
            "      \"business\": {\n" +
            "        \"type\": \"keyword\",\n" +
            "        \"copy_to\": \"all\"\n" +
            "      },\n" +
            "      \"pic\": {\n" +
            "        \"type\": \"keyword\",\n" +
            "        \"index\": false\n" +
            "      },\n" +
            "      \"location\": {\n" +
            "        \"type\": \"geo_point\"\n" +
            "      },\n" +
            "      \"all\": {\n" +
            "        \"type\": \"text\",\n" +
            "        \"analyzer\": \"ik_max_word\"\n" +
            "      }\n" +
            "    }\n" +
            "  }\n" +
            "}";
}

测试类

Java 复制代码
@Test
void testCreateIndex() throws IOException {
    // 1.准备Request      PUT /hotel
    CreateIndexRequest request = new CreateIndexRequest("hotel");
    // 2.准备请求参数:DSL参数
    //MAPPING_TEMPLATE静态导入
    request.source(MAPPING_TEMPLATE, XContentType.JSON);
    // 3.发送请求
    client.indices().create(request, RequestOptions.DEFAULT);
}

运行测试类后:

若出现一下报错

properties 复制代码
[hotel/3L_3wWeHTvSZqCkpc7Rdpw] ElasticsearchStatusException[Elasticsearch exception [type=resource_already_exists_exception, reason=index [hotel/3L_3wWeHTvSZqCkpc7Rdpw] already exists]
]

是因为名为hotel的索引库已经存在,更改方法如下:

1.删除索引库

properties 复制代码
#es可视化平台elastic上删除索引库的命令
DELETE /hotel

2.更改测试类中索引库的名称

java 复制代码
	// 1.准备Request      PUT /love
    CreateIndexRequest request = new CreateIndexRequest("love");

四.创建索引库操作的结果

运行后

在es可视化平台elastic上,查看创建的索引库

五.删除索引库

java 复制代码
@Test
void testDeleteIndex() throws IOException {
    // 1.准备Request
    DeleteIndexRequest request = new DeleteIndexRequest("hotel");
    // 3.发送请求
    client.indices().delete(request, RequestOptions.DEFAULT);
}

六.判断索引库是否存在

java 复制代码
@Test
void testExistsIndex() throws IOException {
    // 1.准备Request
    GetIndexRequest request = new GetIndexRequest("hotel");
    // 3.发送请求
    boolean isExists = client.indices().exists(request, RequestOptions.DEFAULT);
	//输出
    System.out.println(isExists ? "存在" : "不存在");
}

先run删除操作,再run判断操作后:

相关推荐
wafrdggh10 小时前
2026电商快递批量查询怎么用?固乔助手模板设置评测
大数据·数据库·小程序
大大大大晴天12 小时前
OLTP、OLAP、数据湖、数据集市、湖仓一体到底是什么关系?
大数据
正在走向自律15 小时前
AI Agent 落地这一年:从“能跑起来”到“敢放出去”
大数据·人工智能·ai agent·智能体·mcp·a2a
freejackman16 小时前
【实战二】字段级血缘追踪:拆解 AST 迷局,精准穿透函数链与子查询
大数据·数据库·sql
goujunwe17 小时前
GEO 内容的“可摘录性”打磨技巧:段落、表格、小标题怎么写,方便大模型提取独立答案块
大数据·人工智能
小田学Python17 小时前
DeepSeek Harness 完整上手指南:安装部署 + 必装插件 + 用一周就回不去的功能
大数据·大模型·agent·ai工具·deepseek
成都蜀味缘餐饮技术培训学校21 小时前
手撕烤兔技术培训实战指南,秘制腌料配方比例与调制手法
大数据·经验分享·笔记·其他·微信公众平台
roman_日积跬步-终至千里21 小时前
AI 能让一个人成为团队吗?从数据中台到 OPC,重新理解软件工程能力
大数据·人工智能·软件工程
演艺大赏1 天前
NiFi 数据流实战:FTP→HDFS 与 CSV→Parquet,附坏数据、漏文件与双写
大数据
数字新视界1 天前
动环监控信创适配在智能机房管理中的应用价值与未来展望
大数据·服务器·数据库·动环监控系统·动力与环境监控系统