目录

一、简介

二、关于索引相关API操作

三、关于文档相关API操作

四、总结


一、简介

前面一篇文章我们已经实现了es整合springboot项目,本篇文章将总结关于高级客户端API操作索引和文档的一些操作。

二、关于索引相关API操作

在es中,很多API操作都是基于RestHighLevelClient对象来进行,下面我们通过几个常见示例说明其用法。

【a】创建一个名为"student_info"的索引库

主要分为下面三个步骤:

  1. 创建索引请求;
  2. 执行索引​​请求;
  3. 获取索引请求响应结果;
@SpringBootTest
class WshElasticsearchApiApplicationTests {@Autowiredprivate RestHighLevelClient restHighLevelClient;/*** 测试创建索引*/@Testvoid createIndex() {//创建索引请求CreateIndexRequest studentInfoIndexRequest = new CreateIndexRequest("student_info");//执行请求try {//获取响应CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(studentInfoIndexRequest, RequestOptions.DEFAULT);System.out.println(createIndexResponse);} catch (IOException e) {e.printStackTrace();}}}

执行单元测试:

如上图,成功创建索引。

【b】判断索引库是否存在

@Testvoid existsIndex() {//创建获取索引的请求GetIndexRequest getIndexRequest = new GetIndexRequest("student_info");boolean exists = false;try {//执行请求,获取响应结果exists = restHighLevelClient.indices().exists(getIndexRequest, RequestOptions.DEFAULT);} catch (IOException e) {e.printStackTrace();}System.out.println(exists);}

控制台输出日志如下:

可以看到,我们的索引库student_info存在。

【c】删除索引库

@Testvoid deleteIndex() {//创建删除索引的请求DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("student_info");//执行请求,获取响应结果AcknowledgedResponse acknowledgedResponse = null;try {acknowledgedResponse = restHighLevelClient.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);} catch (IOException e) {e.printStackTrace();}System.out.println(acknowledgedResponse);}

控制台输出日志如下:

可以看到,成功删除索引库student_info,es-head中也查看不到student_info的索引了。

三、关于文档相关API操作

【a】添加文档

首先,我们先创建一个"student_info"的索引库:

创建完成后,我们需要创建一个实体类Student用于模拟插入数据:

package com.wsh.elasticsearch.wshelasticsearchapi.entity;import org.springframework.stereotype.Component;@Component
public class Student {private String name;private int age;public Student() {}public Student(String name, int age) {this.name = name;this.age = age;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}@Overridepublic String toString() {return "Student{" +"name='" + name + '\'' +", age=" + age +'}';}
}

pom.xml文件中添加json转化工具包fastjson依赖,后面保存数据时需要用到:

 <dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.60</version></dependency>

新建文档:

 @Testvoid createDocument() {//创建对象Student student = new Student("张三", 30);//创建索引请求IndexRequest request = new IndexRequest("student_info");//设置IDrequest.id("1");//设置超时request.timeout(TimeValue.timeValueSeconds(1));//将数据放入请求(json格式)request.source(JSON.toJSONString(student), XContentType.JSON);//客户端发送请求IndexResponse response = null;try {//获取响应response = restHighLevelClient.index(request, RequestOptions.DEFAULT);} catch (IOException e) {e.printStackTrace();}System.out.println(response.toString());System.out.println(response.status());}

控制台日志输出如下:

IndexResponse[index=student_info,type=_doc,id=1,version=1,result=created,seqNo=0,primaryTerm=1,shards={"total":2,"successful":1,"failed":0}]
CREATED

可以看到数据的状态为CREATE创建状态,创建完成后,我们去es-head中查看索引数据:

可见,文档成功插入到索引库中。

【b】判断文档是否存在

@Testvoid existsDocument() {//创建获取文档请求GetRequest request = new GetRequest("student_info", "1");boolean exists = false;try {exists = restHighLevelClient.exists(request, RequestOptions.DEFAULT);} catch (IOException e) {e.printStackTrace();}System.out.println(exists);}

控制台日志输出如下:

可见,ID为1的文档记录存在索引库中。

【c】获取文档的信息

@Testvoid getDocument() {//创建获取文档请求GetRequest request = new GetRequest("student_info", "1");GetResponse response = null;try {//获取响应response = restHighLevelClient.get(request, RequestOptions.DEFAULT);} catch (IOException e) {e.printStackTrace();}System.out.println("response: " + response);System.out.println("id: " + response.getId());System.out.println("index: " + response.getIndex());System.out.println("source: " + response.getSource());System.out.println("source string: " + response.getSourceAsString());System.out.println("version: " + response.getVersion());System.out.println("fields: " + response.getFields());}

控制台日志输出如下:

response: {"_index":"student_info","_type":"_doc","_id":"1","_version":1,"_seq_no":0,"_primary_term":1,"found":true,"_source":{"age":30,"name":"张三"}}
id: 1
index: student_info
source: {name=张三, age=30}
source string: {"age":30,"name":"张三"}
version: 1
fields: {}

【d】更新文档的信息

@Testvoid updateDocument() {//创建更新文档请求UpdateRequest request = new UpdateRequest("student_info", "1");//设置超时request.timeout("1s");//创建对象Student student = new Student("李四", 40);//设置请求体内容request.doc(JSON.toJSONString(student), XContentType.JSON);UpdateResponse response = null;try {//执行更新请求,获取响应结果response = restHighLevelClient.update(request, RequestOptions.DEFAULT);} catch (IOException e) {e.printStackTrace();}System.out.println(response);}

控制台日志输出如下:

UpdateResponse[index=student_info,type=_doc,id=1,version=2,seqNo=1,primaryTerm=1,result=updated,shards=ShardInfo{total=2, successful=1, failures=[]}]

更新完成后,我们去es-head中查看索引数据:

可见,数据成功被更新。

【e】删除文档信息

@Testvoid deleteDocument() {//创建删除请求DeleteRequest request = new DeleteRequest("student_info", "1");request.timeout("1s");DeleteResponse response = null;try {//执行删除请求,获取响应结果response = restHighLevelClient.delete(request, RequestOptions.DEFAULT);} catch (IOException e) {e.printStackTrace();}System.out.println(response);}

控制台日志输出如下:

DeleteResponse[index=student_info,type=_doc,id=1,version=3,result=deleted,shards=ShardInfo{total=2, successful=1, failures=[]}]

删除完成后,我们去es-head中查看索引数据:

可见,数据成功被删除。

【f】批量插入数据

@Testvoid bulkRequest() {//创建批处理请求BulkRequest request = new BulkRequest();//设置超时request.timeout("15s");//创建集合List<Student> studentList = new ArrayList<>();studentList.add(new Student("张三", 10));studentList.add(new Student("李四", 20));studentList.add(new Student("王五", 30));studentList.add(new Student("赵六", 40));studentList.add(new Student("田七", 50));for (int i = 0; i < studentList.size(); i++) {Student student = studentList.get(i);IndexRequest indexRequest = new IndexRequest("student_info").id((i + 1) + "").source(JSON.toJSONString(student), XContentType.JSON);request.add(indexRequest);}BulkResponse response = null;try {response = restHighLevelClient.bulk(request, RequestOptions.DEFAULT);} catch (IOException e) {e.printStackTrace();}//是否失败  false表示成功System.out.println(response.hasFailures());//状态System.out.println(response.status());}

控制台日志输出如下:

插入完成后,我们去es-head中查看索引数据:

可见,批量插入数据成功。

同理,批量更新、批量删除只是构造的xxxRequest不同而已,其他基本一致。

四、总结

本篇文章主要总结了es高级客户端API操作索引以及文档的一些操作,通过详细的示例说明其用法。大体的步骤基本一致:

  1. 第一步,先构造xxxRequest请求对象,可以设置超时等信息;
  2. 第二部,通过restHighLevelClient对象执行对应的请求;
  3. 第三步,获取执行请求的响应结果进行分析;

更多详细的高级API操作可参考elasticsearch官方文档进行学习,下一篇文章我们将总结一些关于查询相关的API详解。

ElasticSearch全文搜索引擎之索引和文档的API操作详解相关推荐

  1. tensorflow 读取cifar_对tensorflow中cifar-10文档的Read操作详解

    前言 在tensorflow的官方文档中得卷积神经网络一章,有一个使用cifar-10图片数据集的实验,搭建卷积神经网络倒不难,但是那个cifar10_input文件着实让我费了一番心思.配合着官方文 ...

  2. 【实现平台搜索功能】lucene全文搜索引擎模块的简单使用,内含原理详解

    0.Lucene介绍 lunece是一项全文检索技术,是apache下的一个开源全文检索引擎工具包,提供了完整的查询引擎和索引引擎,部分文本分析引擎.需要实现全文检索的一般功能的时候是够用的了. 数据 ...

  3. ElasticSearch——Spring Boot 集成 ES 操作详解

    文章目录 ElasticSearch--Spring Boot 集成 ES 操作详解 1.SpringBoot 集成 ES 2.索引的API操作详解 3.文档的API操作详解 ElasticSearc ...

  4. 第三百六十二节,Python分布式爬虫打造搜索引擎Scrapy精讲—elasticsearch(搜索引擎)基本的索引和文档CRUD操作、增、删、改、查...

    第三百六十二节,Python分布式爬虫打造搜索引擎Scrapy精讲-elasticsearch(搜索引擎)基本的索引和文档CRUD操作.增.删.改.查 elasticsearch(搜索引擎)基本的索引 ...

  5. ElasticSearch 全文搜索引擎

    一.ElasticSearch 简介 1.什么是 ElasticSearch? Elaticsearch,简称为es, es是一个开源的高扩展的分布式全文检索引擎,它可以近乎实时的存储.检索数据:本身 ...

  6. ElasticSearch 全文搜索引擎;ES 搜索引擎

    一.ElasticSearch 简介 1.什么是 ElasticSearch? Elaticsearch,简称为es, es是一个开源的高扩展的分布式全文检索引擎,它可以近乎实时的存储.检索数据:本身 ...

  7. Elasticsearch全文搜索引擎,从0到0.6

    目录 一,ES简介 1,es实现原理 2,基本结构 3,ELK 二.Linux搭建环境 1,jdk安装 2,安装Elasticsearch 3,启动es 4,启动es可能遇到的错误 4,在windon ...

  8. 一文看懂-ElasticSearch全文搜索引擎

    一文看懂-ElasticSearch全文搜索引擎 一.ElasticSearch简介 1.1 什么是ElasticSearch ElasticSearch简称ES,其中Elastic 从名字里我们可以 ...

  9. Elasticsearch全文搜索引擎-PHP使用教程。

    1.声明依赖关系:         比方说,你的项目中需要一个php版的elasticsearch框架.为了将它添加到你的项目中(下载),你所需要做的就是创建一个 composer.json 文件,其 ...

  10. ElasticSearch 全文搜索引擎的查询详解①(Ubuntu版 v6.6.2)

    ElasticSearch 全文搜索引擎的查询详解①(Ubuntu版 v6.6.2) 1. 前提 2. 轻量搜索 2.1 单条件查询 2.2 多条件查询 2.3 不指定属性查询(查询所有文档属性)-- ...

最新文章

  1. AutoLayouterLib第一版基本完成
  2. 2017软件工程第三次作业--效能分析
  3. 对比Excel,学习Python报表自动化实战
  4. Vue学习【第六篇】:Vue-cli脚手架(框架)与实战案例
  5. 【转】WebApi中的C#await / async,重点是什么?
  6. 打不开mysql exe文件怎么打开文件_exe文件打不开怎么办?
  7. BIO ,NIO,AIO的区别
  8. 009_【OS X和iOS系统学习笔记】 OS X架构
  9. 数据结构—链表-单链表基本操作实现
  10. JS中实现Trim(),TrimStart(),TrimEnd() 的方法
  11. sleep方法和wait方法的区别?
  12. Windows命令行netsh winsock reset解决网络连接问题
  13. 游戏使用html签名,利用HTML5实现电子签名板文字涂鸦代码
  14. UVa-11137 Ingenuous Cubrency
  15. mysql查看锁死的sql,最全指南
  16. 如何从Word,Excel和PowerPoint文档中提取图像,文本和嵌入式文件
  17. python图像处理(三)波形叠加模拟
  18. Mac终端ssh连接Linux服务器
  19. Centos备份文件
  20. 前端图片通过src读取服务器图片

热门文章

  1. 四年级计算机病毒与网络安全,《计算机病毒与网络安全》教学案例
  2. debug运行时出现错误unicodedecodeerror_怎么回事??抖音直播伴侣!出现运行错误...
  3. 自动驾驶 2-1 第 1 课补充阅读:传感器和计算硬件 -- 上
  4. 极客大学架构师训练营 编程的本质与未来 第三课 听课总结
  5. 算法:回溯十四 Restore IP Addresses数字字符串还原为IP地址(2种解法)
  6. 2021-09-03DIEN分成两步去抓取用户的兴趣演化:1兴趣抽取层 去抽取基于用户行为序列的兴趣序列2兴趣演化层 跟target item相关
  7. 442.数组中重复的数据
  8. Cannot open D:\Program Files\Anaconda\Scripts\pip3-script.py
  9. 对于Y=Hx的H细节的一些讨论
  10. 深度学习之四大经典CNN技术浅析