【SpringBoot笔记28】SpringBoot集成ES数据库之操作doc文档(创建、更新、删除、查询)
创始人
2024-02-07 06:53:54
0

这篇文章,主要介绍SpringBoot集成ES数据库之操作doc文档(创建、更新、删除、查询)。

目录

一、SpringBoot操作ES文档数据

1.1、创建文档

1.2、更新文档

1.3、删除文档

1.4、查询文档

1.5、判断文档是否存在

1.6、批量创建文档


一、SpringBoot操作ES文档数据

ElasticSearch数据库中,所有的数据都是采用JSON格式来保存的,也叫做JSON文档,ES中的一条数据,就是一个JSON文档,一般叫做:doc文档。一个index索引下可以保存多个doc文档,每一个doc文档中的数据,保存的JSON格式可以相同、也可以不相同,一般实际开发过程中,相同索引下的doc文档结构都是相同的,因为这样可以提高ES的搜索效率。这里可以将ES中的doc文档看作是关系型数据库中的表记录,大致如下图所示。

下面具体介绍如何通过SpringBoot框架来操作doc文档。

1.1、创建文档

创建文档,需要通过【IndexRequest】请求对象,该对象需要指定index索引名称,以及文档id,文档id可以通过调用【id()】方法来指定,具体的doc文档数据内容通过【source()】方法来保存,该方法有多个重载格式。

注意:当文档id已经存在,再次创建重复的文档id,ES就会抛出异常。

具体案例代码:

