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

embedded/2024/9/19 11:24:58/ 标签: 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 客户端实例。


http://www.ppmy.cn/embedded/100743.html

相关文章

C++竞赛初阶L1-13-第五单元-循环嵌套(29~30课)538: T456457 第 n 小的质数

题目内容 输入一个正整数 n&#xff0c;求正整数范围中第 n 小的质数。 输入格式 一个不超过 30000 的正整数 n。 输出格式 第 n 小的质数。 样例 1 输入 10 全部程序代码&#xff1a; #include<bits/stdc.h> using namespace std; int main() {long long n,i;ci…

StarRocks 存算分离数据回收原理

前言 StarRocks存算分离表中&#xff0c;垃圾回收是为了删除那些无用的历史版本数据&#xff0c;从而节约存储空间。考虑到对象存储按照存储容量收费&#xff0c;因此&#xff0c;节约存储空间对于降本增效尤为必要。 在系统运行过程中&#xff0c;有以下几种情况可能会需要删…

Linux运维、Windows运维常用命令,保存起来当手册用

文章目录 一、centos基本命令1、升级内核到最新版本2、文件句柄数限制优化3、ssh、sftp、scp等远程命令4、find文件查找5、vi命令 二、windows常用操作 一、centos基本命令 1、升级内核到最新版本 # 1、查看内核版本 [rootlocalhost ~]# cat /etc/centos-release CentOS Linu…

关于Spring Boot的自动配置

目录 1.EnableAutoConfiguration注解 2.SpringBootConfiguration注解 3.Import注解 4.spring.factories 5.总结 &#xff08;1&#xff09;EnableAutoConfiguration &#xff08;2&#xff09;AutoConfigurationImportSelector &#xff08;3&#xff09; SpringFactoriesLoade…

G1处理器GC调优常用参数详解

mixGC触发机制&#xff1a; G1 垃圾收集器在执行垃圾收集时&#xff0c;会根据不同的情况选择不同的垃圾收集策略&#xff0c;其中 "Mixed GC" 是一种比较复杂的策略&#xff0c;用于回收整个堆内存中的垃圾。 G1 垃圾收集器执行 Mixed GC 的时机通常取决于以下几个…

【Python进阶(十)】——Matplotlib基础可视化

&#x1f349;CSDN小墨&晓末:https://blog.csdn.net/jd1813346972 个人介绍: 研一&#xff5c;统计学&#xff5c;干货分享          擅长Python、Matlab、R等主流编程软件          累计十余项国家级比赛奖项&#xff0c;参与研究经费10w、40w级横向 文…

Java泛型机制详解

引入泛型的原因 泛型的本质是为了参数化类型&#xff08;在不创建新的类型的情况下&#xff0c;通过泛型指定的不同类型来控制形参具体限制的类型&#xff09;。也就是说在泛型使用过程中&#xff0c;操作的数据类型被指定为一个参数&#xff0c;这种参数类型可以用在类、接口…

一、HTML5知识点精讲

一、HTML5介绍 html是用来描述网页的一种语言&#xff08;就是写网页的一种语言&#xff09;。 它和CSS&#xff0c;JS称为网页三要素。 HTML负责把元素简单呈现在网页上&#xff0c;是网页的身体CSS负责给网页元素添加各种样式&#xff0c;是网页的衣服JS负责实现各种动态、…

ShellSweepPlus 介绍:开源 Web Shell 检测

ShellSweepPlus 概述 ShellSweepPlus是一款开源工具,旨在帮助安全团队检测潜在的 Web Shell。它是 ShellSweep 的增强版 Webshell 的威胁 Web shell 对组织构成重大威胁,因为它们为攻击者提供了对受感染 Web 服务器的未经授权的访问和控制。攻击者可以利用这些 shell 来:…

6.InnoDB引擎

