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

相关推荐
大数据CLUB2 小时前
基于spark的澳洲光伏发电站选址预测
大数据·hadoop·分布式·数据分析·spark·数据开发
ratbag6720132 小时前
当环保遇上大数据:生态环境大数据技术专业的课程侧重哪些领域?
大数据
计算机编程小央姐4 小时前
跟上大数据时代步伐:食物营养数据可视化分析系统技术前沿解析
大数据·hadoop·信息可视化·spark·django·课程设计·食物
智数研析社5 小时前
9120 部 TMDb 高分电影数据集 | 7 列全维度指标 (评分 / 热度 / 剧情)+API 权威源 | 电影趋势分析 / 推荐系统 / NLP 建模用
大数据·人工智能·python·深度学习·数据分析·数据集·数据清洗
潘达斯奈基~5 小时前
《大数据之路1》笔记2:数据模型
大数据·笔记
寻星探路5 小时前
数据库造神计划第六天---增删改查(CRUD)(2)
java·大数据·数据库
翰林小院7 小时前
【大数据专栏】流式处理框架-Apache Fink
大数据·flink
孟意昶8 小时前
Spark专题-第一部分:Spark 核心概述(2)-Spark 应用核心组件剖析
大数据·spark·big data
一路向北North8 小时前
lucene渲染未命中最匹配的关键词和内容
搜索引擎·全文检索·lucene
IT学长编程9 小时前
计算机毕业设计 基于Hadoop的健康饮食推荐系统的设计与实现 Java 大数据毕业设计 Hadoop毕业设计选题【附源码+文档报告+安装调试】
java·大数据·hadoop·毕业设计·课程设计·推荐算法·毕业论文