ES详细使用!Elasticsearch实现索引操作,增删改查,批处理

要想知道ES怎么具体实现对数据的操作,我们首先应该了解一下什么叫做restful编码风格,因为es的具体操作都是restful风格的。

1.RESTful风格

RESTful 是一种软件架构风格,用于创建可扩展的网络服务。它使用 HTTP 方法(如 GET、POST、PUT、DELETE)来执行 CRUD 操作(创建、读取、更新、删除)。RESTful API 通常具有以下特征:

资源导向:所有内容都是资源,每个资源都有唯一的 URI。
无状态:每个请求都是独立的,服务器不存储客户端的状态。
使用标准方法:使用 HTTP 动词来表示操作。
可缓存:响应可以被客户端缓存以提高性能。

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.*;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api/documents")
public class DocumentController {

    private final ElasticsearchClient client;

    public DocumentController() {
        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
        RestClientTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        this.client = new ElasticsearchClient(transport);
    }

    @PostMapping("/{indexName}/{docId}")
    public String addDocument(@PathVariable String indexName, @PathVariable String docId, @RequestBody Map<String, Object> document) throws Exception {
        client.index(i -> i.index(indexName).id(docId).document(document));
        return "Document added.";
    }

    @GetMapping("/{indexName}/{docId}")
    public Map<String, Object> getDocument(@PathVariable String indexName, @PathVariable String docId) throws Exception {
        GetResponse<Map<String, Object>> response = client.get(g -> g.index(indexName).id(docId), Map.class);
        return response.source();
    }

    @DeleteMapping("/{indexName}/{docId}")
    public String deleteDocument(@PathVariable String indexName, @PathVariable String docId) throws Exception {
        client.delete(d -> d.index(indexName).id(docId));
        return "Document deleted.";
    }
}
  • URI 设计:API 路径如 /api/documents/{indexName}/{docId} 用于操作特定索引和文档。
  • HTTP 方法:使用 @PostMapping@GetMapping@DeleteMapping 分别处理创建、读取和删除操作。
  • 依赖注入:通过构造函数创建 Elasticsearch 客户端实例。

2.ES的具体操作

2.1添加具体依赖

 在pom.xml里面添加下面的依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>co.elastic.clients</groupId>
    <artifactId>elasticsearch-java</artifactId>
    <version>8.4.0</version>
</dependency>

2.2控制器代码

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.*;
import co.elastic.clients.elasticsearch.core.bulk.*;
import co.elastic.clients.elasticsearch.indices.*;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class ElasticsearchController {

    private final ElasticsearchClient client;

    public ElasticsearchController() {
        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
        RestClientTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        this.client = new ElasticsearchClient(transport);
    }

    // 创建索引
    @PostMapping("/index/{indexName}")
    public String createIndex(@PathVariable String indexName) throws Exception {
        CreateIndexResponse response = client.indices().create(c -> c.index(indexName));
        return response.acknowledged() ? "Index created." : "Index creation failed.";
    }

    // 删除索引
    @DeleteMapping("/index/{indexName}")
    public String deleteIndex(@PathVariable String indexName) throws Exception {
        DeleteIndexResponse response = client.indices().delete(d -> d.index(indexName));
        return response.acknowledged() ? "Index deleted." : "Index deletion failed.";
    }

    // 添加文档
    @PostMapping("/document/{indexName}/{docId}")
    public String addDocument(@PathVariable String indexName, @PathVariable String docId, @RequestBody Map<String, Object> document) throws Exception {
        client.index(i -> i.index(indexName).id(docId).document(document));
        return "Document added.";
    }

    // 获取文档
    @GetMapping("/document/{indexName}/{docId}")
    public Map<String, Object> getDocument(@PathVariable String indexName, @PathVariable String docId) throws Exception {
        GetResponse<Map<String, Object>> response = client.get(g -> g.index(indexName).id(docId), Map.class);
        return response.source();
    }

    // 删除文档
    @DeleteMapping("/document/{indexName}/{docId}")
    public String deleteDocument(@PathVariable String indexName, @PathVariable String docId) throws Exception {
        client.delete(d -> d.index(indexName).id(docId));
        return "Document deleted.";
    }

    // 批量插入文档
    @PostMapping("/bulk/{indexName}")
    public String bulkInsert(@PathVariable String indexName, @RequestBody List<Map<String, Object>> documents) throws Exception {
        BulkRequest.Builder br = new BulkRequest.Builder();

        for (int i = 0; i < documents.size(); i++) {
            br.operations(op -> op.index(idx -> idx.index(indexName).id(String.valueOf(i)).document(documents.get(i))));
        }

        BulkResponse result = client.bulk(br.build());
        return result.errors() ? "Bulk insert had errors." : "Bulk insert completed.";
    }
}

