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 客户端实例。

相关推荐
Elasticsearch10 分钟前
使用 FastAPI 的 WebSockets 和 Elasticsearch 来构建实时应用
elasticsearch
我星期八休息23 分钟前
大模型 + 垂直场景:搜索/推荐/营销/客服领域开发新范式与技术实践
大数据·人工智能·python
最初的↘那颗心1 小时前
Flink Stream API - 源码开发需求描述
java·大数据·hadoop·flink·实时计算
白鲸开源2 小时前
收藏!史上最全 Apache SeaTunnel Source 连接器盘点 (2025版),一篇通晓数据集成生态
大数据·数据库·开源
爱疯生活2 小时前
车e估牵头正式启动乘用车金融价值评估师编制
大数据·人工智能·金融
Lx3522 小时前
MapReduce作业调试技巧:从本地测试到集群运行
大数据·hadoop
计算机程序员小杨2 小时前
计算机专业的你懂的:大数据毕设就选贵州茅台股票分析系统准没错|计算机毕业设计|数据可视化|数据分析
java·大数据
BYSJMG3 小时前
计算机大数据毕业设计推荐:基于Spark的气候疾病传播可视化分析系统【Hadoop、python、spark】
大数据·hadoop·python·信息可视化·spark·django·课程设计
励志成为糕手3 小时前
大数据MapReduce架构:分布式计算的经典范式
大数据·hadoop·mapreduce·分布式计算·批处理
计算机毕设残哥3 小时前
大数据毕业设计选题推荐:护肤品店铺运营数据可视化分析系统详解
大数据·信息可视化·课程设计