InnoDB引擎 1.逻辑存储结构2.架构2.1内存架构2.2 磁盘结构 3.事务原理3.1 事务3.2 redo log3.3undo log 4.MVCC4.1MVCC 基本概率14.2 实现原理 1.逻辑存储结构 2.架构 2.1内存架构 2.2 磁盘结构 create tablespace mytest add datafile mytest.idb engineinnodb;后台线程 mys…

用 postman 的时候如何区分服务器还是自己的问题?

“首先&#xff0c;可以通过请求的目标地址来判断。如果目标地址是已知的服务器地址&#xff0c;那很可能是在与服务器进行交互。而如果目标地址指向本地的特定端口或 IP 地址&#xff0c;比如 127.0.0.1 或 localhost&#xff0c;那就可能是在测试本地的服务。 其次&#xff…

AD的3D模型格式是什么

AD通常指的是Altium Designer&#xff0c;这是一款用于电子设计自动化的软件&#xff0c;主要用于电路板的设计。在Altium Designer中&#xff0c;3D模型主要用于PCB&#xff08;印制电路板&#xff09;设计中的可视化&#xff0c;以便设计师能够在三维空间中查看组件和板的布局…

ES6笔记总结(Xmind格式):第三天

Xmind鸟瞰图&#xff1a; 简单文字总结&#xff1a; ES6知识总结&#xff1a; Promise的使用: 1.使用 new Promise() 构造函数来创建一个 promise 对象 2.接受两个函数作为参数&#xff1a;resolve 和 reject ①resolve 函数在异步操作成功完成时调用&#xf…

正则表达式——详解

正则表达式是什么&#xff1f; 正则表达式&#xff08;Regular Expression&#xff0c;通常简写为 regex、regexp 或 RE&#xff09;是一种强大的文本处理工具&#xff0c;用于描述一组字符串的模式。它可以用来匹配、查找、替换等操作&#xff0c;几乎所有现代编程语言都支持…

Web AI测试WINSCP从windows同步文件到Linux脚本使用案例-测试验证成功

Web AI测试脚本使用案例 提问&#xff1a; windows 使用winscp工具定时传输文件到Linux系统的/tmp目录 回答&#xff1a; option batch abort option confirm off open sftp://username:passwordhostname put "C:\path\to\your\local\file" /tmp/ exitecho off &…

stm32的UART重定向printf()

1配置好uart 2打开usart.c文件 3在此文件前面添加头文件 4在末尾添加重定向代码 添加的代码 /* USER CODE BEGIN 1 *///加入以下代码,支持printf函数,而不需要选择use MicroLIB //#define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f) #if 1 //#pragma import(__use_n…

Java-Redis

文章目录 基础基础内容使用场景/功能常见数据类型下载与安装可视化&#xff08;多个&#xff09;发布订阅功能事务两种持久化主从模式哨兵模式集群模式Cluster缓存淘汰过期删除缓存一致 Cache Aside缓存击穿缓存穿透缓存雪崩分布式锁 实战内容配置文件配置Redis的BeanRedis为什…

js怎样改变元素的内容、属性、样式?

一、改变元素内容 使用 textContent 属性&#xff1a; textContent 可以设置或获取元素及其后代的文本内容。例如 const element document.getElementById(myElement);element.textContent New text content;使用 innerHTML 属性&#xff1a; innerHTML 可以设置或获取元素的…

C++ 模板

模版收尾 模版的声明和定义不能分离&#xff0c;否则会报错. 写下面三个文件&#xff1a; Stack.h#pragma once #include<iostream> using namespace std; template <class T> T Add(const T& left, const T& right);Stack.cpp#include"Stack.h&qu…

【git】如何更改git绑定账号

更换之前同事的git账号&#xff08;gitee仓库&#xff09; 1、公钥配置 公钥的作用&#xff1a;身份验证&#xff0c;免去每次提交或拉去的登录操作。步骤&#xff1a; 1.安装git --> 鼠标右键 --> Git Bash Here -->进入命令窗口 命令一&#xff1a;查看git配置 …