package com.spring.boot.demo.controller;import org.elasticsearch.action.DocWriteRequest;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import java.io.IOException;
import java.util.Map;/*** @author ZhuYouBin* @version 1.0.0* @Date: 2022/11/21 22:45* @Description ES数据操作*/
@RestController
@RequestMapping("/api/es/doc")
public class DocController {private static int seqNo = 1;@Autowiredprivate RestHighLevelClient highRestClient;@PostMapping("/create")public String createDoc(@RequestBody Map map) throws IOException {// 创建索引请求: 指定操作doc数据保存到哪个索引下面,索引不存在,则会创建索引IndexRequest indexRequest = new IndexRequest("idx_20221121");// 指定doc文档的唯一id标识, 如果不指定,则ES会默认生成一个值indexRequest.id("2022112100" + (seqNo++));// 设置需要保存的数据,即:doc文档indexRequest.source(map);// 指定本次请求的操作类型,create 表示创建indexRequest.opType(DocWriteRequest.OpType.CREATE);// 执行请求IndexResponse response = highRestClient.index(indexRequest, RequestOptions.DEFAULT);// 处理响应结果DocWriteResponse.Result result = response.getResult();String lowercase = result.getLowercase();System.out.println("result: " + lowercase);return "success.";}}

当doc文档创建完成后,可以通过【getResult()】方法获取结果对象,调用【getLowercase()】方法可以获取到小写的结果值,等于【created】表示doc文档创建成功。

1.2、更新文档

当创建的doc文档数据不正确时候,此时可以通过【UpdateRequest】来更新数据,通过【UpdateRequest】的构造方法来是指定index索引名称、以及doc文档的id,调用【doc()】方法设置更新的数据。

注意:当更新的doc文档id不存在,那么更新的时候就会抛出一个异常。

具体案例代码:

package com.spring.boot.demo.controller;import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;import java.io.IOException;
import java.util.Map;/*** @author ZhuYouBin* @version 1.0.0* @Date: 2022/11/21 22:45* @Description ES数据操作*/
@RestController
@RequestMapping("/api/es/doc")
public class DocController {@Autowiredprivate RestHighLevelClient highRestClient;@PostMapping("/update")public String updateDoc(@RequestBody Map map, @RequestParam("id") String id) throws IOException {// 创建更新doc文档的请求: 指定操作哪个索引下的doc文档UpdateRequest updateRequest = new UpdateRequest("idx_20221121", id);// 设置需要保存的数据,即:doc文档updateRequest.doc(map);// 执行更新请求UpdateResponse response = highRestClient.update(updateRequest, RequestOptions.DEFAULT);// 处理响应结果DocWriteResponse.Result result = response.getResult();String lowercase = result.getLowercase();System.out.println("result: " + lowercase);return "success.";}}

当doc文档更新成功后,可以通过【getResult()】方法获取结果对象,调用【getLowercase()】方法可以获取到小写的结果值,如果文档实际更新了,那么result就等于【updated】表示doc文档更新成功,如果等于【noop】则表示没有更新文档,两次文档内容是一致的。

1.3、删除文档

删除doc文档,是通过【DeleteRequest】请求对象,该构造方法中传递需要index索引名称和doc文档的id,这样ES才知道要删除哪一条数据。

注意:如果删除的doc文档id不存在,ES不会抛异常,这一点和创建、更新不一样,创建、更新时候,如果doc文档id不存在,都会抛异常

具体案例代码:

package com.spring.boot.demo.controller;import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;import java.io.IOException;/*** @author ZhuYouBin* @version 1.0.0* @Date: 2022/11/21 22:45* @Description ES数据操作*/
@RestController
@RequestMapping("/api/es/doc")
public class DocController {private static int seqNo = 1;@Autowiredprivate RestHighLevelClient highRestClient;@PostMapping("/delete")public String deleteDoc(@RequestParam("id") String id) throws IOException {// 创建删除doc文档的请求: 指定删除哪个索引下的doc文档DeleteRequest deleteIndexRequest = new DeleteRequest("idx_20221122", id);// 执行删除请求DeleteResponse response = highRestClient.delete(deleteIndexRequest, RequestOptions.DEFAULT);// 处理响应结果DocWriteResponse.Result result = response.getResult();String lowercase = result.getLowercase();System.out.println("result: " + lowercase);return "success.";}}

删除成功,那么【getResult()】会返回【deleted】,没有找到删除的doc文档id,此时会返回【not_found】。

1.4、查询文档

查询文档需要通过【GetRequest】请求对象,调用【get()】方法之后,会返回一个【GetResponse】对象,这个响应对象提供了如下方法:

其中,可以getSource开头的方法,就是doc文档的具体数据。

注意:没有查询到指定的doc文档,getSource则返回的是null。

具体案例代码:

package com.spring.boot.demo.controller;import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;import java.io.IOException;
import java.util.Map;/*** @author ZhuYouBin* @version 1.0.0* @Date: 2022/11/21 22:45* @Description ES数据操作*/
@RestController
@RequestMapping("/api/es/doc")
public class DocController {private static int seqNo = 1;@Autowiredprivate RestHighLevelClient highRestClient;@GetMapping("/get")public String getDoc(@RequestParam("id") String id) throws IOException {// 创建删除doc文档的请求: 指定查询哪个索引下的doc文档GetRequest getRequest = new GetRequest("idx_20221122", id);// 执行删除请求GetResponse response = highRestClient.get(getRequest, RequestOptions.DEFAULT);// 处理响应结果: 获取doc文档数据Map source = response.getSource();System.out.println(source);return "success.";}}

1.5、判断文档是否存在

判断文档是否存在,也需要通过【GetRequest】请求对象,然后调用【exists()】方法即可。

package com.spring.boot.demo.controller;import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.search.fetch.subphase.FetchSourceContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;import java.io.IOException;/*** @author ZhuYouBin* @version 1.0.0* @Date: 2022/11/21 22:45* @Description ES数据操作*/
@RestController
@RequestMapping("/api/es/doc")
public class DocController {private static int seqNo = 1;@Autowiredprivate RestHighLevelClient highRestClient;@GetMapping("/exists")public String existsDoc(@RequestParam("id") String id) throws IOException {// 创建删除doc文档的请求: 指定查询哪个索引下的doc文档GetRequest getRequest = new GetRequest("idx_20221122", id);// 因为这里只是判断doc文档存不存在,没必要查询具体的数据内容,所以可以指定不返回数据内容getRequest.fetchSourceContext(new FetchSourceContext(false));// 执行删除请求boolean exists = highRestClient.exists(getRequest, RequestOptions.DEFAULT);// 处理响应结果System.out.println("doc文档是否存在: " + exists);return "success.";}}

1.6、批量创建文档

前面介绍的都是单条文档的创建,ES也支持批量创建文档,通过【BulkRequest】请求对象封装多条doc文档数据,然后调用【bulk()】方法执行批量操作即可。

注意:bulk执行批量更新的时候,第一次创建doc文档时候,返回的201状态码,之后更新doc文档的时候,是返回200状态码。

具体案例代码:

package com.spring.boot.demo.controller;import com.fasterxml.jackson.databind.ObjectMapper;
import com.spring.boot.demo.pojo.User;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;import java.io.IOException;
//import java.util.Map;/*** @author ZhuYouBin* @version 1.0.0* @Date: 2022/11/21 22:45* @Description ES数据操作*/
@RestController
@RequestMapping("/api/es/doc")
public class DocController {private static int seqNo = 1;@Autowiredprivate RestHighLevelClient highRestClient;@GetMapping("/bulk")public String bulkDoc() throws IOException {// 创建批量请求BulkRequest bulkRequest = new BulkRequest();// 模拟数据for (int i = 0; i < 10; i++) {IndexRequest indexRequest = new IndexRequest("idx_20221122");indexRequest.id("doc_id00" + i); // 设置doc文档的idUser user = new User("test-name-00" + i, "abcd00100" + i, 20 + i);ObjectMapper objectMapper = new ObjectMapper();String json = objectMapper.writeValueAsString(user);indexRequest.source(json, XContentType.JSON);// 添加到bulk里面bulkRequest.add(indexRequest);}// 批量执行创建请求BulkResponse response = highRestClient.bulk(bulkRequest, RequestOptions.DEFAULT);// 处理响应结果boolean hasFailures = response.hasFailures();if (hasFailures) {System.out.println("批量创建文档失败");}// 获取每一个请求响应BulkItemResponse[] responseItems = response.getItems();for (BulkItemResponse responseItem : responseItems) {int status = responseItem.status().getStatus();// bulk批量操作时候,第一次创建doc文档,返回的201状态码// 之后更新文档,是返回200状态码if (status != 200 && status != 201) {System.out.println("status=" + status + ",执行失败,id=" + responseItem.getId());} else {System.out.println("status=" + status + ",执行成功,id=" + responseItem.getId());}}return "success.";}}

运行结果如下所示:

到此,SpringBoot框架操作ES文档数据就介绍完啦。

综上,这篇文章结束了,主要介绍SpringBoot集成ES数据库之操作doc文档(创建、更新、删除、查询)。

相关内容

热门资讯

喜欢穿一身黑的男生性格(喜欢穿... 今天百科达人给各位分享喜欢穿一身黑的男生性格的知识,其中也会对喜欢穿一身黑衣服的男人人好相处吗进行解...
发春是什么意思(思春和发春是什... 本篇文章极速百科给大家谈谈发春是什么意思,以及思春和发春是什么意思对应的知识点,希望对各位有所帮助,...
网络用语zl是什么意思(zl是... 今天给各位分享网络用语zl是什么意思的知识,其中也会对zl是啥意思是什么网络用语进行解释,如果能碰巧...
为什么酷狗音乐自己唱的歌不能下... 本篇文章极速百科小编给大家谈谈为什么酷狗音乐自己唱的歌不能下载到本地?,以及为什么酷狗下载的歌曲不是...
华为下载未安装的文件去哪找(华... 今天百科达人给各位分享华为下载未安装的文件去哪找的知识,其中也会对华为下载未安装的文件去哪找到进行解...
家里可以做假山养金鱼吗(假山能... 今天百科达人给各位分享家里可以做假山养金鱼吗的知识,其中也会对假山能放鱼缸里吗进行解释,如果能碰巧解...
四分五裂是什么生肖什么动物(四... 本篇文章极速百科小编给大家谈谈四分五裂是什么生肖什么动物,以及四分五裂打一生肖是什么对应的知识点,希...
怎么往应用助手里添加应用(应用... 今天百科达人给各位分享怎么往应用助手里添加应用的知识,其中也会对应用助手怎么添加微信进行解释,如果能...
客厅放八骏马摆件可以吗(家里摆... 今天给各位分享客厅放八骏马摆件可以吗的知识,其中也会对家里摆八骏马摆件好吗进行解释,如果能碰巧解决你...
美团联名卡审核成功待激活(美团... 今天百科达人给各位分享美团联名卡审核成功待激活的知识,其中也会对美团联名卡审核未通过进行解释,如果能...