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

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

1.RESTful风格

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

资源导向:所有内容都是资源,每个资源都有唯一的 URI。

无状态:每个请求都是独立的,服务器不存储客户端的状态。

使用标准方法:使用 HTTP 动词来表示操作。

可缓存:响应可以被客户端缓存以提高性能。

java 复制代码
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里面添加下面的依赖

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控制器代码

java 复制代码
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控制器类

java 复制代码
@RestController
@RequestMapping("/api")
public class ElasticsearchController {

@RestController:标记这个类为一个 RESTful 控制器。

@RequestMapping("/api"):为所有方法定义基础路径 /api。

2.2.2Elasticsearch 客户端初始化

java 复制代码
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创建索引

java 复制代码
@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删除索引

java 复制代码
@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添加文档

java 复制代码
@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获取文档

java 复制代码
@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删除文档

java 复制代码
@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批量插入文档

java 复制代码
@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启动类

java 复制代码
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 客户端实例。

相关推荐
AI_Auto1 小时前
架构视角看数字化转型|核心架构:大共享平台+小应用,从按需走向适变
大数据·人工智能·架构·制造
小蒋观天下1 小时前
社区AI智能摄像头完整选型指南
大数据·人工智能·安全·计算机视觉·语音识别·ai大模型
AI 思录2 小时前
Prompt 事故档案(八):日常表达被标为“待校准”,AI 的爹味语法从哪里来
大数据·人工智能·算法·prompt·用户体验·ai合规
2601_965742223 小时前
全媒体运营与短视频代运营,两者有什么区别?
大数据·数据结构·人工智能·算法·ai·媒体
anxiao_m4 小时前
2026企业AI数字孪生选型攻略,不同场景对应不同解决方案
大数据·网络·数据库
SelectDB4 小时前
从 ClickHouse 迁移到 Doris:SQL 兼容、同步与验证清单(实战笔记)
大数据·数据库·数据分析
SelectDB4 小时前
Doris 还是 ClickHouse?一张表说清 6 个关键差异(实战笔记)
大数据·数据库·数据分析
DolphinScheduler社区5 小时前
Apache DolphinScheduler 8 月报:权限安全加固,调度补火上线,性能与稳定性持续提升
大数据·安全·开源·apache·任务调度·海豚调度
动恰客流统计5 小时前
传统红外对射客流统计为何逐步淡出主流?准确率与场景限制深度分析
大数据·前端·人工智能
IT毕设梦工厂5 小时前
计算机毕业设计选题推荐:基于大数据的印度上市公司财务指标数据可视化分析|毕业设计选题|计算机毕设|选题推荐|毕设指导|项目定制|源码|高质量项目
大数据·hadoop·python·信息可视化·spark·课程设计·大数据毕设项目