2.2.1控制器类 

@RestController
@RequestMapping("/api")
public class ElasticsearchController {

 @RestController:标记这个类为一个 RESTful 控制器。
@RequestMapping("/api"):为所有方法定义基础路径 /api。

2.2.2Elasticsearch 客户端初始化

private final ElasticsearchClient client;

public ElasticsearchController() {
    RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
    RestClientTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
    this.client = new ElasticsearchClient(transport);
}

创建一个 ElasticsearchClient 实例,用于与 Elasticsearch 通信。

连接到本地运行的 Elasticsearch 实例(localhost:9200)。 这里的localhost可以修改成服务器地址

2.2.3创建索引

@PostMapping("/index/{indexName}")
public String createIndex(@PathVariable String indexName) throws Exception {
    CreateIndexResponse response = client.indices().create(c -> c.index(indexName));
    return response.acknowledged() ? "Index created." : "Index creation failed.";
}

@PostMapping("/index/{indexName}"):处理 POST 请求,路径中包含索引名称。

使用 client.indices().create() 创建索引。

返回创建结果。

2.2.4删除索引

@DeleteMapping("/index/{indexName}")
public String deleteIndex(@PathVariable String indexName) throws Exception {
    DeleteIndexResponse response = client.indices().delete(d -> d.index(indexName));
    return response.acknowledged() ? "Index deleted." : "Index deletion failed.";
}

 @DeleteMapping("/index/{indexName}"):处理 DELETE 请求,路径中包含索引名称。

使用 client.indices().delete() 删除索引。

返回删除结果。

2.2.5添加文档

@PostMapping("/document/{indexName}/{docId}")
public String addDocument(@PathVariable String indexName, @PathVariable String docId, @RequestBody Map<String, Object> document) throws Exception {
    client.index(i -> i.index(indexName).id(docId).document(document));
    return "Document added.";
}

 @PostMapping("/document/{indexName}/{docId}"):处理 POST 请求,包含索引名称和文档 ID。

@RequestBody Map<String, Object> document:从请求体中获取文档内容。

使用 client.index() 添加文档。

2.2.6获取文档

@GetMapping("/document/{indexName}/{docId}")
public Map<String, Object> getDocument(@PathVariable String indexName, @PathVariable String docId) throws Exception {
    GetResponse<Map<String, Object>> response = client.get(g -> g.index(indexName).id(docId), Map.class);
    return response.source();
}

@GetMapping("/document/{indexName}/{docId}"):处理 GET 请求,路径中包含索引名称和文档 ID。

使用 client.get() 获取文档,返回文档内容。

 2.2.7删除文档

@DeleteMapping("/document/{indexName}/{docId}")
public String deleteDocument(@PathVariable String indexName, @PathVariable String docId) throws Exception {
    client.delete(d -> d.index(indexName).id(docId));
    return "Document deleted.";
}

@DeleteMapping("/document/{indexName}/{docId}"):处理 DELETE 请求,路径中包含索引名称和文档 ID。

使用 client.delete() 删除文档。

2.2.8批量插入文档

@PostMapping("/bulk/{indexName}")
public String bulkInsert(@PathVariable String indexName, @RequestBody List<Map<String, Object>> documents) throws Exception {
    BulkRequest.Builder br = new BulkRequest.Builder();

    for (int i = 0; i < documents.size(); i++) {
        br.operations(op -> op.index(idx -> idx.index(indexName).id(String.valueOf(i)).document(documents.get(i))));
    }

    BulkResponse result = client.bulk(br.build());
    return result.errors() ? "Bulk insert had errors." : "Bulk insert completed.";
}

@PostMapping("/bulk/{indexName}"):处理 POST 请求,路径中包含索引名称。

@RequestBody List<Map<String, Object>> documents:从请求体中获取多个文档。

使用 BulkRequest.Builder 进行批量操作。

返回批量插入结果。

2.3启动类

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ElasticsearchApplication {

    public static void main(String[] args) {
        SpringApplication.run(ElasticsearchApplication.class, args);
    }
}

3.总结

索引操作:使用 POST 和 DELETE 方法创建和删除索引。
文档操作:使用 POST、GET 和 DELETE 方法进行文档的添加、读取和删除。
批处理:通过 POST 方法实现批量插入文档。
依赖注入:通过构造函数创建 Elasticsearch 客户端实例。

  • 7
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Code apprenticeship

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值