三、RestClient操作索引库与文档

本文介绍了如何使用Elasticsearch官方的RestClient进行索引库的设计、创建、删除及文档操作,包括mappings配置和基本的CRUD操作。

三、RestClient操作索引库与文档

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

官方文档地址: https://www.elastic.co/guide/en/elasticsearch/client/index.html

数据库文件:视频里展示的数据库表可以使用自己有的其他数据替代,不一定非要一致。

自己手敲了个工程项目(包含SQL文件):测试RestClient项目文件

3.1 操作索引库

设计数据表对应的mappings

PUT /movie
{
  "mappings": {
    "properties": {
      "all":{
        "type": "text",
        "analyzer": "ik_max_word"
      },
      "movieId":{
        "type": "keyword"
      },
      "movieTitle":{
        "type": "text",
        "analyzer": "ik_max_word", 
        "copy_to": "all"
      },
      "movieIntroduction":{
        "type": "text",
        "analyzer": "ik_max_word", 
        "copy_to": "all"
      },
      "movieRating":{
        "type": "float"
      },
      "movieReleaseDate":{
        "type": "keyword", 
        "copy_to": "all"
      }
    }
  }
}

引入依赖

<properties>
    <java.version>1.8</java.version>
    <elasticsearch.version>7.12.1</elasticsearch.version>
    <mybatis-plus-boot.version>3.4.2</mybatis-plus-boot.version>
</properties>

<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>7.12.1</version>
</dependency>

初始化

public class MovieIndexTest {
    private RestHighLevelClient client;
    @Test
    void testInit(){
        System.out.println(client);
    }
    @BeforeEach
    void setUp(){
        this.client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://10.120.54.174:9200")
        ));
    }
    @AfterEach
    void close() throws IOException {
        this.client.close();
    }
}

创建movie索引,CREATE_MOVIE 为上面的 mappings

public class MovieIndexTest {
    // ...........
    
    @Test
    void testCreateMovieIndex() throws IOException {
        // 创建Request
        CreateIndexRequest request = new CreateIndexRequest("movie");
        // 准备请求数据
        request.source(CREATE_MOVIE, XContentType.JSON);
        // 发送请求
        client.indices().create(request, RequestOptions.DEFAULT);
    }
    // ...........
}

删除、获取,判断是否存在

public class MovieIndexTest {
	@Test
    void testDelete() throws IOException {
        DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("movie");
        client.indices().delete(deleteIndexRequest,RequestOptions.DEFAULT);
    }
    @Test
    void testExists() throws IOException {
        GetIndexRequest getIndexRequest = new GetIndexRequest("movie");
        boolean exists = client.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
        System.out.println(exists);
    }
    @Test
    void testGet() throws IOException {
        GetIndexRequest getIndexRequest = new GetIndexRequest("movie");
        GetIndexResponse getIndexResponse = client.indices().get(getIndexRequest, RequestOptions.DEFAULT);
        System.out.println(getIndexResponse);
    }
}

3.2 操作文档

【TODO】

结束语

上一篇:二、ElasticSearch中索引库与文档操作

使用RestClient操作Elasticsearch主要分为以下步骤: ### 1. 引入依赖 需要引入es的RestHighLevelClient依赖,示例代码如下: ```xml <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-high-level-client</artifactId> </dependency> ``` 因为SpringBoot默认的ES版本是7.6.2,所以需要覆盖默认的ES版本,示例代码如下: ```xml <properties> <java.version>1.8</java.version> <elasticsearch.version>7.12.1</elasticsearch.version> </properties> ``` ### 2. 初始化RestHighLevelClient 在elasticsearch提供的API中,elasticsearch一切交互都封装在一个名为RestHighLevelClient的类中,必须先完成这个对象的初始化,建立elasticsearch的连接。示例代码如下: ```java import org.apache.http.HttpHost; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; public class ElasticsearchClientConfig { public static RestHighLevelClient getRestHighLevelClient() { RestHighLevelClient client = new RestHighLevelClient( RestClient.builder( new HttpHost("localhost", 9200, "http"))); return client; } } ``` ### 3. 进行具体操作 以下是一些常见操作的示例: #### 创建索引 ```java import org.elasticsearch.action.admin.indices.create.CreateIndexRequest; import org.elasticsearch.action.admin.indices.create.CreateIndexResponse; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestHighLevelClient; import java.io.IOException; public class CreateIndexExample { public static void main(String[] args) throws IOException { RestHighLevelClient client = ElasticsearchClientConfig.getRestHighLevelClient(); CreateIndexRequest request = new CreateIndexRequest("my_index"); CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT); boolean acknowledged = createIndexResponse.isAcknowledged(); System.out.println("Index created: " + acknowledged); client.close(); } } ``` #### 添加文档 ```java import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.common.xcontent.XContentType; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class AddDocumentExample { public static void main(String[] args) throws IOException { RestHighLevelClient client = ElasticsearchClientConfig.getRestHighLevelClient(); Map<String, Object> jsonMap = new HashMap<>(); jsonMap.put("message", "Hello Elasticsearch!"); IndexRequest request = new IndexRequest("my_index") .id("1") .source(jsonMap, XContentType.JSON); IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT); System.out.println("Document added: " + indexResponse.getId()); client.close(); } } ``` #### 查询文档 ```java import org.elasticsearch.action.get.GetRequest; import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestHighLevelClient; import java.io.IOException; public class GetDocumentExample { public static void main(String[] args) throws IOException { RestHighLevelClient client = ElasticsearchClientConfig.getRestHighLevelClient(); GetRequest getRequest = new GetRequest("my_index", "1"); GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT); if (getResponse.isExists()) { String sourceAsString = getResponse.getSourceAsString(); System.out.println("Document content: " + sourceAsString); } else { System.out.println("Document not found"); } client.close(); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值