2.1 Elasticsearch 安装
2.1.1 下载软件
Elasticsearch 的官方地址:https://www.elastic.co/cn/
下载地址:https://www.elastic.co/cn/downloads/elasticsearch
Elasticsearch 分为 Linux 和 Windows 版本,基于我们主要学习的是 Elasticsearch 的 Java 客户端的使用,所以课程中使用的是安装较为简便的 Windows 版本 。
2.1.2 安装软件
Windows 版的 Elasticsearch 的安装很简单,解压即安装完毕,解压后的 Elasticsearch 的目录结构如下
| 目录 | 含义 |
|---|---|
| bin | 可执行脚本目录 |
| config | 配置目录 |
| jdk | 内置 JDK 目录 |
| lib | 类库 |
| logs | 日志目录 |
| modules | 模块目录 |
| plugins | 插件目录 |
解压后,进入 bin 文件目录,点击 elasticsearch.bat 文件启动 ES 服务
注意:9300 端口为 Elasticsearch 集群间组件的通信端口,9200 端口为浏览器访问的 http 协议 RESTful 端口。
第一次启动时会自动生成对应的用户名和密码,以及 kibana 连接所需要的 token,需要记下来,下一次再启动则不再显示
打开浏览器(推荐使用谷歌浏览器),输入地址:https://localhost:9200,输入对应的用户名和密码测试结果
2.1.3 问题解决
- Elasticsearch 是使用 java 开发的,且 8.x 版本的 ES 需要 JDK 版本 17 以上,默认安装包带有 jdk 环境,如果系统配置 JAVA_HOME,那么使用系统默认的 JDK,如果没有配置使用自带的 JDK,一般建议使用系统配置的 JDK。
- 双击启动窗口闪退,通过路径访问追踪错误,如果是“空间不足”,请修改 config/jvm.options 配置文件
# 设置 JVM 初始内存为 4G 。此值可以设置与 Xmx 相同,以避免每次垃圾回收完成后 JVM 重新分配内存# Xms represents the initial size of total heap space# 设置 JVM 最大可用内存为 4G# Xmx represents the maximum size of total heap spaceXms4gXmx4g
2.2 Elasticsearch 基本操作
2.2.1 RESTful
REST 指的是一组架构约束条件和原则。满足这些约束条件和原则的应用程序或设计就是 RESTful。Web 应用程序最重要的 REST 原则是,客户端和服务器之间的交互在请求之间是无状态的。从客户端到服务器的每个请求都必须包含理解请求所必需的信息。如果服务器在请求之间的任何时间点重启,客户端不会得到通知。此外,无状态请求可以由任何可用
服务器回答,这十分适合云计算之类的环境。客户端可以缓存数据以改进性能。
在服务器端,应用程序状态和功能可以分为各种资源。资源是一个有趣的概念实体,它向客户端公开。资源的例子有:应用程序对象、数据库记录、算法等等。每个资源都使用 URI(Universal Resource Identifier)得到一个唯一的地址。所有资源都共享统一的接口,以便在客户端和服务器之间传输状态。使用的是标准的 HTTP 方法,比如 GET、PUT、POST 和 DELETE。
在 REST 样式的 Web 服务中,每个资源都有一个地址。资源本身都是方法调用的目标,方法列表对所有资源都是一样的。这些方法都是标准方法,包括 HTTP GET、POST、PUT、 DELETE,还可能包括 HEAD 和 OPTIONS。简单的理解就是,如果想要访问互联网上的资源,就必须向资源所在的服务器发出请求,请求体中必须包含资源的网络路径,以及对资源进行的操作(增删改查)。2.2.2 客户端安装
如果直接通过浏览器向 Elasticsearch 服务器发请求,那么需要在发送的请求中包含 HTTP 标准的方法,而 HTTP 的大部分特性且仅支持 GET 和 POST 方法。所以为了能方便地进行客户端的访问,可以使用 Postman 软件。
Postman 是一款强大的网页调试工具,提供功能强大的 Web API 和 HTTP 请求调试。软件功能强大,界面简洁明晰、操作方便快捷,设计得很人性化。Postman 中文版能够发送任何类型的 HTTP 请求(GET、HEAD、POST,PUT…),不仅能够表单提交,且可以附带任意类型请求体。
Postman 官网:https://www.getpostman.com
Postman 下载:https://www.postman.com/downloads/
注意:在使用时需要配置 Authorization 参数,否则请求会失败
2.2.3 数据格式
Elasticsearch 是面向文档型数据库,一条数据在这里就是一个文档。为了方便大家理解,我们将 Elasticsearch 里存储文档数据和关系型数据库 MySQL 存储数据的概念进行一个类比
ES 里的 Index 可以看做一个库,而 Types 相当于表,Documents 则相当于表的行。这里 Types 的概念已经被逐渐弱化,Elasticsearch 6.X 中,一个 index 下已经只能包含一个 type,Elasticsearch 7.X 中,Type 的概念已经被删除了。
用 JSON 作为文档序列化的格式,比如一条用户信息:{"name": "John","sex": "Male","age": 25,"birthDate": "1990/05/01","about": "I love to go rock climbing","interests": ["sports", "music"]}
2.2.4 HTTP 操作
2.2.4.1 索引操作
- 创建索引
对比关系型数据库,创建索引就等同于创建数据库
在 Postman 中,向 ES 服务器发 PUT 请求:http://127.0.0.1:9200/shopping
请求后,服务器返回响应
{"acknowledged": true, #响应结果"shards_acknowledged": true, #分片结果"index": "shopping" #索引名称}
注意:创建索引库的分片数默认 1 片,在 7.0.0 之前的 Elasticsearch 版本中,默认 5 片
如果重复添加索引,会返回错误信息
- 查看所有索引
在 Postman 中,向 ES 服务器发 GET 请求:http://127.0.0.1:9200/_cat/indices?v
这里请求路径中的 _cat 表示查看的意思,indices 表示索引,所以整体含义就是查看当前 ES 服务器中的所有索引,就好像 MySQL 中的 show tables 的感觉,服务器响应结果如下
| 表头 | 含义 |
|---|---|
| health | 当前服务器健康状态: green(集群完整)yellow(单点正常、集群不完整)red(单点不正常) |
| status | 索引打开、关闭状态 |
| index | 索引名 |
| uuid | 索引统一编号 |
| pri | 主分片数量 |
| rep | 副本数量 |
| docs.count | 可用文档数量 |
| docs.deleted | 文档删除状态(逻辑删除) |
| store.size | 主分片和副分片整体占空间大小 |
| pri.store.size | 主分片占空间大小 |
- 查看单个索引
在 Postman 中,向 ES 服务器发 GET 请求:http://127.0.0.1:9200/shopping
查看索引向 ES 服务器发送的请求路径和创建索引是一致的。但是 HTTP 方法不一致。这里可以体会一下 Restful 的意义,请求后,服务器响应结果如下:

- 删除索引
在 Postman 中,向 ES 服务器发 DELETE 请求:http://127.0.0.1:9200/shopping

重新访问索引时,服务器返回响应:索引不存在
2.2.4.2 文档操作
- 创建文档
索引已经创建好了,接下来我们来创建文档,并添加数据。这里的文档可以类比为关系型数据库中的表数据,添加的数据格式为 JSON 格式
在 Postman 中,向 ES 服务器发 POST 请求 http://127.0.0.1:9200/shopping/_doc
请求体内容为:
{"title": "小米手机","category": "小米","images": "http://www.gulixueyuan.com/xm.jpg","price": 3999.00}

此处发送请求的方式必须为 POST ,不能是 PUT ,否则会发生错误,因为 POST 不是幂等性,PUT 是幂等性,这里创建文档不是幂等性。
服务器响应结果如下:

上面的数据创建后,由于没有指定数据唯一性标识(ID),默认情况下 ES 服务器会随机生成一个 。如果想要自定义唯一性标识,需要在创建时指定 http://127.0.0.1:9200/shopping/_doc/1

此处需要注意:如果增加数据时明确数据主键,那么请求方式也可以为 PUT
- 查看文档
查看文档时,需要指明文档的唯一性标识,类似于 MySQL 中数据的主键查询
在 Postman 中,向 ES 服务器发 GET 请求 http://127.0.0.1:9200/shopping /_doc/1
查询成功后,服务器响应结果:

- 修改文档
和新增文档一样,输入相同的 URL 地址请求,如果请求体变化,会将原有的数据内容覆盖
在 Postman 中,向 ES 服 务器发 POST 请求 http://127.0.0.1:9200/shopping/_doc/1
请求体内容为:
{"title": "华为手机","category": "华为","images": "http://www.gulixueyuan.com/hw.jpg","price": 4999.00}

修改成功后,服务器响应结果:

- 修改字段
修改数据时,也可以只修改某一给条数据的局部信息
在 Postman 中,向 ES 服务器发 POST 请求 http://127.0.0.1:9200/shopping/opping/_update/1
请求体内容为:
{"doc": {"price": 3000.00}}

修改成功后,服务器响应结果:
根据唯一性标识,查询文档数据,文档数据已经更新

- 删除文档
删除一个文档不会立即从磁盘上移除,它只是被标记成已删除(逻辑删除)。
在 Postman 中,向 ES 服务器发 DELETE 请求 http://127.0.0.1:9200/shopping/_doc/1
删除成功,服务器响应结果:

删除后再查询当前文档信息

如果删除一个并不存在的文档


- 条件删除文档
一般删除数据都是根据文档的唯一性标识进行删除,实际操作时,也可以根据条件对多条数据进行删除
首先分别增加多条数据:
[{"title": "小米手机","category": "小米","images": "http://www.gulixueyuan.com/xm.jpg","price": 4000.00}, {"title": "华为手机","category": "华为","images": "http://www.gulixueyuan.com/hw.jpg ","price": 4000.00}]


向 ES 服务器发 POST 请求 http://127.0.0.1:9200/shopping/_delete_by_query
请求体内容为:
{" query": {"match": {"price": 4000.00}}}
2.2.4.3 映射操作
有了索引库,等于有了数据库中的 database。
接下来就需要建索引库(index)中的映射了,类似于数据库(database)中的表结构(table)。创建数据库表需要设置字段名称,类型,长度,约束等;索引库也一样,需要知道这个类型下有哪些字段,每个字段有哪些约束信息,这就叫做映射(mapping)。
- 创建映射
在 Postman 中,向 ES 服务器发 PUT 请求 http://127.0.0.1:9200/student/_mapping
请求体内容为:
{"properties": {"name": {"type": "text","index": true},"sex": {"type": "text","index": false},"age": {"type": "long","index": false}}}

服务器响应结果如下:
映射数据说明:
- 字段名:任意填写,下面指定许多属性,例如:title 、subtitle、images、price
- type:类型,Elasticsearch 中支持的数据类型非常丰富,说几个关键的:
- String 类型,又分两种:
- text:可分词
- keyword:不可分词,数据会作为完整字段进行匹配
- Numerical:数值类型,分两类
- 基本数据类型:long、integer、short、byte、double、float、half_float
- 浮点数的高精度类型:scaled_float
- Date:日期类型
- Array:数组类型
- Object:对象
- String 类型,又分两种:
- index:是否索引,默认为 true,也就是说你不进行任何配置,所有字段都会被索引。
- true:字段会被索引,则可以用来进行搜索
- false:字段不会被索引,不能用来搜索
- store:是否将数据进行独立存储,默认为 false
原始的文本会存储在 _source 里面,默认情况下其他提取出来的字段都不是独立存储的,是从 _source 里面提取出来的。当然你也可以独立的存储某个字段,只要设置”store”: true 即可,获取独立存储的字段要比从 _source 中解析快得多,但是也会占用更多的空间,所以要根据实际业务需求来设置。 - analyzer:分词器,这里的 ik_max_word 即使用 ik 分词器 后面会有专门的章节学习
- 查看映射
在 Postman 中,向 ES 服务器发 GET 请求 http://127.0.0.1:9200/student/_mapping
服务器响应结果如下:
- 索引映射关联
在 Postman 中,向 ES 服务器发 PUT 请求 http://127.0.0.1:9200/student1
{"settings": {},"mappings": {"properties": {"name": {"type": "text","index": true},"sex": {"type": "text","index": false},"age": {"type": "long","index": false}}}}
2.2.2.4 高级查询
Elasticsearch 提供了基于 JSON 提供完整的查询 DSL 来定义查询
定义数据:
POST /student/_doc/1001
{"name": "zhangsan","nickname": "zhangsan","sex": "男","age": 30}
POST /student/_doc/1002
{"name": "lisi","nickname": "lisi","sex": "男","age": 20}
POST /student/_doc/1003
{"name": "wangwu","nickname": "wangwu","sex": "女","age": 40}
POST /student/_doc/1004
{"name": "zhangsanl","nickname": "zhangsan1","sex": "女","age": 50}
POST /student/_doc/1005
{"name": " zhangsan2","nickname": "zhanqsan2","sex": "女","age": 30}
- 查询所有文档
在 Postman 中,向 ES 服务器发 GET 请求 http://127.0.0.1:9200/student/_search
{"query": {"match_all": {}}}
“query”:这里的 query 代表一个查询对象,里面可以有不同的查询属性
“match_ all”:查询类型,例如 match_all(代表查询所有),match、term、range 等等
{查询条件}:查询条件会根据类型的不同,写法也有差异
服务器响应结果如下:


- 匹配查询
match 匹配类型查询,会把查询条件进行分词,然后进行查询,多个词条之间是 or 的关系
在 Postman 中,向 ES 服务器发 GET 请求 http://127.0.0.1:9200/student/_search
{"query": {"match": {"name": "zhangsan"}}}

服务器响应结果为:
- 字段匹配查询
multi_match 与 match 类似,不同的是它可以在多个字段中查询。
在 Postman 中,向 ES 服务器发 GET 请求 http://127.0.0.1:9200/student/_search
{"query": {"multi match": {"query": "zhangsan","fields": ["name", "nickname"]}}}

服务器响应结果:
- 关键字精确查询
term 查询,精确的关键词匹配查询,不对查询条件进行分词。
在 Postman 中,向 ES 服务器发 GET 请求 http://127.0.0.1:9200/student/_search
{"query": {"term": {"name": {"value": "zhangsan"}}}}

服务器响应结果:
- 多关键字精确查询
terms 查询和 term 查询一样,但它允许你指定多值进行匹配。如果这个字段包含了指定值中的任何一个值,那么这个文档满足条件,类似于 mysql 的 in
在 Postman 中,向 ES 服务器发 GET 请求 http://127.0.0.1:9200/student/_search
{"query": {"terms": {"name": ["zhangsan", "lisi"]}}}

服务器响应结果:
- 指定查询字段
默认情况下,Elasticsearch 在搜索的结果中,会把文档中保存在 _source 的所有字段都返回。如果我们只想获取其中的部分字段,我们可以添加 _source 的过滤
在 Postman 中,向 ES 服务器发 GET 请求 http://127.0.0.1:9200/student/_search
{"source": ["name", "nickname"],"query": {"terms": {"nickname": ["zhangsan"]}}}

服务器响应结果:
- 过滤字段
我们也可以通过:
- includes:来指定想要显示的字段
- excludes:来指定不想要显示的字段
在 Postman 中,向 ES 服务器发 GET 请求 http://127.0.0.1:9200/student/_search
{"_source ": {"includes": ["name", "nickname"]},"query": {"terms": {"nickname": ["zhangsan"]}}}

服务器响应结果:
在 Postman 中,向 ES 服务器发 GET 请求 http://127.0.0.1:9200/student/_search
{"_source": {"excludes": ["name", "nickname"]},"query": {"terms": {"nickname": ["zhangsan"]}}}

服务器响应结果:
- 组合查询
“bool”把各种其它查询通过”must”(必须 )、”must_not”(必须不)、”should”(应该)的方式进行组合
在 Postman 中,向 ES 服务器发 GET 请求 http://127.0.0.1:9200/student/_search
{"query": {"bool": {"must": [{"match": {"name": "zhangsan"}}],"must_not": [{"match": {"age": "40"}}],"should": [{"match": {"sex": "男"}}]}}}

服务器响应结果:
- 范围查询
range 查询找出那些落在指定区间内的数字或者时间。 range 查询允许以下字符
| 操作符 | 说明 |
|---|---|
| gt | 大于 |
| gte | 大于等于 |
| lt | 小于 |
| lte | 小于等于 |
在 Postman 中,向 ES 服务器发 GET 请求 http://127.0.0.1:9200/student/_search
{"query": {"range": {"age": {"gte": 30,"lte": 35}}}}

服务器响应结果:
- 模糊查询
返回包含与搜索字词相似的字词的文档。
编辑距离是将一个术语转换为另一个术语所需的一个字符更改的次数。这些更改可以包括:
- 更改字符(box -> fox)
- 删除字符(black -> lack)
- 插入字符(sic -> sick)
- 转置两个相邻字符(act -> cat)
为了找到相似的术语,fuzzy 查询会在指定的编辑距离内创建一组搜索词的所有可能的变体或扩展。然后查询返回每个扩展的完全匹配。通过 fuzziness 修改编辑距离。一般使用默认值 AUTO,根据术语的长度生成编辑距离。
在 Postman 中,向 ES 服务器发 GET 请求 http://127.0.0.1:9200/student/_search
{"query": {"fuzzy": {"title": {"value": "zhangsan"}}}}

服务器响应结果:
在 Postman 中,向 ES 服务器发 GET 请求 http://127.0.0.1:9200/student/_search
{"query": {" fuzzy": {"title": {"value": "zhangsan","fuzziness": 2}}}}

服务器响应结果:
- 单字段排序
sort 可以让我们按照不同的字段进行排序,并且通过 order 指定排序的方式。 desc 降序,asc 升序。
在 Postman 中,向 ES 服务器发 GET 请求 http://127.0.0.1:9200/student/_search
{"query": {"match": {"name": "zhangsan"}},"sort": [{"age": {"order": "desc"}}]}

服务器响应结果:
- 多字段排序
假定我们想要结合使用 age 和 _score 进行查询,并且匹配的结果首先按照年龄排序,然后按照相关性得分排序
在 Postman 中,向 ES 服务器发 GET 请求 http://127.0.0.1:9200/student/_search
{"query": {"match all": {}},"sort": [{"age": {"order": "desc"}}, {"_score": {"order": "desc"}}]}

服务器响应结果:
- 高亮查询
在进行关键字搜索时,搜索出的内容中的关键字会显示不同的颜色,称之为高亮。
在百度搜索“京东”
Elasticsearch 可以对查询内容中的关键字部分,进行标签和样式(高亮)的设置。
在使用 match 查询的同时,加上一个 highlight 属性:
- pre_tags:前置标签
- post_tags:后置标签
- fields:需要高亮的字段
- title:这里声明 title 字段需要高亮,后面可以为这个字段设置特有配置,也可以空
在 Postman 中,向 ES 服务器发 GET 请求 http://127.0.0.1:9200/student/_search
{"query": {"match": {"name": "zhangsan"}},"highlight": {"pre_tags": "<font color='red'>","post_tags": "</font>","fields": {"name": {}}}}

服务器响应结果:
- 分页查询
from:当前页的起始索引,默认从 0 开始。 from = (pageNum 1) * size
size:每页显示多少条
在 Postman 中,向 ES 服务器发 GET 请求 http://127.0.0.1:9200/student/_search
{"query ": {"match all": {}},"sort": [{"age": {"order": "desc"}}],"from": 0,"size": 2}

服务器响应结果:
- 聚合查询
聚合允许使用者对 es 文档进行统计分析,类似与关系型数据库中的 group by ,当然还有很多其他的聚合,例如取最大值、平均值等等。
- 对某个字段取最大值 max
在 Postman 中,向 ES 服务器发 GET 请求 http://127.0.0.1:9200/student/_search
{"aggs": {"max _age": {"max": {"field": "age"}}},"size": 0}

服务器响应结果:
- 对某个字段取最小值 min
在 Postman 中,向 ES 服务器发 GET 请求 http://127.0.0.1:9200/student/_search
{"aggs": {"min age": {"min": {"field": "age"}},"size": 0}}

服务器响应结果:
- 对某个字段求和 sum
在 Postman 中,向 ES 服务器发 GET 请求 http://127.0.0.1:9200/student/_search
{"aggs": {"sum_age": {"sum": {"field": "age"}}},"size": 0}

服务器响应结果:
- 对某个字段取平均值 avg
在 Postman 中,向 ES 服务器发 GET 请求 http://127.0.0.1:9200/student/_search
{"aggs": {"avg_age": {"avg": {"field": "age"}}},"size": 0}

服务器响应结果:
- 对某个字段的值进行去重之后再取总数
在 Postman 中,向 ES 服务器发 GET 请求 http://127.0.0.1:9200/student/_search
{"aggs": {"distinct_age": {"cardinality": {"field": "age"}}},"size": 0}

服务器响应结果:
- State 聚合
stats 聚合,对某个字段一次性返回 count max min avg 和 sum 五个指标
在 Postman 中,向 ES 服务器发 GET 请求 http://127.0.0.1:9200/student/_search
{"aggs": {" stats_age": {"stats": {"field": "age"}}},"size": 0}

服务器响应结果:
- 桶聚合查询
桶聚和相当于 sql 中的 group by 语句
- terms 聚合,分组统计
在 Postman 中,向 ES 服务器发 GET 请求 http://127.0.0.1:9200/student/_search
{"aggs": {" age_groupby": {"terms": {"field": "age"}}},"size": 0}

服务器响应结果:
- 在 terms 分组下再进行聚合
在 Postman 中,向 ES 服务器发 GET 请求 http://127.0.0.1:9200/student/_search
{"aggs": {" age_groupby": {"terms": {"field": "age"}}},"size": 0}
2.2.5 Java API 操作
Elasticsearch 软件是由 Java 语言开发的,所以也可以通过 Java API 的方式对 Elasticsearch 服务进行访问
2.2.5.1 创建 Maven 项目
我们在 IDEA 开发工具中创建 Maven 项目(模块也可)ES
修改 pom 文件,增加 Maven 依赖关系
<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>org.example</groupId><artifactId>es-test</artifactId><version>1.0-SNAPSHOT</version><properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target></properties><dependencies><!-- elasticsearch 的客户端--><dependency><groupId>co.elastic.clients</groupId><artifactId>elasticsearch-java</artifactId><version>8.1.1</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.13.2.2</version></dependency><!-- junit单元测试--><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.13.2</version><scope>test</scope></dependency></dependencies><!-- 设定仓库,按设定顺序进行查找 --><repositories><repository><id>aliyunmaven</id><name>aliyun</name><url>https://maven.aliyun.com/repository/central</url><snapshots><enabled>true</enabled></snapshots></repository></repositories></project>
2.2.5.2 客户端对象
创建 com.atguigu.es.test.Elasticsearch01_Client 类,代码中创建 Elasticsearch 客户端对象。因为早期版本的客户端对象已经不再推荐使用,且在未来版本中会被删除,所以这里我们采用高级 REST 客户端对象(7.15 版本已经不再推荐使用,后面采用 Java API Client for Elasticsearch)

package com.atguigu.es.test;import co.elastic.clients.elasticsearch.ElasticsearchClient;import co.elastic.clients.elasticsearch.indices.CreateIndexResponse;import co.elastic.clients.json.jackson.JacksonJsonpMapper;import co.elastic.clients.transport.ElasticsearchTransport;import co.elastic.clients.transport.rest_client.RestClientTransport;import org.apache.http.HttpHost;import org.apache.http.auth.AuthScope;import org.apache.http.auth.UsernamePasswordCredentials;import org.apache.http.client.CredentialsProvider;import org.apache.http.impl.client.BasicCredentialsProvider;import org.apache.http.ssl.SSLContextBuilder;import org.apache.http.ssl.SSLContexts;import org.elasticsearch.client.RestClient;import javax.net.ssl.SSLContext;import java.io.InputStream;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths;import java.security.KeyStore;import java.security.cert.Certificate;import java.security.cert.CertificateFactory;/*** @author: zhangxin* @date: 2022/3/31*/public class ESTest_Client {public static void main(String[] args) throws Exception {// 用户认证对象final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();// 设置账号密码credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("elastic", "IZ=zWc_zSRJIYFcadYxL"));Path caCertificatePath = Paths.get("d:/http_ca.crt");CertificateFactory factory = CertificateFactory.getInstance("X.509");Certificate trustedCa;try (InputStream is = Files.newInputStream(caCertificatePath)) {trustedCa = factory.generateCertificate(is);}KeyStore trustStore = KeyStore.getInstance("pkcs12");trustStore.load(null, null);trustStore.setCertificateEntry("ca", trustedCa);SSLContextBuilder sslContextBuilder = SSLContexts.custom().loadTrustMaterial(trustStore, null);final SSLContext sslContext = sslContextBuilder.build();// 创建 es 客户端RestClient restClient = RestClient.builder(new HttpHost("172.18.1.31", 9200, "https")).setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setSSLContext(sslContext).setDefaultCredentialsProvider(credentialsProvider)).build();// 使用 Jackson 映射器创建传输层ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());// 创建 API 客户端ElasticsearchClient esClient = new ElasticsearchClient(transport);// 关闭 es 客户端transport.close();restClient.close();}}
注意:9200 端口为 Elasticsearch 的 Web 通信端口,localhost 为启动 ES 服务的主机名
执行代码,查看控制台信息:
2.2.5.3 索引操作
ES 服务器正常启动后,可以通过 Java API 客户端对象对 ES 索引进行操作
- 创建索引 ```java package com.atguigu.es.test;
import co.elastic.clients.elasticsearch.ElasticsearchClient; import co.elastic.clients.elasticsearch.indices.CreateIndexResponse; import co.elastic.clients.json.jackson.JacksonJsonpMapper; import co.elastic.clients.transport.ElasticsearchTransport; import co.elastic.clients.transport.rest_client.RestClientTransport; import org.apache.http.HttpHost; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.ssl.SSLContextBuilder; import org.apache.http.ssl.SSLContexts; import org.elasticsearch.client.RestClient;
import javax.net.ssl.SSLContext; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.security.KeyStore; import java.security.cert.Certificate; import java.security.cert.CertificateFactory;
/**
- @author: zhangxin
@date: 2022/3/31 */ public class ESTest_Client { public static void main(String[] args) throws Exception {
// 用户认证对象final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();// 设置账号密码credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("elastic", "IZ=zWc_zSRJIYFcadYxL"));Path caCertificatePath = Paths.get("d:/http_ca.crt");CertificateFactory factory = CertificateFactory.getInstance("X.509");Certificate trustedCa;try (InputStream is = Files.newInputStream(caCertificatePath)) {trustedCa = factory.generateCertificate(is);}KeyStore trustStore = KeyStore.getInstance("pkcs12");trustStore.load(null, null);trustStore.setCertificateEntry("ca", trustedCa);SSLContextBuilder sslContextBuilder = SSLContexts.custom().loadTrustMaterial(trustStore, null);final SSLContext sslContext = sslContextBuilder.build();// 创建 es 客户端RestClient restClient = RestClient.builder(new HttpHost("172.18.1.31", 9200, "https")).setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setSSLContext(sslContext).setDefaultCredentialsProvider(credentialsProvider)).build();// 使用 Jackson 映射器创建传输层ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());// 创建 API 客户端ElasticsearchClient esClient = new ElasticsearchClient(transport);// 创建索引CreateIndexResponse response = esClient.indices().create(c -> c.index("user"));Boolean acknowledged = response.acknowledged();// 响应状态System.out.println("索引操作:" + acknowledged);// 关闭 es 客户端transport.close();restClient.close();
} } ``` 操作结果:

- 查看索引 ```java package com.atguigu.es.test;
import co.elastic.clients.elasticsearch.ElasticsearchClient; import co.elastic.clients.elasticsearch.indices.CreateIndexResponse; import co.elastic.clients.elasticsearch.indices.DeleteIndexResponse; import co.elastic.clients.elasticsearch.indices.GetIndexResponse; import co.elastic.clients.elasticsearch.indices.IndexState; import co.elastic.clients.json.jackson.JacksonJsonpMapper; import co.elastic.clients.transport.ElasticsearchTransport; import co.elastic.clients.transport.rest_client.RestClientTransport; import org.apache.http.HttpHost; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.ssl.SSLContextBuilder; import org.apache.http.ssl.SSLContexts; import org.elasticsearch.client.RestClient;
import javax.net.ssl.SSLContext; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.security.KeyStore; import java.security.cert.Certificate; import java.security.cert.CertificateFactory;
/**
- @author: zhangxin
@date: 2022/3/31 */ public class ESTest_Client { public static void main(String[] args) throws Exception {
// 用户认证对象final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();// 设置账号密码credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("elastic", "wkZQNElpnNj6+QWflIBU"));Path caCertificatePath = Paths.get("d:/http_ca.crt");CertificateFactory factory = CertificateFactory.getInstance("X.509");Certificate trustedCa;try (InputStream is = Files.newInputStream(caCertificatePath)) {trustedCa = factory.generateCertificate(is);}KeyStore trustStore = KeyStore.getInstance("pkcs12");trustStore.load(null, null);trustStore.setCertificateEntry("ca", trustedCa);SSLContextBuilder sslContextBuilder = SSLContexts.custom().loadTrustMaterial(trustStore, null);final SSLContext sslContext = sslContextBuilder.build();// 创建 es 客户端RestClient restClient = RestClient.builder(new HttpHost("172.18.1.31", 9200, "https")).setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setSSLContext(sslContext).setDefaultCredentialsProvider(credentialsProvider)).build();// 使用 Jackson 映射器创建传输层ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());// 创建 API 客户端ElasticsearchClient esClient = new ElasticsearchClient(transport);// 查看索引GetIndexResponse response = esClient.indices().get(c -> c.index("user"));IndexState user = response.get("user");// 响应状态System.out.println(user.aliases());System.out.println(user.mappings());System.out.println(user.settings());// 关闭 es 客户端transport.close();restClient.close();
} } ```

- 删除索引 ```java package com.atguigu.es.test;
import co.elastic.clients.elasticsearch.ElasticsearchClient; import co.elastic.clients.elasticsearch.indices.DeleteIndexResponse; import co.elastic.clients.json.jackson.JacksonJsonpMapper; import co.elastic.clients.transport.ElasticsearchTransport; import co.elastic.clients.transport.rest_client.RestClientTransport; import org.apache.http.HttpHost; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.ssl.SSLContextBuilder; import org.apache.http.ssl.SSLContexts; import org.elasticsearch.client.RestClient;
import javax.net.ssl.SSLContext; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.security.KeyStore; import java.security.cert.Certificate; import java.security.cert.CertificateFactory;
/**
- @author: zhangxin
@date: 2022/3/31 */ public class ESTest_Client { public static void main(String[] args) throws Exception {
// 用户认证对象final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();// 设置账号密码credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("elastic", "wkZQNElpnNj6+QWflIBU"));Path caCertificatePath = Paths.get("d:/http_ca.crt");CertificateFactory factory = CertificateFactory.getInstance("X.509");Certificate trustedCa;try (InputStream is = Files.newInputStream(caCertificatePath)) {trustedCa = factory.generateCertificate(is);}KeyStore trustStore = KeyStore.getInstance("pkcs12");trustStore.load(null, null);trustStore.setCertificateEntry("ca", trustedCa);SSLContextBuilder sslContextBuilder = SSLContexts.custom().loadTrustMaterial(trustStore, null);final SSLContext sslContext = sslContextBuilder.build();// 创建 es 客户端RestClient restClient = RestClient.builder(new HttpHost("172.18.1.31", 9200, "https")).setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setSSLContext(sslContext).setDefaultCredentialsProvider(credentialsProvider)).build();// 使用 Jackson 映射器创建传输层ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());// 创建 API 客户端ElasticsearchClient esClient = new ElasticsearchClient(transport);// 删除索引DeleteIndexResponse response = esClient.indices().delete(c -> c.index("user"));// 操作结果Boolean acknowledged = response.acknowledged();System.out.println("索引操作:" + acknowledged);// 关闭 es 客户端transport.close();restClient.close();
2.2.5.4 文档操作
- 新增文档
创建数据模型
package com.atguigu.es.test;public class User {private String name;private Integer age;private String sex;private String id;public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}public String getId() {return id;}public void setId(String id) {this.id = id;}public User(String name, Integer age, String sex, String id) {this.name = name;this.age = age;this.sex = sex;this.id = id;}public User() {}@Overridepublic String toString() {return "User{" +"name='" + name + '\'' +", age=" + age +", sex='" + sex + '\'' +", id='" + id + '\'' +'}';}}
创建数据,添加到文档中
package com.atguigu.es.test.document;import co.elastic.clients.elasticsearch.ElasticsearchClient;import co.elastic.clients.elasticsearch.core.IndexResponse;import co.elastic.clients.json.jackson.JacksonJsonpMapper;import co.elastic.clients.transport.ElasticsearchTransport;import co.elastic.clients.transport.rest_client.RestClientTransport;import com.atguigu.es.test.User;import org.apache.http.HttpHost;import org.apache.http.auth.AuthScope;import org.apache.http.auth.UsernamePasswordCredentials;import org.apache.http.client.CredentialsProvider;import org.apache.http.impl.client.BasicCredentialsProvider;import org.apache.http.ssl.SSLContextBuilder;import org.apache.http.ssl.SSLContexts;import org.elasticsearch.client.RestClient;import javax.net.ssl.SSLContext;import java.io.InputStream;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths;import java.security.KeyStore;import java.security.cert.Certificate;import java.security.cert.CertificateFactory;/*** @author: zhangxin* @date: 2022/3/31*/public class InsertClient {public static void main(String[] args) throws Exception {// 用户认证对象final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();// 设置账号密码credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("elastic", "wkZQNElpnNj6+QWflIBU"));Path caCertificatePath = Paths.get("d:/http_ca.crt");CertificateFactory factory = CertificateFactory.getInstance("X.509");Certificate trustedCa;try (InputStream is = Files.newInputStream(caCertificatePath)) {trustedCa = factory.generateCertificate(is);}KeyStore trustStore = KeyStore.getInstance("pkcs12");trustStore.load(null, null);trustStore.setCertificateEntry("ca", trustedCa);SSLContextBuilder sslContextBuilder = SSLContexts.custom().loadTrustMaterial(trustStore, null);final SSLContext sslContext = sslContextBuilder.build();// 创建 es 客户端RestClient restClient = RestClient.builder(new HttpHost("172.18.1.31", 9200, "https")).setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setSSLContext(sslContext).setDefaultCredentialsProvider(credentialsProvider)).build();// 使用 Jackson 映射器创建传输层ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());// 创建 API 客户端ElasticsearchClient esClient = new ElasticsearchClient(transport);// 新增文档 请求对象// 创建数据对象User user = new User();user.setName("zhangsan");user.setAge(30);user.setSex("男");// 设置索引及唯一性标识// 客户端发送请求,获取响应对象IndexResponse response = esClient.index(i -> i.index("user").id("1001").document(user));// 打印结果信息System.out.println("_index:" + response.index());System.out.println("_id:" + response.id());System.out.println("_result:" + response.result());// 关闭 es 客户端transport.close();restClient.close();}}
操作结果:
- 修改文档 ```java package com.atguigu.es.test.document;
import co.elastic.clients.elasticsearch.ElasticsearchClient; import co.elastic.clients.elasticsearch.core.UpdateResponse; import co.elastic.clients.json.jackson.JacksonJsonpMapper; import co.elastic.clients.transport.ElasticsearchTransport; import co.elastic.clients.transport.rest_client.RestClientTransport; import com.atguigu.es.test.User; import org.apache.http.HttpHost; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.ssl.SSLContextBuilder; import org.apache.http.ssl.SSLContexts; import org.elasticsearch.client.RestClient;
import javax.net.ssl.SSLContext; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.security.KeyStore; import java.security.cert.Certificate; import java.security.cert.CertificateFactory;
/**
- @author: zhangxin
@date: 2022/3/31 */ public class UpdateClient { public static void main(String[] args) throws Exception {
// 用户认证对象final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();// 设置账号密码credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("elastic", "wkZQNElpnNj6+QWflIBU"));Path caCertificatePath = Paths.get("d:/http_ca.crt");CertificateFactory factory = CertificateFactory.getInstance("X.509");Certificate trustedCa;try (InputStream is = Files.newInputStream(caCertificatePath)) {trustedCa = factory.generateCertificate(is);}KeyStore trustStore = KeyStore.getInstance("pkcs12");trustStore.load(null, null);trustStore.setCertificateEntry("ca", trustedCa);SSLContextBuilder sslContextBuilder = SSLContexts.custom().loadTrustMaterial(trustStore, null);final SSLContext sslContext = sslContextBuilder.build();// 创建 es 客户端RestClient restClient = RestClient.builder(new HttpHost("172.18.1.31", 9200, "https")).setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setSSLContext(sslContext).setDefaultCredentialsProvider(credentialsProvider)).build();// 使用 Jackson 映射器创建传输层ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());// 创建 API 客户端ElasticsearchClient esClient = new ElasticsearchClient(transport);User user = new User();user.setName("zhangsan");user.setAge(30);user.setSex("女");// 更新文档UpdateResponse<User> response = esClient.update(i -> i.index("user").id("1001").doc(user), User.class);System.out.println("_index:" + response.index());System.out.println("_id:" + response.id());System.out.println("_result:" + response.result());// 关闭 es 客户端transport.close();restClient.close();
} } ``` 执行结果:

- 查询文档 ```java package com.atguigu.es.test.document;
import co.elastic.clients.elasticsearch.ElasticsearchClient; import co.elastic.clients.elasticsearch.core.GetResponse; import co.elastic.clients.json.jackson.JacksonJsonpMapper; import co.elastic.clients.transport.ElasticsearchTransport; import co.elastic.clients.transport.rest_client.RestClientTransport; import com.atguigu.es.test.User; import org.apache.http.HttpHost; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.ssl.SSLContextBuilder; import org.apache.http.ssl.SSLContexts; import org.elasticsearch.client.RestClient;
import javax.net.ssl.SSLContext; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.security.KeyStore; import java.security.cert.Certificate; import java.security.cert.CertificateFactory;
/**
- @author: zhangxin
@date: 2022/3/31 */ public class GetClient { public static void main(String[] args) throws Exception {
// 用户认证对象final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();// 设置账号密码credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("elastic", "wkZQNElpnNj6+QWflIBU"));Path caCertificatePath = Paths.get("d:/http_ca.crt");CertificateFactory factory = CertificateFactory.getInstance("X.509");Certificate trustedCa;try (InputStream is = Files.newInputStream(caCertificatePath)) {trustedCa = factory.generateCertificate(is);}KeyStore trustStore = KeyStore.getInstance("pkcs12");trustStore.load(null, null);trustStore.setCertificateEntry("ca", trustedCa);SSLContextBuilder sslContextBuilder = SSLContexts.custom().loadTrustMaterial(trustStore, null);final SSLContext sslContext = sslContextBuilder.build();// 创建 es 客户端RestClient restClient = RestClient.builder(new HttpHost("172.18.1.31", 9200, "https")).setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setSSLContext(sslContext).setDefaultCredentialsProvider(credentialsProvider)).build();// 使用 Jackson 映射器创建传输层ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());// 创建 API 客户端ElasticsearchClient esClient = new ElasticsearchClient(transport);// 设置索引及唯一性标识// 客户端发送请求,获取响应对象GetResponse<User> response = esClient.get(i -> i.index("user").id("1001"), User.class);// 打印结果信息System.out.println("_index:" + response.index());System.out.println("source:" + response.source().toString());System.out.println("_id:" + response.id());// 关闭 es 客户端transport.close();restClient.close();
} } ``` 执行结果为:

- 删除文档 ```java package com.atguigu.es.test.document;
import co.elastic.clients.elasticsearch.ElasticsearchClient; import co.elastic.clients.elasticsearch.core.DeleteResponse; import co.elastic.clients.elasticsearch.core.GetResponse; import co.elastic.clients.json.jackson.JacksonJsonpMapper; import co.elastic.clients.transport.ElasticsearchTransport; import co.elastic.clients.transport.rest_client.RestClientTransport; import com.atguigu.es.test.User; import org.apache.http.HttpHost; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.ssl.SSLContextBuilder; import org.apache.http.ssl.SSLContexts; import org.elasticsearch.client.RestClient;
import javax.net.ssl.SSLContext; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.security.KeyStore; import java.security.cert.Certificate; import java.security.cert.CertificateFactory;
/**
- @author: zhangxin
@date: 2022/3/31 */ public class DeleteClient { public static void main(String[] args) throws Exception {
// 用户认证对象final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();// 设置账号密码credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("elastic", "wkZQNElpnNj6+QWflIBU"));Path caCertificatePath = Paths.get("d:/http_ca.crt");CertificateFactory factory = CertificateFactory.getInstance("X.509");Certificate trustedCa;try (InputStream is = Files.newInputStream(caCertificatePath)) {trustedCa = factory.generateCertificate(is);}KeyStore trustStore = KeyStore.getInstance("pkcs12");trustStore.load(null, null);trustStore.setCertificateEntry("ca", trustedCa);SSLContextBuilder sslContextBuilder = SSLContexts.custom().loadTrustMaterial(trustStore, null);final SSLContext sslContext = sslContextBuilder.build();// 创建 es 客户端RestClient restClient = RestClient.builder(new HttpHost("172.18.1.31", 9200, "https")).setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setSSLContext(sslContext).setDefaultCredentialsProvider(credentialsProvider)).build();// 使用 Jackson 映射器创建传输层ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());// 创建 API 客户端ElasticsearchClient esClient = new ElasticsearchClient(transport);// 设置索引及唯一性标识// 客户端发送请求,获取响应对象DeleteResponse response = esClient.delete(i -> i.index("user").id("1001"));// 打印结果信息System.out.println(response.toString());// 关闭 es 客户端transport.close();restClient.close();
} } ``` 执行结果为:

- 批量操作
批量新增
package com.atguigu.es.test.document.batch;import co.elastic.clients.elasticsearch.ElasticsearchClient;import co.elastic.clients.elasticsearch.core.BulkRequest;import co.elastic.clients.elasticsearch.core.BulkResponse;import co.elastic.clients.json.jackson.JacksonJsonpMapper;import co.elastic.clients.transport.ElasticsearchTransport;import co.elastic.clients.transport.rest_client.RestClientTransport;import com.atguigu.es.test.User;import org.apache.http.HttpHost;import org.apache.http.auth.AuthScope;import org.apache.http.auth.UsernamePasswordCredentials;import org.apache.http.client.CredentialsProvider;import org.apache.http.impl.client.BasicCredentialsProvider;import org.apache.http.ssl.SSLContextBuilder;import org.apache.http.ssl.SSLContexts;import org.elasticsearch.client.RestClient;import javax.net.ssl.SSLContext;import java.io.InputStream;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths;import java.security.KeyStore;import java.security.cert.Certificate;import java.security.cert.CertificateFactory;import java.util.ArrayList;import java.util.List;import java.util.Random;import java.util.concurrent.atomic.AtomicInteger;/*** @author: zhangxin* @date: 2022/3/31*/public class BatchInsertClient {public static void main(String[] args) throws Exception {// 用户认证对象final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();// 设置账号密码credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("elastic", "wkZQNElpnNj6+QWflIBU"));Path caCertificatePath = Paths.get("d:/http_ca.crt");CertificateFactory factory = CertificateFactory.getInstance("X.509");Certificate trustedCa;try (InputStream is = Files.newInputStream(caCertificatePath)) {trustedCa = factory.generateCertificate(is);}KeyStore trustStore = KeyStore.getInstance("pkcs12");trustStore.load(null, null);trustStore.setCertificateEntry("ca", trustedCa);SSLContextBuilder sslContextBuilder = SSLContexts.custom().loadTrustMaterial(trustStore, null);final SSLContext sslContext = sslContextBuilder.build();// 创建 es 客户端RestClient restClient = RestClient.builder(new HttpHost("172.18.1.31", 9200, "https")).setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setSSLContext(sslContext).setDefaultCredentialsProvider(credentialsProvider)).build();// 使用 Jackson 映射器创建传输层ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());// 创建 API 客户端ElasticsearchClient esClient = new ElasticsearchClient(transport);// 新增文档 请求对象// 创建数据对象List<User> list = new ArrayList<>();list.add(new User("zhangsan", 30, "男", "1001"));list.add(new User("lisi", 30, "男", "1002"));list.add(new User("wangwu", 30, "男", "1003"));// 设置索引及唯一性标识// 客户端发送请求,获取响应对象BulkRequest.Builder br = new BulkRequest.Builder();for (User user : list) {br.operations(op -> op.index(idx -> idx.index("user").id(user.getId()).document(user)));}BulkResponse response = esClient.bulk(br.build());// 打印结果信息System.out.println("took:" + response.took());System.out.println("items:" + response.items());// 关闭 es 客户端transport.close();restClient.close();}}
执行结果为:
批量删除:
package com.atguigu.es.test.document.batch;import co.elastic.clients.elasticsearch.ElasticsearchClient;import co.elastic.clients.elasticsearch.core.BulkRequest;import co.elastic.clients.elasticsearch.core.BulkResponse;import co.elastic.clients.elasticsearch.core.DeleteRequest;import co.elastic.clients.json.jackson.JacksonJsonpMapper;import co.elastic.clients.transport.ElasticsearchTransport;import co.elastic.clients.transport.rest_client.RestClientTransport;import com.atguigu.es.test.User;import org.apache.http.HttpHost;import org.apache.http.auth.AuthScope;import org.apache.http.auth.UsernamePasswordCredentials;import org.apache.http.client.CredentialsProvider;import org.apache.http.impl.client.BasicCredentialsProvider;import org.apache.http.ssl.SSLContextBuilder;import org.apache.http.ssl.SSLContexts;import org.elasticsearch.client.RequestOptions;import org.elasticsearch.client.RestClient;import javax.net.ssl.SSLContext;import java.io.InputStream;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths;import java.security.KeyStore;import java.security.cert.Certificate;import java.security.cert.CertificateFactory;import java.util.ArrayList;import java.util.List;import java.util.Random;/*** @author: zhangxin* @date: 2022/3/31*/public class BatchDeleteClient {public static void main(String[] args) throws Exception {// 用户认证对象final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();// 设置账号密码credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("elastic", "wkZQNElpnNj6+QWflIBU"));Path caCertificatePath = Paths.get("d:/http_ca.crt");CertificateFactory factory = CertificateFactory.getInstance("X.509");Certificate trustedCa;try (InputStream is = Files.newInputStream(caCertificatePath)) {trustedCa = factory.generateCertificate(is);}KeyStore trustStore = KeyStore.getInstance("pkcs12");trustStore.load(null, null);trustStore.setCertificateEntry("ca", trustedCa);SSLContextBuilder sslContextBuilder = SSLContexts.custom().loadTrustMaterial(trustStore, null);final SSLContext sslContext = sslContextBuilder.build();// 创建 es 客户端RestClient restClient = RestClient.builder(new HttpHost("172.18.1.31", 9200, "https")).setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setSSLContext(sslContext).setDefaultCredentialsProvider(credentialsProvider)).build();// 使用 Jackson 映射器创建传输层ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());// 创建 API 客户端ElasticsearchClient esClient = new ElasticsearchClient(transport);List<User> list = new ArrayList<>();list.add(new User("zhangsan", 30, "男", "1001"));list.add(new User("lisi", 30, "男", "1002"));list.add(new User("wangwu", 30, "男", "1003"));// 设置索引及唯一性标识// 客户端发送请求,获取响应对象BulkRequest.Builder br = new BulkRequest.Builder();for (User user : list) {br.operations(op -> op.delete(idx -> idx.index("user").id(user.getId())));}BulkResponse response = esClient.bulk(br.build());// 打印结果信息System.out.println("took:" + response.took());System.out.println("items:" + response.items());// 关闭 es 客户端transport.close();restClient.close();}}
2.2.5.5 高级查询
- 请求体查询
查询所有索引数据
package com.atguigu.es.test.query;import co.elastic.clients.elasticsearch.ElasticsearchClient;import co.elastic.clients.elasticsearch._types.query_dsl.Query;import co.elastic.clients.elasticsearch._types.query_dsl.QueryBuilders;import co.elastic.clients.elasticsearch.core.SearchRequest;import co.elastic.clients.elasticsearch.core.SearchResponse;import co.elastic.clients.elasticsearch.core.search.Hit;import co.elastic.clients.elasticsearch.indices.GetIndexResponse;import co.elastic.clients.elasticsearch.indices.IndexState;import co.elastic.clients.json.jackson.JacksonJsonpMapper;import co.elastic.clients.transport.ElasticsearchTransport;import co.elastic.clients.transport.rest_client.RestClientTransport;import com.atguigu.es.test.User;import org.apache.http.HttpHost;import org.apache.http.auth.AuthScope;import org.apache.http.auth.UsernamePasswordCredentials;import org.apache.http.client.CredentialsProvider;import org.apache.http.impl.client.BasicCredentialsProvider;import org.apache.http.ssl.SSLContextBuilder;import org.apache.http.ssl.SSLContexts;import org.elasticsearch.client.RequestOptions;import org.elasticsearch.client.RestClient;import javax.net.ssl.SSLContext;import java.io.InputStream;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths;import java.security.KeyStore;import java.security.cert.Certificate;import java.security.cert.CertificateFactory;import java.util.List;/*** @author: zhangxin* @date: 2022/3/31*/public class AllClient {private static Query.Builder q;public static void main(String[] args) throws Exception {// 用户认证对象final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();// 设置账号密码credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("elastic", "wkZQNElpnNj6+QWflIBU"));Path caCertificatePath = Paths.get("d:/http_ca.crt");CertificateFactory factory = CertificateFactory.getInstance("X.509");Certificate trustedCa;try (InputStream is = Files.newInputStream(caCertificatePath)) {trustedCa = factory.generateCertificate(is);}KeyStore trustStore = KeyStore.getInstance("pkcs12");trustStore.load(null, null);trustStore.setCertificateEntry("ca", trustedCa);SSLContextBuilder sslContextBuilder = SSLContexts.custom().loadTrustMaterial(trustStore, null);final SSLContext sslContext = sslContextBuilder.build();// 创建 es 客户端RestClient restClient = RestClient.builder(new HttpHost("172.18.1.31", 9200, "https")).setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setSSLContext(sslContext).setDefaultCredentialsProvider(credentialsProvider)).build();// 使用 Jackson 映射器创建传输层ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());// 创建 API 客户端ElasticsearchClient esClient = new ElasticsearchClient(transport);// 创建搜索请求对象SearchResponse<User> response = esClient.search(s -> s.index("user"), User.class);// 查询匹配System.out.println("took:" + response.took());System.out.println("timeout:" + response.timedOut());System.out.println("total:" + response.hits().total().value());System.out.println("MaxScore:" + response.hits().maxScore());System.out.println("hits========>>");List<Hit<User>> hits = response.hits().hits();for (Hit<User> hit: hits) {User user = hit.source();// 输出每条查询的结果信息System.out.println(user);}System.out.println("<<========");// 关闭 es 客户端transport.close();restClient.close();}}

term 查询,查询条件为关键字
package com.atguigu.es.test.query;import co.elastic.clients.elasticsearch.ElasticsearchClient;import co.elastic.clients.elasticsearch._types.query_dsl.Query;import co.elastic.clients.elasticsearch._types.query_dsl.QueryBuilders;import co.elastic.clients.elasticsearch.core.SearchResponse;import co.elastic.clients.elasticsearch.core.search.Hit;import co.elastic.clients.json.jackson.JacksonJsonpMapper;import co.elastic.clients.transport.ElasticsearchTransport;import co.elastic.clients.transport.rest_client.RestClientTransport;import com.atguigu.es.test.User;import org.apache.http.HttpHost;import org.apache.http.auth.AuthScope;import org.apache.http.auth.UsernamePasswordCredentials;import org.apache.http.client.CredentialsProvider;import org.apache.http.impl.client.BasicCredentialsProvider;import org.apache.http.ssl.SSLContextBuilder;import org.apache.http.ssl.SSLContexts;import org.elasticsearch.client.RestClient;import javax.net.ssl.SSLContext;import java.io.InputStream;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths;import java.security.KeyStore;import java.security.cert.Certificate;import java.security.cert.CertificateFactory;import java.util.List;/*** @author: zhangxin* @date: 2022/3/31*/public class TermClient {private static Query.Builder q;public static void main(String[] args) throws Exception {// 用户认证对象final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();// 设置账号密码credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("elastic", "wkZQNElpnNj6+QWflIBU"));Path caCertificatePath = Paths.get("d:/http_ca.crt");CertificateFactory factory = CertificateFactory.getInstance("X.509");Certificate trustedCa;try (InputStream is = Files.newInputStream(caCertificatePath)) {trustedCa = factory.generateCertificate(is);}KeyStore trustStore = KeyStore.getInstance("pkcs12");trustStore.load(null, null);trustStore.setCertificateEntry("ca", trustedCa);SSLContextBuilder sslContextBuilder = SSLContexts.custom().loadTrustMaterial(trustStore, null);final SSLContext sslContext = sslContextBuilder.build();// 创建 es 客户端RestClient restClient = RestClient.builder(new HttpHost("172.18.1.31", 9200, "https")).setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setSSLContext(sslContext).setDefaultCredentialsProvider(credentialsProvider)).build();// 使用 Jackson 映射器创建传输层ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());// 创建 API 客户端ElasticsearchClient esClient = new ElasticsearchClient(transport);// 创建搜索请求对象SearchResponse<User> response = esClient.search(s -> s.index("user").query(q -> q.match(t -> t.field("age").query("30"))),User.class);// 查询匹配System.out.println("took:" + response.took());System.out.println("timeout:" + response.timedOut());System.out.println("total:" + response.hits().total().value());System.out.println("MaxScore:" + response.hits().maxScore());System.out.println("hits========>>");List<Hit<User>> hits = response.hits().hits();for (Hit<User> hit : hits) {User user = hit.source();// 输出每条查询的结果信息System.out.println(user);}System.out.println("<<========");// 关闭 es 客户端transport.close();restClient.close();}}

分页查询
package com.atguigu.es.test.query;import co.elastic.clients.elasticsearch.ElasticsearchClient;import co.elastic.clients.elasticsearch._types.query_dsl.Query;import co.elastic.clients.elasticsearch.core.SearchResponse;import co.elastic.clients.elasticsearch.core.search.Hit;import co.elastic.clients.json.jackson.JacksonJsonpMapper;import co.elastic.clients.transport.ElasticsearchTransport;import co.elastic.clients.transport.rest_client.RestClientTransport;import com.atguigu.es.test.User;import org.apache.http.HttpHost;import org.apache.http.auth.AuthScope;import org.apache.http.auth.UsernamePasswordCredentials;import org.apache.http.client.CredentialsProvider;import org.apache.http.impl.client.BasicCredentialsProvider;import org.apache.http.ssl.SSLContextBuilder;import org.apache.http.ssl.SSLContexts;import org.elasticsearch.client.RestClient;import javax.net.ssl.SSLContext;import java.io.InputStream;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths;import java.security.KeyStore;import java.security.cert.Certificate;import java.security.cert.CertificateFactory;import java.util.List;/*** @author: zhangxin* @date: 2022/3/31*/public class PageClient {private static Query.Builder q;public static void main(String[] args) throws Exception {// 用户认证对象final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();// 设置账号密码credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("elastic", "wkZQNElpnNj6+QWflIBU"));Path caCertificatePath = Paths.get("d:/http_ca.crt");CertificateFactory factory = CertificateFactory.getInstance("X.509");Certificate trustedCa;try (InputStream is = Files.newInputStream(caCertificatePath)) {trustedCa = factory.generateCertificate(is);}KeyStore trustStore = KeyStore.getInstance("pkcs12");trustStore.load(null, null);trustStore.setCertificateEntry("ca", trustedCa);SSLContextBuilder sslContextBuilder = SSLContexts.custom().loadTrustMaterial(trustStore, null);final SSLContext sslContext = sslContextBuilder.build();// 创建 es 客户端RestClient restClient = RestClient.builder(new HttpHost("172.18.1.31", 9200, "https")).setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setSSLContext(sslContext).setDefaultCredentialsProvider(credentialsProvider)).build();// 使用 Jackson 映射器创建传输层ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());// 创建 API 客户端ElasticsearchClient esClient = new ElasticsearchClient(transport);// 创建搜索请求对象SearchResponse<User> response = esClient.search(s -> s.index("user").from(0).size(2), User.class);// 查询匹配System.out.println("took:" + response.took());System.out.println("timeout:" + response.timedOut());System.out.println("total:" + response.hits().total().value());System.out.println("MaxScore:" + response.hits().maxScore());System.out.println("hits========>>");List<Hit<User>> hits = response.hits().hits();for (Hit<User> hit : hits) {User user = hit.source();// 输出每条查询的结果信息System.out.println(user);}System.out.println("<<========");// 关闭 es 客户端transport.close();restClient.close();}}

数据排序
package com.atguigu.es.test.query;import co.elastic.clients.elasticsearch.ElasticsearchClient;import co.elastic.clients.elasticsearch._types.SortOptions;import co.elastic.clients.elasticsearch._types.SortOrder;import co.elastic.clients.elasticsearch._types.query_dsl.Query;import co.elastic.clients.elasticsearch.core.SearchResponse;import co.elastic.clients.elasticsearch.core.search.Hit;import co.elastic.clients.json.jackson.JacksonJsonpMapper;import co.elastic.clients.transport.ElasticsearchTransport;import co.elastic.clients.transport.rest_client.RestClientTransport;import com.atguigu.es.test.User;import org.apache.http.HttpHost;import org.apache.http.auth.AuthScope;import org.apache.http.auth.UsernamePasswordCredentials;import org.apache.http.client.CredentialsProvider;import org.apache.http.impl.client.BasicCredentialsProvider;import org.apache.http.ssl.SSLContextBuilder;import org.apache.http.ssl.SSLContexts;import org.elasticsearch.client.RestClient;import javax.net.ssl.SSLContext;import java.io.InputStream;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths;import java.security.KeyStore;import java.security.cert.Certificate;import java.security.cert.CertificateFactory;import java.util.List;/*** @author: zhangxin* @date: 2022/3/31*/public class SortClient {private static Query.Builder q;public static void main(String[] args) throws Exception {// 用户认证对象final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();// 设置账号密码credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("elastic", "wkZQNElpnNj6+QWflIBU"));Path caCertificatePath = Paths.get("d:/http_ca.crt");CertificateFactory factory = CertificateFactory.getInstance("X.509");Certificate trustedCa;try (InputStream is = Files.newInputStream(caCertificatePath)) {trustedCa = factory.generateCertificate(is);}KeyStore trustStore = KeyStore.getInstance("pkcs12");trustStore.load(null, null);trustStore.setCertificateEntry("ca", trustedCa);SSLContextBuilder sslContextBuilder = SSLContexts.custom().loadTrustMaterial(trustStore, null);final SSLContext sslContext = sslContextBuilder.build();// 创建 es 客户端RestClient restClient = RestClient.builder(new HttpHost("172.18.1.31", 9200, "https")).setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setSSLContext(sslContext).setDefaultCredentialsProvider(credentialsProvider)).build();// 使用 Jackson 映射器创建传输层ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());// 创建 API 客户端ElasticsearchClient esClient = new ElasticsearchClient(transport);// 创建搜索请求对象SearchResponse<User> response = esClient.search(s -> s.index("user").sort(so -> so.field(v -> v.field("age").order(SortOrder.Asc))), User.class);// 查询匹配System.out.println("took:" + response.took());System.out.println("timeout:" + response.timedOut());System.out.println("total:" + response.hits().total().value());System.out.println("MaxScore:" + response.hits().maxScore());System.out.println("hits========>>");List<Hit<User>> hits = response.hits().hits();for (Hit<User> hit : hits) {User user = hit.source();// 输出每条查询的结果信息System.out.println(user);}System.out.println("<<========");// 关闭 es 客户端transport.close();restClient.close();}}

过滤字段
package com.atguigu.es.test.query;import co.elastic.clients.elasticsearch.ElasticsearchClient;import co.elastic.clients.elasticsearch._types.query_dsl.Query;import co.elastic.clients.elasticsearch.core.SearchResponse;import co.elastic.clients.elasticsearch.core.search.Hit;import co.elastic.clients.json.jackson.JacksonJsonpMapper;import co.elastic.clients.transport.ElasticsearchTransport;import co.elastic.clients.transport.rest_client.RestClientTransport;import com.atguigu.es.test.User;import org.apache.http.HttpHost;import org.apache.http.auth.AuthScope;import org.apache.http.auth.UsernamePasswordCredentials;import org.apache.http.client.CredentialsProvider;import org.apache.http.impl.client.BasicCredentialsProvider;import org.apache.http.ssl.SSLContextBuilder;import org.apache.http.ssl.SSLContexts;import org.elasticsearch.client.RestClient;import javax.net.ssl.SSLContext;import java.io.InputStream;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths;import java.security.KeyStore;import java.security.cert.Certificate;import java.security.cert.CertificateFactory;import java.util.List;/*** @author: zhangxin* @date: 2022/3/31*/public class FetchClient {private static Query.Builder q;public static void main(String[] args) throws Exception {// 用户认证对象final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();// 设置账号密码credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("elastic", "wkZQNElpnNj6+QWflIBU"));Path caCertificatePath = Paths.get("d:/http_ca.crt");CertificateFactory factory = CertificateFactory.getInstance("X.509");Certificate trustedCa;try (InputStream is = Files.newInputStream(caCertificatePath)) {trustedCa = factory.generateCertificate(is);}KeyStore trustStore = KeyStore.getInstance("pkcs12");trustStore.load(null, null);trustStore.setCertificateEntry("ca", trustedCa);SSLContextBuilder sslContextBuilder = SSLContexts.custom().loadTrustMaterial(trustStore, null);final SSLContext sslContext = sslContextBuilder.build();// 创建 es 客户端RestClient restClient = RestClient.builder(new HttpHost("172.18.1.31", 9200, "https")).setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setSSLContext(sslContext).setDefaultCredentialsProvider(credentialsProvider)).build();// 使用 Jackson 映射器创建传输层ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());// 创建 API 客户端ElasticsearchClient esClient = new ElasticsearchClient(transport);// 创建搜索请求对象SearchResponse<User> response = esClient.search(s -> s.index("user").source(f -> f.filter(m -> m.includes("name", "age"))), User.class);// 查询匹配System.out.println("took:" + response.took());System.out.println("timeout:" + response.timedOut());System.out.println("total:" + response.hits().total().value());System.out.println("MaxScore:" + response.hits().maxScore());System.out.println("hits========>>");List<Hit<User>> hits = response.hits().hits();for (Hit<User> hit : hits) {User user = hit.source();// 输出每条查询的结果信息System.out.println(user);}System.out.println("<<========");// 关闭 es 客户端transport.close();restClient.close();}}

Bool 查询
package com.atguigu.es.test.query;import co.elastic.clients.elasticsearch.ElasticsearchClient;import co.elastic.clients.elasticsearch._types.query_dsl.Query;import co.elastic.clients.elasticsearch._types.query_dsl.QueryBuilders;import co.elastic.clients.elasticsearch.core.SearchResponse;import co.elastic.clients.elasticsearch.core.search.Hit;import co.elastic.clients.json.jackson.JacksonJsonpMapper;import co.elastic.clients.transport.ElasticsearchTransport;import co.elastic.clients.transport.rest_client.RestClientTransport;import com.atguigu.es.test.User;import org.apache.http.HttpHost;import org.apache.http.auth.AuthScope;import org.apache.http.auth.UsernamePasswordCredentials;import org.apache.http.client.CredentialsProvider;import org.apache.http.impl.client.BasicCredentialsProvider;import org.apache.http.ssl.SSLContextBuilder;import org.apache.http.ssl.SSLContexts;import org.elasticsearch.client.RestClient;import javax.net.ssl.SSLContext;import java.io.InputStream;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths;import java.security.KeyStore;import java.security.cert.Certificate;import java.security.cert.CertificateFactory;import java.util.List;/*** @author: zhangxin* @date: 2022/3/31*/public class BoolClient {private static Query.Builder q;public static void main(String[] args) throws Exception {// 用户认证对象final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();// 设置账号密码credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("elastic", "wkZQNElpnNj6+QWflIBU"));Path caCertificatePath = Paths.get("d:/http_ca.crt");CertificateFactory factory = CertificateFactory.getInstance("X.509");Certificate trustedCa;try (InputStream is = Files.newInputStream(caCertificatePath)) {trustedCa = factory.generateCertificate(is);}KeyStore trustStore = KeyStore.getInstance("pkcs12");trustStore.load(null, null);trustStore.setCertificateEntry("ca", trustedCa);SSLContextBuilder sslContextBuilder = SSLContexts.custom().loadTrustMaterial(trustStore, null);final SSLContext sslContext = sslContextBuilder.build();// 创建 es 客户端RestClient restClient = RestClient.builder(new HttpHost("172.18.1.31", 9200, "https")).setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setSSLContext(sslContext).setDefaultCredentialsProvider(credentialsProvider)).build();// 使用 Jackson 映射器创建传输层ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());// 创建 API 客户端ElasticsearchClient esClient = new ElasticsearchClient(transport);// 创建搜索请求对象SearchResponse<User> response = esClient.search(s -> s.index("user").query(q -> q.bool(b ->b.must(qu -> qu.match(m -> m.field("age").query("30"))).mustNot(mn -> mn.match(m -> m.field("name").query("zhangsan"))).should(sh -> sh.match(m -> m.field("sex").query("男"))))), User.class);// 查询匹配System.out.println("took:" + response.took());System.out.println("timeout:" + response.timedOut());System.out.println("total:" + response.hits().total().value());System.out.println("MaxScore:" + response.hits().maxScore());System.out.println("hits========>>");List<Hit<User>> hits = response.hits().hits();for (Hit<User> hit : hits) {User user = hit.source();// 输出每条查询的结果信息System.out.println(user);}System.out.println("<<========");// 关闭 es 客户端transport.close();restClient.close();}}

范围查询
package com.atguigu.es.test.query;import co.elastic.clients.elasticsearch.ElasticsearchClient;import co.elastic.clients.elasticsearch._types.query_dsl.Query;import co.elastic.clients.elasticsearch.core.SearchResponse;import co.elastic.clients.elasticsearch.core.search.Hit;import co.elastic.clients.json.JsonData;import co.elastic.clients.json.jackson.JacksonJsonpMapper;import co.elastic.clients.transport.ElasticsearchTransport;import co.elastic.clients.transport.rest_client.RestClientTransport;import com.atguigu.es.test.User;import org.apache.http.HttpHost;import org.apache.http.auth.AuthScope;import org.apache.http.auth.UsernamePasswordCredentials;import org.apache.http.client.CredentialsProvider;import org.apache.http.impl.client.BasicCredentialsProvider;import org.apache.http.ssl.SSLContextBuilder;import org.apache.http.ssl.SSLContexts;import org.elasticsearch.client.RestClient;import javax.net.ssl.SSLContext;import java.io.InputStream;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths;import java.security.KeyStore;import java.security.cert.Certificate;import java.security.cert.CertificateFactory;import java.util.List;/*** @author: zhangxin* @date: 2022/3/31*/public class RangeClient {private static Query.Builder q;public static void main(String[] args) throws Exception {// 用户认证对象final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();// 设置账号密码credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("elastic", "wkZQNElpnNj6+QWflIBU"));Path caCertificatePath = Paths.get("d:/http_ca.crt");CertificateFactory factory = CertificateFactory.getInstance("X.509");Certificate trustedCa;try (InputStream is = Files.newInputStream(caCertificatePath)) {trustedCa = factory.generateCertificate(is);}KeyStore trustStore = KeyStore.getInstance("pkcs12");trustStore.load(null, null);trustStore.setCertificateEntry("ca", trustedCa);SSLContextBuilder sslContextBuilder = SSLContexts.custom().loadTrustMaterial(trustStore, null);final SSLContext sslContext = sslContextBuilder.build();// 创建 es 客户端RestClient restClient = RestClient.builder(new HttpHost("172.18.1.31", 9200, "https")).setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setSSLContext(sslContext).setDefaultCredentialsProvider(credentialsProvider)).build();// 使用 Jackson 映射器创建传输层ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());// 创建 API 客户端ElasticsearchClient esClient = new ElasticsearchClient(transport);// 创建搜索请求对象SearchResponse<User> response = esClient.search(s -> s.index("user").query(q -> q.range(r -> r.field("age").gte(JsonData.of("30")).lte(JsonData.of("40")))), User.class);// 查询匹配System.out.println("took:" + response.took());System.out.println("timeout:" + response.timedOut());System.out.println("total:" + response.hits().total().value());System.out.println("MaxScore:" + response.hits().maxScore());System.out.println("hits========>>");List<Hit<User>> hits = response.hits().hits();for (Hit<User> hit : hits) {User user = hit.source();// 输出每条查询的结果信息System.out.println(user);}System.out.println("<<========");// 关闭 es 客户端transport.close();restClient.close();}}

模糊查询
package com.atguigu.es.test.query;import co.elastic.clients.elasticsearch.ElasticsearchClient;import co.elastic.clients.elasticsearch._types.query_dsl.Query;import co.elastic.clients.elasticsearch.core.SearchResponse;import co.elastic.clients.elasticsearch.core.search.Hit;import co.elastic.clients.json.jackson.JacksonJsonpMapper;import co.elastic.clients.transport.ElasticsearchTransport;import co.elastic.clients.transport.rest_client.RestClientTransport;import com.atguigu.es.test.User;import org.apache.http.HttpHost;import org.apache.http.auth.AuthScope;import org.apache.http.auth.UsernamePasswordCredentials;import org.apache.http.client.CredentialsProvider;import org.apache.http.impl.client.BasicCredentialsProvider;import org.apache.http.ssl.SSLContextBuilder;import org.apache.http.ssl.SSLContexts;import org.elasticsearch.client.RestClient;import javax.net.ssl.SSLContext;import java.io.InputStream;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths;import java.security.KeyStore;import java.security.cert.Certificate;import java.security.cert.CertificateFactory;import java.util.List;/*** @author: zhangxin* @date: 2022/3/31*/public class FuzzyClient {private static Query.Builder q;public static void main(String[] args) throws Exception {// 用户认证对象final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();// 设置账号密码credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("elastic", "wkZQNElpnNj6+QWflIBU"));Path caCertificatePath = Paths.get("d:/http_ca.crt");CertificateFactory factory = CertificateFactory.getInstance("X.509");Certificate trustedCa;try (InputStream is = Files.newInputStream(caCertificatePath)) {trustedCa = factory.generateCertificate(is);}KeyStore trustStore = KeyStore.getInstance("pkcs12");trustStore.load(null, null);trustStore.setCertificateEntry("ca", trustedCa);SSLContextBuilder sslContextBuilder = SSLContexts.custom().loadTrustMaterial(trustStore, null);final SSLContext sslContext = sslContextBuilder.build();// 创建 es 客户端RestClient restClient = RestClient.builder(new HttpHost("172.18.1.31", 9200, "https")).setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setSSLContext(sslContext).setDefaultCredentialsProvider(credentialsProvider)).build();// 使用 Jackson 映射器创建传输层ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());// 创建 API 客户端ElasticsearchClient esClient = new ElasticsearchClient(transport);// 创建搜索请求对象SearchResponse<User> response = esClient.search(s -> s.index("user").query(q -> q.fuzzy(f -> f.field("name").value("zhangsan").fuzziness("1"))), User.class);// 查询匹配System.out.println("took:" + response.took());System.out.println("timeout:" + response.timedOut());System.out.println("total:" + response.hits().total().value());System.out.println("MaxScore:" + response.hits().maxScore());System.out.println("hits========>>");List<Hit<User>> hits = response.hits().hits();for (Hit<User> hit : hits) {User user = hit.source();// 输出每条查询的结果信息System.out.println(user);}System.out.println("<<========");// 关闭 es 客户端transport.close();restClient.close();}}

- 高亮查询 ```java package com.atguigu.es.test.query;
import co.elastic.clients.elasticsearch.ElasticsearchClient; import co.elastic.clients.elasticsearch._types.query_dsl.Query; import co.elastic.clients.elasticsearch.core.SearchResponse; import co.elastic.clients.elasticsearch.core.search.Hit; import co.elastic.clients.json.jackson.JacksonJsonpMapper; import co.elastic.clients.transport.ElasticsearchTransport; import co.elastic.clients.transport.rest_client.RestClientTransport; import com.atguigu.es.test.User; import org.apache.http.HttpHost; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.ssl.SSLContextBuilder; import org.apache.http.ssl.SSLContexts; import org.elasticsearch.client.RestClient;
import javax.net.ssl.SSLContext; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.security.KeyStore; import java.security.cert.Certificate; import java.security.cert.CertificateFactory; import java.util.List;
/**
- @author: zhangxin
@date: 2022/3/31 */ public class HighlightClient { private static Query.Builder q;
public static void main(String[] args) throws Exception {
// 用户认证对象final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();// 设置账号密码credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("elastic", "wkZQNElpnNj6+QWflIBU"));Path caCertificatePath = Paths.get("d:/http_ca.crt");CertificateFactory factory = CertificateFactory.getInstance("X.509");Certificate trustedCa;try (InputStream is = Files.newInputStream(caCertificatePath)) {trustedCa = factory.generateCertificate(is);}KeyStore trustStore = KeyStore.getInstance("pkcs12");trustStore.load(null, null);trustStore.setCertificateEntry("ca", trustedCa);SSLContextBuilder sslContextBuilder = SSLContexts.custom().loadTrustMaterial(trustStore, null);final SSLContext sslContext = sslContextBuilder.build();// 创建 es 客户端RestClient restClient = RestClient.builder(new HttpHost("172.18.1.31", 9200, "https")).setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setSSLContext(sslContext).setDefaultCredentialsProvider(credentialsProvider)).build();// 使用 Jackson 映射器创建传输层ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());// 创建 API 客户端ElasticsearchClient esClient = new ElasticsearchClient(transport);// 创建搜索请求对象SearchResponse<User> response = esClient.search(s -> s.index("user").query(q -> q.term(t -> t.field("name").value("zhangsan"))).highlight(h -> h.fields("name", hh -> hh.preTags("<font color='red'>").postTags("</font>"))), User.class);// 查询匹配System.out.println("took:" + response.took());System.out.println("timeout:" + response.timedOut());System.out.println("total:" + response.hits().total().value());System.out.println("MaxScore:" + response.hits().maxScore());System.out.println("hits========>>");List<Hit<User>> hits = response.hits().hits();for (Hit<User> hit : hits) {System.out.println(hit.highlight().get("name").get(0));User user = hit.source();// 输出每条查询的结果信息System.out.println(user);}System.out.println("<<========");// 关闭 es 客户端transport.close();restClient.close();
} } ```

- 聚合查询
最大年龄
package com.atguigu.es.test.query.aggregation;import co.elastic.clients.elasticsearch.ElasticsearchClient;import co.elastic.clients.elasticsearch._types.aggregations.HistogramBucket;import co.elastic.clients.elasticsearch._types.aggregations.MaxAggregate;import co.elastic.clients.elasticsearch._types.query_dsl.Query;import co.elastic.clients.elasticsearch.core.SearchResponse;import co.elastic.clients.elasticsearch.core.search.Hit;import co.elastic.clients.json.jackson.JacksonJsonpMapper;import co.elastic.clients.transport.ElasticsearchTransport;import co.elastic.clients.transport.rest_client.RestClientTransport;import com.atguigu.es.test.User;import org.apache.http.HttpHost;import org.apache.http.auth.AuthScope;import org.apache.http.auth.UsernamePasswordCredentials;import org.apache.http.client.CredentialsProvider;import org.apache.http.impl.client.BasicCredentialsProvider;import org.apache.http.ssl.SSLContextBuilder;import org.apache.http.ssl.SSLContexts;import org.elasticsearch.client.RestClient;import javax.net.ssl.SSLContext;import java.io.InputStream;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths;import java.security.KeyStore;import java.security.cert.Certificate;import java.security.cert.CertificateFactory;import java.util.List;/*** @author: zhangxin* @date: 2022/3/31*/public class AggregagionClient {private static Query.Builder q;public static void main(String[] args) throws Exception {// 用户认证对象final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();// 设置账号密码credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("elastic", "wkZQNElpnNj6+QWflIBU"));Path caCertificatePath = Paths.get("d:/http_ca.crt");CertificateFactory factory = CertificateFactory.getInstance("X.509");Certificate trustedCa;try (InputStream is = Files.newInputStream(caCertificatePath)) {trustedCa = factory.generateCertificate(is);}KeyStore trustStore = KeyStore.getInstance("pkcs12");trustStore.load(null, null);trustStore.setCertificateEntry("ca", trustedCa);SSLContextBuilder sslContextBuilder = SSLContexts.custom().loadTrustMaterial(trustStore, null);final SSLContext sslContext = sslContextBuilder.build();// 创建 es 客户端RestClient restClient = RestClient.builder(new HttpHost("172.18.1.31", 9200, "https")).setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setSSLContext(sslContext).setDefaultCredentialsProvider(credentialsProvider)).build();// 使用 Jackson 映射器创建传输层ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());// 创建 API 客户端ElasticsearchClient esClient = new ElasticsearchClient(transport);// 创建搜索请求对象SearchResponse<User> response = esClient.search(s -> s.index("user").aggregations("maxAge", agg -> agg.max(ag -> ag.field("age"))), User.class);// 查询匹配System.out.println("took:" + response.took());System.out.println("timeout:" + response.timedOut());System.out.println("total:" + response.hits().total().value());System.out.println("MaxScore:" + response.hits().maxScore());System.out.println("hits========>>");MaxAggregate maxAge = response.aggregations().get("maxAge").max();System.out.println("最大年龄" + maxAge.value() + "岁");System.out.println("<<========");// 关闭 es 客户端transport.close();restClient.close();}}

分组统计
package com.atguigu.es.test.query.aggregation;import co.elastic.clients.elasticsearch.ElasticsearchClient;import co.elastic.clients.elasticsearch._types.aggregations.LongTermsBucket;import co.elastic.clients.elasticsearch._types.query_dsl.Query;import co.elastic.clients.elasticsearch.core.SearchResponse;import co.elastic.clients.elasticsearch.core.search.Hit;import co.elastic.clients.json.jackson.JacksonJsonpMapper;import co.elastic.clients.transport.ElasticsearchTransport;import co.elastic.clients.transport.rest_client.RestClientTransport;import com.atguigu.es.test.User;import org.apache.http.HttpHost;import org.apache.http.auth.AuthScope;import org.apache.http.auth.UsernamePasswordCredentials;import org.apache.http.client.CredentialsProvider;import org.apache.http.impl.client.BasicCredentialsProvider;import org.apache.http.ssl.SSLContextBuilder;import org.apache.http.ssl.SSLContexts;import org.elasticsearch.client.RestClient;import javax.net.ssl.SSLContext;import java.io.InputStream;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths;import java.security.KeyStore;import java.security.cert.Certificate;import java.security.cert.CertificateFactory;import java.util.List;/*** @author: zhangxin* @date: 2022/3/31*/public class GroupClient {private static Query.Builder q;public static void main(String[] args) throws Exception {// 用户认证对象final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();// 设置账号密码credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("elastic", "wkZQNElpnNj6+QWflIBU"));Path caCertificatePath = Paths.get("d:/http_ca.crt");CertificateFactory factory = CertificateFactory.getInstance("X.509");Certificate trustedCa;try (InputStream is = Files.newInputStream(caCertificatePath)) {trustedCa = factory.generateCertificate(is);}KeyStore trustStore = KeyStore.getInstance("pkcs12");trustStore.load(null, null);trustStore.setCertificateEntry("ca", trustedCa);SSLContextBuilder sslContextBuilder = SSLContexts.custom().loadTrustMaterial(trustStore, null);final SSLContext sslContext = sslContextBuilder.build();// 创建 es 客户端RestClient restClient = RestClient.builder(new HttpHost("172.18.1.31", 9200, "https")).setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setSSLContext(sslContext).setDefaultCredentialsProvider(credentialsProvider)).build();// 使用 Jackson 映射器创建传输层ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());// 创建 API 客户端ElasticsearchClient esClient = new ElasticsearchClient(transport);// 创建搜索请求对象SearchResponse<User> response = esClient.search(s -> s.index("user").aggregations("age groupby", agg -> agg.terms(ag -> ag.field("age"))), User.class);// 查询匹配System.out.println("took:" + response.took());System.out.println("timeout:" + response.timedOut());System.out.println("total:" + response.hits().total().value());System.out.println("MaxScore:" + response.hits().maxScore());System.out.println("hits========>>");List<LongTermsBucket> buckets = response.aggregations().get("age groupby").lterms().buckets().array();for (LongTermsBucket bucket : buckets) {System.out.println(bucket.key() + "岁有" + bucket.docCount() + "人");}System.out.println("<<========");// 关闭 es 客户端transport.close();restClient.close();}}





