Elasticsearch通过Java客户端API操作文档(四)
  19qMgiCiiRfc 2023年11月05日 52 0

一、添加依赖

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.31</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.83</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

二、application.yml配置

spring:
  jpa:
    show-sql: true
    hibernate:
      ddl-auto: update
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: 123456
    url: jdbc:mysql://127.0.0.1:3306/es?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8&useSSL=false&rewriteBatchedStatements=true&allowPublicKeyRetrieval=true

三、创建数据实体并初始化数据

package com.example.esdemo.entity;

import lombok.Data;

import javax.persistence.*;

/**
 * @author qx
 * @date 2023/10/13
 * @des 商品实体类
 */
@Entity
@Table(name = "t_store")
@Data
public class Store {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    private String address;

}

Elasticsearch通过Java客户端API操作文档(四)_文档

四、新增文档

  1. 创建Request对象
  2. 准备请求参数,也就是DSL中的JSON文档
  3. 发送请求
package com.example.esdemo;

import com.alibaba.fastjson.JSON;
import com.example.esdemo.entity.Store;
import com.example.esdemo.repository.StoreRepository;
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.index.IndexRequest;
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.xcontent.XContentType;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;
import java.util.Optional;

@SpringBootTest
class EsDemoApplicationTests {

    @Autowired
    private StoreRepository storeRepository;

    private RestHighLevelClient client;

    @BeforeEach
    void setUp() {
        // 初始化代码 建立连接
        this.client = new RestHighLevelClient(RestClient.builder(HttpHost.create("http://127.0.0.1:9200")));
    }

    /**
     * 新增文档
     */
    @Test
    void testIndexDocument() throws IOException {
        // 查询商店数据
        Store store = storeRepository.findById(1L).orElse(null);
        String json = JSON.toJSONString(store);

        //1.创建request对象 相当于/myindex/_doc/1
        IndexRequest request = new IndexRequest("myindex").id(String.valueOf(store.getId()));
        // 2.准备Json文档
        request.source(json, XContentType.JSON);
        //3.发送请求
        client.index(request, RequestOptions.DEFAULT);
    }

    @AfterEach
    void tearDown() throws IOException {
        // 结束代码
        this.client.close();
    }

}

执行之后我们在Kibana控制台上调试查询文档的接口。

Elasticsearch通过Java客户端API操作文档(四)_elasticsearch_02

五、查询文档

1. 准备Request对象。这次是查询,所以是GetRequest

2. 发送请求,得到结果。因为是查询,这里调用client.get()方法

3.解析结果,就是对JSON做反序列化

示例代码:

package com.example.esdemo;

import com.alibaba.fastjson.JSON;
import com.example.esdemo.entity.Store;
import com.example.esdemo.repository.StoreRepository;
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
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.xcontent.XContentType;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;
import java.util.Optional;

@SpringBootTest
class EsDemoApplicationTests {

    @Autowired
    private StoreRepository storeRepository;

    private RestHighLevelClient client;

    @BeforeEach
    void setUp() {
        // 初始化代码 建立连接
        this.client = new RestHighLevelClient(RestClient.builder(HttpHost.create("http://127.0.0.1:9200")));
    }


    /**
     * 查询文档
     *
     * @throws IOException
     */
    @Test
    void testGetDocument() throws IOException {
        //1.创建request对象
        GetRequest request = new GetRequest("myindex", "1");
        //2.发送请求,得到数据
        GetResponse response = client.get(request, RequestOptions.DEFAULT);
        // 3.得到结果
        String json = response.getSourceAsString();
        // 4.输出:{"address":"广州天河路","id":1,"name":"大润发"}
        System.out.println(json);
         Store store = JSON.parseObject(json, Store.class);
        //5.输出:Store(id=1, name=大润发, address=广州天河路)
        System.out.println(store);
    }

    @AfterEach
    void tearDown() throws IOException {
        // 结束代码
        this.client.close();
    }

}

六、删除文档

1. 准备Request对象,因为是删除,这次是DeleteRequest对象。要指定索引库名和id

2. 发送请求。因为是删除,所以是client.delete()方法

示例代码:

package com.example.esdemo;

import com.alibaba.fastjson.JSON;
import com.example.esdemo.entity.Store;
import com.example.esdemo.repository.StoreRepository;
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
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.xcontent.XContentType;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;
import java.util.Optional;

@SpringBootTest
class EsDemoApplicationTests {

    @Autowired
    private StoreRepository storeRepository;

    private RestHighLevelClient client;

    @BeforeEach
    void setUp() {
        // 初始化代码 建立连接
        this.client = new RestHighLevelClient(RestClient.builder(HttpHost.create("http://127.0.0.1:9200")));
    }
    /**
     * 删除文档
     *
     * @throws IOException
     */
    @Test
    void testDocument() throws IOException {
        //1.准备request
        DeleteRequest request = new DeleteRequest("myindex", "1");
        //2.发送请求
        client.delete(request, RequestOptions.DEFAULT);
    }

    @AfterEach
    void tearDown() throws IOException {
        // 结束代码
        this.client.close();
    }

}

执行删除文档的测试方法之后,我们在Kibana控制台查询这个文档ID的文档,发现没有找到相关文档数据。

Elasticsearch通过Java客户端API操作文档(四)_文档_03

七、修改文档

1. 准备Request对象。这次是修改,所以是UpdateRequest

2. 准备参数。里面包含要修改的字段

3. 更新文档。这里调用client.update()方法

示例代码:

package com.example.esdemo;

import com.alibaba.fastjson.JSON;
import com.example.esdemo.entity.Store;
import com.example.esdemo.repository.StoreRepository;
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.support.WriteRequest;
import org.elasticsearch.action.update.UpdateRequest;
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.xcontent.XContentType;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@SpringBootTest
class EsDemoApplicationTests {

    @Autowired
    private StoreRepository storeRepository;

    private RestHighLevelClient client;

    @BeforeEach
    void setUp() {
        // 初始化代码 建立连接
        this.client = new RestHighLevelClient(RestClient.builder(HttpHost.create("http://127.0.0.1:9200")));
    }

    /**
     * 修改文档
     * @throws IOException
     */
    @Test
    void testUpdateDocument() throws IOException {
        Store store = storeRepository.findById(1L).orElse(null);
        String json = JSON.toJSONString(store);
        //1.准备request
        UpdateRequest request = new UpdateRequest("myindex","1");
        //2.准备参数
        request.doc(json,XContentType.JSON);
        //3.更新文档
        client.update(request,RequestOptions.DEFAULT);
    }

    @AfterEach
    void tearDown() throws IOException {
        // 结束代码
        this.client.close();
    }

}


【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

推荐阅读
19qMgiCiiRfc