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 的目录结构如下
第 2 章 Elasticsearch 入门 - 图1

目录 含义
bin 可执行脚本目录
config 配置目录
jdk 内置 JDK 目录
lib 类库
logs 日志目录
modules 模块目录
plugins 插件目录

解压后,进入 bin 文件目录,点击 elasticsearch.bat 文件启动 ES 服务
第 2 章 Elasticsearch 入门 - 图2
注意:9300 端口为 Elasticsearch 集群间组件的通信端口,9200 端口为浏览器访问的 http 协议 RESTful 端口。
第一次启动时会自动生成对应的用户名和密码,以及 kibana 连接所需要的 token,需要记下来,下一次再启动则不再显示
image.png
打开浏览器(推荐使用谷歌浏览器),输入地址:https://localhost:9200,输入对应的用户名和密码测试结果
image.png

2.1.3 问题解决

  • Elasticsearch 是使用 java 开发的,且 8.x 版本的 ES 需要 JDK 版本 17 以上,默认安装包带有 jdk 环境,如果系统配置 JAVA_HOME,那么使用系统默认的 JDK,如果没有配置使用自带的 JDK,一般建议使用系统配置的 JDK。
  • 双击启动窗口闪退,通过路径访问追踪错误,如果是“空间不足”,请修改 config/jvm.options 配置文件
    1. # 设置 JVM 初始内存为 4G 。此值可以设置与 Xmx 相同,以避免每次垃圾回收完成后 JVM 重新分配内存
    2. # Xms represents the initial size of total heap space
    3. # 设置 JVM 最大可用内存为 4G
    4. # Xmx represents the maximum size of total heap space
    5. Xms4g
    6. Xmx4g

    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/
    第 2 章 Elasticsearch 入门 - 图5
    注意:在使用时需要配置 Authorization 参数,否则请求会失败
    image.png

    2.2.3 数据格式

    Elasticsearch 是面向文档型数据库,一条数据在这里就是一个文档。为了方便大家理解,我们将 Elasticsearch 里存储文档数据和关系型数据库 MySQL 存储数据的概念进行一个类比
    第 2 章 Elasticsearch 入门 - 图7
    ES 里的 Index 可以看做一个库,而 Types 相当于表,Documents 则相当于表的行。这里 Types 的概念已经被逐渐弱化,Elasticsearch 6.X 中,一个 index 下已经只能包含一个 type,Elasticsearch 7.X 中,Type 的概念已经被删除了。
    用 JSON 作为文档序列化的格式,比如一条用户信息:
    1. {
    2. "name": "John",
    3. "sex": "Male",
    4. "age": 25,
    5. "birthDate": "1990/05/01",
    6. "about": "I love to go rock climbing",
    7. "interests": ["sports", "music"]
    8. }

    2.2.4 HTTP 操作

    2.2.4.1 索引操作

  1. 创建索引

对比关系型数据库,创建索引就等同于创建数据库
在 Postman 中,向 ES 服务器发 PUT 请求:http://127.0.0.1:9200/shopping
第 2 章 Elasticsearch 入门 - 图8
请求后,服务器返回响应
第 2 章 Elasticsearch 入门 - 图9

  1. {
  2. "acknowledged": true, #响应结果
  3. "shards_acknowledged": true, #分片结果
  4. "index": "shopping" #索引名称
  5. }

注意:创建索引库的分片数默认 1 片,在 7.0.0 之前的 Elasticsearch 版本中,默认 5 片
如果重复添加索引,会返回错误信息
第 2 章 Elasticsearch 入门 - 图10

  1. 查看所有索引

在 Postman 中,向 ES 服务器发 GET 请求:http://127.0.0.1:9200/_cat/indices?v
第 2 章 Elasticsearch 入门 - 图11
这里请求路径中的 _cat 表示查看的意思,indices 表示索引,所以整体含义就是查看当前 ES 服务器中的所有索引,就好像 MySQL 中的 show tables 的感觉,服务器响应结果如下
第 2 章 Elasticsearch 入门 - 图12

表头 含义
health 当前服务器健康状态:
green(集群完整)yellow(单点正常、集群不完整)red(单点不正常)
status 索引打开、关闭状态
index 索引名
uuid 索引统一编号
pri 主分片数量
rep 副本数量
docs.count 可用文档数量
docs.deleted 文档删除状态(逻辑删除)
store.size 主分片和副分片整体占空间大小
pri.store.size 主分片占空间大小
  1. 查看单个索引

在 Postman 中,向 ES 服务器发 GET 请求:http://127.0.0.1:9200/shopping
第 2 章 Elasticsearch 入门 - 图13
查看索引向 ES 服务器发送的请求路径和创建索引是一致的。但是 HTTP 方法不一致。这里可以体会一下 Restful 的意义,请求后,服务器响应结果如下:
第 2 章 Elasticsearch 入门 - 图14
image.png

  1. 删除索引

在 Postman 中,向 ES 服务器发 DELETE 请求:http://127.0.0.1:9200/shopping
第 2 章 Elasticsearch 入门 - 图16
第 2 章 Elasticsearch 入门 - 图17
重新访问索引时,服务器返回响应:索引不存在
第 2 章 Elasticsearch 入门 - 图18
第 2 章 Elasticsearch 入门 - 图19

2.2.4.2 文档操作

  1. 创建文档

索引已经创建好了,接下来我们来创建文档,并添加数据。这里的文档可以类比为关系型数据库中的表数据,添加的数据格式为 JSON 格式
在 Postman 中,向 ES 服务器发 POST 请求 http://127.0.0.1:9200/shopping/_doc
请求体内容为:

  1. {
  2. "title": "小米手机",
  3. "category": "小米",
  4. "images": "http://www.gulixueyuan.com/xm.jpg",
  5. "price": 3999.00
  6. }

image.png
此处发送请求的方式必须为 POST ,不能是 PUT ,否则会发生错误,因为 POST 不是幂等性,PUT 是幂等性,这里创建文档不是幂等性。
image.png
服务器响应结果如下:
image.png
image.png
上面的数据创建后,由于没有指定数据唯一性标识(ID),默认情况下 ES 服务器会随机生成一个 。如果想要自定义唯一性标识,需要在创建时指定 http://127.0.0.1:9200/shopping/_doc/1
image.png
image.png
此处需要注意:如果增加数据时明确数据主键,那么请求方式也可以为 PUT

  1. 查看文档

查看文档时,需要指明文档的唯一性标识,类似于 MySQL 中数据的主键查询
在 Postman 中,向 ES 服务器发 GET 请求 http://127.0.0.1:9200/shopping /_doc/1
image.png
查询成功后,服务器响应结果:
image.png
image.png

  1. 修改文档

和新增文档一样,输入相同的 URL 地址请求,如果请求体变化,会将原有的数据内容覆盖
在 Postman 中,向 ES 服 务器发 POST 请求 http://127.0.0.1:9200/shopping/_doc/1
请求体内容为:

  1. {
  2. "title": "华为手机",
  3. "category": "华为",
  4. "images": "http://www.gulixueyuan.com/hw.jpg",
  5. "price": 4999.00
  6. }

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

  1. 修改字段

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

  1. {
  2. "doc": {
  3. "price": 3000.00
  4. }
  5. }

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

  1. 删除文档

删除一个文档不会立即从磁盘上移除,它只是被标记成已删除(逻辑删除)。
在 Postman 中,向 ES 服务器发 DELETE 请求 http://127.0.0.1:9200/shopping/_doc/1
image.png
删除成功,服务器响应结果:
image.png
image.png
删除后再查询当前文档信息
image.png
image.png
如果删除一个并不存在的文档
image.png
image.png
image.png

  1. 条件删除文档

一般删除数据都是根据文档的唯一性标识进行删除,实际操作时,也可以根据条件对多条数据进行删除
首先分别增加多条数据:

  1. [{
  2. "title": "小米手机",
  3. "category": "小米",
  4. "images": "http://www.gulixueyuan.com/xm.jpg",
  5. "price": 4000.00
  6. }, {
  7. "title": "华为手机",
  8. "category": "华为",
  9. "images": "http://www.gulixueyuan.com/hw.jpg ",
  10. "price": 4000.00
  11. }]

image.png
image.png
向 ES 服务器发 POST 请求 http://127.0.0.1:9200/shopping/_delete_by_query
请求体内容为:

  1. {
  2. " query": {
  3. "match": {
  4. "price": 4000.00
  5. }
  6. }
  7. }

image.png
删除成功后,服务器响应结果:
image.png
image.png

2.2.4.3 映射操作

有了索引库,等于有了数据库中的 database。
接下来就需要建索引库(index)中的映射了,类似于数据库(database)中的表结构(table)。创建数据库表需要设置字段名称,类型,长度,约束等;索引库也一样,需要知道这个类型下有哪些字段,每个字段有哪些约束信息,这就叫做映射(mapping)。

  1. 创建映射

在 Postman 中,向 ES 服务器发 PUT 请求 http://127.0.0.1:9200/student/_mapping
请求体内容为:

  1. {
  2. "properties": {
  3. "name": {
  4. "type": "text",
  5. "index": true
  6. },
  7. "sex": {
  8. "type": "text",
  9. "index": false
  10. },
  11. "age": {
  12. "type": "long",
  13. "index": false
  14. }
  15. }
  16. }

image.png
服务器响应结果如下:
image.png
映射数据说明:

  • 字段名:任意填写,下面指定许多属性,例如:title 、subtitle、images、price
  • type:类型,Elasticsearch 中支持的数据类型非常丰富,说几个关键的:
    • String 类型,又分两种:
      • text:可分词
      • keyword:不可分词,数据会作为完整字段进行匹配
    • Numerical:数值类型,分两类
      • 基本数据类型:long、integer、short、byte、double、float、half_float
      • 浮点数的高精度类型:scaled_float
    • Date:日期类型
    • Array:数组类型
    • Object:对象
  • index:是否索引,默认为 true,也就是说你不进行任何配置,所有字段都会被索引。
    • true:字段会被索引,则可以用来进行搜索
    • false:字段不会被索引,不能用来搜索
  • store:是否将数据进行独立存储,默认为 false
    原始的文本会存储在 _source 里面,默认情况下其他提取出来的字段都不是独立存储的,是从 _source 里面提取出来的。当然你也可以独立的存储某个字段,只要设置”store”: true 即可,获取独立存储的字段要比从 _source 中解析快得多,但是也会占用更多的空间,所以要根据实际业务需求来设置。
  • analyzer:分词器,这里的 ik_max_word 即使用 ik 分词器 后面会有专门的章节学习
  1. 查看映射

在 Postman 中,向 ES 服务器发 GET 请求 http://127.0.0.1:9200/student/_mapping
image.png
服务器响应结果如下:
image.png

  1. 索引映射关联

在 Postman 中,向 ES 服务器发 PUT 请求 http://127.0.0.1:9200/student1

  1. {
  2. "settings": {},
  3. "mappings": {
  4. "properties": {
  5. "name": {
  6. "type": "text",
  7. "index": true
  8. },
  9. "sex": {
  10. "type": "text",
  11. "index": false
  12. },
  13. "age": {
  14. "type": "long",
  15. "index": false
  16. }
  17. }
  18. }
  19. }

image.png
服务器响应结果如下:
image.png

2.2.2.4 高级查询

Elasticsearch 提供了基于 JSON 提供完整的查询 DSL 来定义查询
定义数据:
POST /student/_doc/1001

  1. {
  2. "name": "zhangsan",
  3. "nickname": "zhangsan",
  4. "sex": "男",
  5. "age": 30
  6. }

POST /student/_doc/1002

  1. {
  2. "name": "lisi",
  3. "nickname": "lisi",
  4. "sex": "男",
  5. "age": 20
  6. }

POST /student/_doc/1003

  1. {
  2. "name": "wangwu",
  3. "nickname": "wangwu",
  4. "sex": "女",
  5. "age": 40
  6. }

POST /student/_doc/1004

  1. {
  2. "name": "zhangsanl",
  3. "nickname": "zhangsan1",
  4. "sex": "女",
  5. "age": 50
  6. }

POST /student/_doc/1005

  1. {
  2. "name": " zhangsan2",
  3. "nickname": "zhanqsan2",
  4. "sex": "女",
  5. "age": 30
  6. }
  1. 查询所有文档

在 Postman 中,向 ES 服务器发 GET 请求 http://127.0.0.1:9200/student/_search

  1. {
  2. "query": {
  3. "match_all": {}
  4. }
  5. }

“query”:这里的 query 代表一个查询对象,里面可以有不同的查询属性
“match_ all”:查询类型,例如 match_all(代表查询所有),match、term、range 等等
{查询条件}:查询条件会根据类型的不同,写法也有差异
image.png
服务器响应结果如下:
image.png
image.png
image.png

  1. 匹配查询

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

  1. {
  2. "query": {
  3. "match": {
  4. "name": "zhangsan"
  5. }
  6. }
  7. }

image.png
服务器响应结果为:
image.png

  1. 字段匹配查询

multi_match 与 match 类似,不同的是它可以在多个字段中查询。
在 Postman 中,向 ES 服务器发 GET 请求 http://127.0.0.1:9200/student/_search

  1. {
  2. "query": {
  3. "multi match": {
  4. "query": "zhangsan",
  5. "fields": ["name", "nickname"]
  6. }
  7. }
  8. }

image.png
服务器响应结果:
image.png

  1. 关键字精确查询

term 查询,精确的关键词匹配查询,不对查询条件进行分词。
在 Postman 中,向 ES 服务器发 GET 请求 http://127.0.0.1:9200/student/_search

  1. {
  2. "query": {
  3. "term": {
  4. "name": {
  5. "value": "zhangsan"
  6. }
  7. }
  8. }
  9. }

image.png
服务器响应结果:
image.png

  1. 多关键字精确查询

terms 查询和 term 查询一样,但它允许你指定多值进行匹配。如果这个字段包含了指定值中的任何一个值,那么这个文档满足条件,类似于 mysql 的 in
在 Postman 中,向 ES 服务器发 GET 请求 http://127.0.0.1:9200/student/_search

  1. {
  2. "query": {
  3. "terms": {
  4. "name": ["zhangsan", "lisi"]
  5. }
  6. }
  7. }

image.png
服务器响应结果:
image.png

  1. 指定查询字段

默认情况下,Elasticsearch 在搜索的结果中,会把文档中保存在 _source 的所有字段都返回。如果我们只想获取其中的部分字段,我们可以添加 _source 的过滤
在 Postman 中,向 ES 服务器发 GET 请求 http://127.0.0.1:9200/student/_search

  1. {
  2. "source": ["name", "nickname"],
  3. "query": {
  4. "terms": {
  5. "nickname": ["zhangsan"]
  6. }
  7. }
  8. }

image.png
服务器响应结果:
image.png

  1. 过滤字段

我们也可以通过:

  • includes:来指定想要显示的字段
  • excludes:来指定不想要显示的字段

在 Postman 中,向 ES 服务器发 GET 请求 http://127.0.0.1:9200/student/_search

  1. {
  2. "_source ": {
  3. "includes": ["name", "nickname"]
  4. },
  5. "query": {
  6. "terms": {
  7. "nickname": ["zhangsan"]
  8. }
  9. }
  10. }

image.png
服务器响应结果:
image.png
在 Postman 中,向 ES 服务器发 GET 请求 http://127.0.0.1:9200/student/_search

  1. {
  2. "_source": {
  3. "excludes": ["name", "nickname"]
  4. },
  5. "query": {
  6. "terms": {
  7. "nickname": ["zhangsan"]
  8. }
  9. }
  10. }

image.png
服务器响应结果:
image.png

  1. 组合查询

“bool”把各种其它查询通过”must”(必须 )、”must_not”(必须不)、”should”(应该)的方式进行组合
在 Postman 中,向 ES 服务器发 GET 请求 http://127.0.0.1:9200/student/_search

  1. {
  2. "query": {
  3. "bool": {
  4. "must": [{
  5. "match": {
  6. "name": "zhangsan"
  7. }
  8. }],
  9. "must_not": [{
  10. "match": {
  11. "age": "40"
  12. }
  13. }],
  14. "should": [{
  15. "match": {
  16. "sex": "男"
  17. }
  18. }]
  19. }
  20. }
  21. }

image.png
服务器响应结果:
image.png

  1. 范围查询

range 查询找出那些落在指定区间内的数字或者时间。 range 查询允许以下字符

操作符 说明
gt 大于
gte 大于等于
lt 小于
lte 小于等于

在 Postman 中,向 ES 服务器发 GET 请求 http://127.0.0.1:9200/student/_search

  1. {
  2. "query": {
  3. "range": {
  4. "age": {
  5. "gte": 30,
  6. "lte": 35
  7. }
  8. }
  9. }
  10. }

image.png
服务器响应结果:
image.png

  1. 模糊查询

返回包含与搜索字词相似的字词的文档。
编辑距离是将一个术语转换为另一个术语所需的一个字符更改的次数。这些更改可以包括:

  • 更改字符(box -> fox)
  • 删除字符(black -> lack)
  • 插入字符(sic -> sick)
  • 转置两个相邻字符(act -> cat)

为了找到相似的术语,fuzzy 查询会在指定的编辑距离内创建一组搜索词的所有可能的变体或扩展。然后查询返回每个扩展的完全匹配。通过 fuzziness 修改编辑距离。一般使用默认值 AUTO,根据术语的长度生成编辑距离。
在 Postman 中,向 ES 服务器发 GET 请求 http://127.0.0.1:9200/student/_search

  1. {
  2. "query": {
  3. "fuzzy": {
  4. "title": {
  5. "value": "zhangsan"
  6. }
  7. }
  8. }
  9. }

image.png
服务器响应结果:
image.png
在 Postman 中,向 ES 服务器发 GET 请求 http://127.0.0.1:9200/student/_search

  1. {
  2. "query": {
  3. " fuzzy": {
  4. "title": {
  5. "value": "zhangsan",
  6. "fuzziness": 2
  7. }
  8. }
  9. }
  10. }

image.png
服务器响应结果:
image.png

  1. 单字段排序

sort 可以让我们按照不同的字段进行排序,并且通过 order 指定排序的方式。 desc 降序,asc 升序。
在 Postman 中,向 ES 服务器发 GET 请求 http://127.0.0.1:9200/student/_search

  1. {
  2. "query": {
  3. "match": {
  4. "name": "zhangsan"
  5. }
  6. },
  7. "sort": [{
  8. "age": {
  9. "order": "desc"
  10. }
  11. }]
  12. }

image.png
服务器响应结果:
image.png

  1. 多字段排序

假定我们想要结合使用 age 和 _score 进行查询,并且匹配的结果首先按照年龄排序,然后按照相关性得分排序
在 Postman 中,向 ES 服务器发 GET 请求 http://127.0.0.1:9200/student/_search

  1. {
  2. "query": {
  3. "match all": {}
  4. },
  5. "sort": [{
  6. "age": {
  7. "order": "desc"
  8. }
  9. }, {
  10. "_score": {
  11. "order": "desc"
  12. }
  13. }]
  14. }

image.png
服务器响应结果:
image.png

  1. 高亮查询

在进行关键字搜索时,搜索出的内容中的关键字会显示不同的颜色,称之为高亮。
在百度搜索“京东”
image.png
Elasticsearch 可以对查询内容中的关键字部分,进行标签和样式(高亮)的设置。
在使用 match 查询的同时,加上一个 highlight 属性:

  • pre_tags:前置标签
  • post_tags:后置标签
  • fields:需要高亮的字段
  • title:这里声明 title 字段需要高亮,后面可以为这个字段设置特有配置,也可以空

在 Postman 中,向 ES 服务器发 GET 请求 http://127.0.0.1:9200/student/_search

  1. {
  2. "query": {
  3. "match": {
  4. "name": "zhangsan"
  5. }
  6. },
  7. "highlight": {
  8. "pre_tags": "<font color='red'>",
  9. "post_tags": "</font>",
  10. "fields": {
  11. "name": {}
  12. }
  13. }
  14. }

image.png
服务器响应结果:
image.png

  1. 分页查询

from:当前页的起始索引,默认从 0 开始。 from = (pageNum 1) * size
size:每页显示多少条
在 Postman 中,向 ES 服务器发 GET 请求 http://127.0.0.1:9200/student/_search

  1. {
  2. "query ": {
  3. "match all": {}
  4. },
  5. "sort": [{
  6. "age": {
  7. "order": "desc"
  8. }
  9. }],
  10. "from": 0,
  11. "size": 2
  12. }

image.png
服务器响应结果:
image.png

  1. 聚合查询

聚合允许使用者对 es 文档进行统计分析,类似与关系型数据库中的 group by ,当然还有很多其他的聚合,例如取最大值、平均值等等。

  • 对某个字段取最大值 max

在 Postman 中,向 ES 服务器发 GET 请求 http://127.0.0.1:9200/student/_search

  1. {
  2. "aggs": {
  3. "max _age": {
  4. "max": {
  5. "field": "age"
  6. }
  7. }
  8. },
  9. "size": 0
  10. }

image.png
服务器响应结果:
image.png

  • 对某个字段取最小值 min

在 Postman 中,向 ES 服务器发 GET 请求 http://127.0.0.1:9200/student/_search

  1. {
  2. "aggs": {
  3. "min age": {
  4. "min": {
  5. "field": "age"
  6. }
  7. },
  8. "size": 0
  9. }
  10. }

image.png
服务器响应结果:
image.png

  • 对某个字段求和 sum

在 Postman 中,向 ES 服务器发 GET 请求 http://127.0.0.1:9200/student/_search

  1. {
  2. "aggs": {
  3. "sum_age": {
  4. "sum": {
  5. "field": "age"
  6. }
  7. }
  8. },
  9. "size": 0
  10. }

image.png
服务器响应结果:
image.png

  • 对某个字段取平均值 avg

在 Postman 中,向 ES 服务器发 GET 请求 http://127.0.0.1:9200/student/_search

  1. {
  2. "aggs": {
  3. "avg_age": {
  4. "avg": {
  5. "field": "age"
  6. }
  7. }
  8. },
  9. "size": 0
  10. }

image.png
服务器响应结果:
image.png

  • 对某个字段的值进行去重之后再取总数

在 Postman 中,向 ES 服务器发 GET 请求 http://127.0.0.1:9200/student/_search

  1. {
  2. "aggs": {
  3. "distinct_age": {
  4. "cardinality": {
  5. "field": "age"
  6. }
  7. }
  8. },
  9. "size": 0
  10. }

image.png
服务器响应结果:
image.png

  • State 聚合

stats 聚合,对某个字段一次性返回 count max min avg 和 sum 五个指标
在 Postman 中,向 ES 服务器发 GET 请求 http://127.0.0.1:9200/student/_search

  1. {
  2. "aggs": {
  3. " stats_age": {
  4. "stats": {
  5. "field": "age"
  6. }
  7. }
  8. },
  9. "size": 0
  10. }

image.png
服务器响应结果:
image.png

  1. 桶聚合查询

桶聚和相当于 sql 中的 group by 语句

  • terms 聚合,分组统计

在 Postman 中,向 ES 服务器发 GET 请求 http://127.0.0.1:9200/student/_search

  1. {
  2. "aggs": {
  3. " age_groupby": {
  4. "terms": {
  5. "field": "age"
  6. }
  7. }
  8. },
  9. "size": 0
  10. }

image.png
服务器响应结果:
image.png

  • 在 terms 分组下再进行聚合

在 Postman 中,向 ES 服务器发 GET 请求 http://127.0.0.1:9200/student/_search

  1. {
  2. "aggs": {
  3. " age_groupby": {
  4. "terms": {
  5. "field": "age"
  6. }
  7. }
  8. },
  9. "size": 0
  10. }

image.png
服务器响应结果:
image.png

2.2.5 Java API 操作

Elasticsearch 软件是由 Java 语言开发的,所以也可以通过 Java API 的方式对 Elasticsearch 服务进行访问

2.2.5.1 创建 Maven 项目

我们在 IDEA 开发工具中创建 Maven 项目(模块也可)ES
image.png
修改 pom 文件,增加 Maven 依赖关系

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <modelVersion>4.0.0</modelVersion>
  6. <groupId>org.example</groupId>
  7. <artifactId>es-test</artifactId>
  8. <version>1.0-SNAPSHOT</version>
  9. <properties>
  10. <maven.compiler.source>8</maven.compiler.source>
  11. <maven.compiler.target>8</maven.compiler.target>
  12. </properties>
  13. <dependencies>
  14. <!-- elasticsearch 的客户端-->
  15. <dependency>
  16. <groupId>co.elastic.clients</groupId>
  17. <artifactId>elasticsearch-java</artifactId>
  18. <version>8.1.1</version>
  19. </dependency>
  20. <dependency>
  21. <groupId>com.fasterxml.jackson.core</groupId>
  22. <artifactId>jackson-databind</artifactId>
  23. <version>2.13.2.2</version>
  24. </dependency>
  25. <!-- junit单元测试-->
  26. <dependency>
  27. <groupId>junit</groupId>
  28. <artifactId>junit</artifactId>
  29. <version>4.13.2</version>
  30. <scope>test</scope>
  31. </dependency>
  32. </dependencies>
  33. <!-- 设定仓库,按设定顺序进行查找 -->
  34. <repositories>
  35. <repository>
  36. <id>aliyunmaven</id>
  37. <name>aliyun</name>
  38. <url>https://maven.aliyun.com/repository/central</url>
  39. <snapshots>
  40. <enabled>true</enabled>
  41. </snapshots>
  42. </repository>
  43. </repositories>
  44. </project>

2.2.5.2 客户端对象

创建 com.atguigu.es.test.Elasticsearch01_Client 类,代码中创建 Elasticsearch 客户端对象。因为早期版本的客户端对象已经不再推荐使用,且在未来版本中会被删除,所以这里我们采用高级 REST 客户端对象(7.15 版本已经不再推荐使用,后面采用 Java API Client for Elasticsearch)
image.png
image.png

  1. package com.atguigu.es.test;
  2. import co.elastic.clients.elasticsearch.ElasticsearchClient;
  3. import co.elastic.clients.elasticsearch.indices.CreateIndexResponse;
  4. import co.elastic.clients.json.jackson.JacksonJsonpMapper;
  5. import co.elastic.clients.transport.ElasticsearchTransport;
  6. import co.elastic.clients.transport.rest_client.RestClientTransport;
  7. import org.apache.http.HttpHost;
  8. import org.apache.http.auth.AuthScope;
  9. import org.apache.http.auth.UsernamePasswordCredentials;
  10. import org.apache.http.client.CredentialsProvider;
  11. import org.apache.http.impl.client.BasicCredentialsProvider;
  12. import org.apache.http.ssl.SSLContextBuilder;
  13. import org.apache.http.ssl.SSLContexts;
  14. import org.elasticsearch.client.RestClient;
  15. import javax.net.ssl.SSLContext;
  16. import java.io.InputStream;
  17. import java.nio.file.Files;
  18. import java.nio.file.Path;
  19. import java.nio.file.Paths;
  20. import java.security.KeyStore;
  21. import java.security.cert.Certificate;
  22. import java.security.cert.CertificateFactory;
  23. /**
  24. * @author: zhangxin
  25. * @date: 2022/3/31
  26. */
  27. public class ESTest_Client {
  28. public static void main(String[] args) throws Exception {
  29. // 用户认证对象
  30. final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
  31. // 设置账号密码
  32. credentialsProvider.setCredentials(
  33. AuthScope.ANY, new UsernamePasswordCredentials("elastic", "IZ=zWc_zSRJIYFcadYxL"));
  34. Path caCertificatePath = Paths.get("d:/http_ca.crt");
  35. CertificateFactory factory = CertificateFactory.getInstance("X.509");
  36. Certificate trustedCa;
  37. try (InputStream is = Files.newInputStream(caCertificatePath)) {
  38. trustedCa = factory.generateCertificate(is);
  39. }
  40. KeyStore trustStore = KeyStore.getInstance("pkcs12");
  41. trustStore.load(null, null);
  42. trustStore.setCertificateEntry("ca", trustedCa);
  43. SSLContextBuilder sslContextBuilder = SSLContexts.custom()
  44. .loadTrustMaterial(trustStore, null);
  45. final SSLContext sslContext = sslContextBuilder.build();
  46. // 创建 es 客户端
  47. RestClient restClient = RestClient.builder(
  48. new HttpHost("172.18.1.31", 9200, "https"))
  49. .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setSSLContext(sslContext)
  50. .setDefaultCredentialsProvider(credentialsProvider)).build();
  51. // 使用 Jackson 映射器创建传输层
  52. ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
  53. // 创建 API 客户端
  54. ElasticsearchClient esClient = new ElasticsearchClient(transport);
  55. // 关闭 es 客户端
  56. transport.close();
  57. restClient.close();
  58. }
  59. }

注意:9200 端口为 Elasticsearch 的 Web 通信端口,localhost 为启动 ES 服务的主机名
执行代码,查看控制台信息:
image.png

2.2.5.3 索引操作

ES 服务器正常启动后,可以通过 Java API 客户端对象对 ES 索引进行操作

  1. 创建索引 ```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 {

    1. // 用户认证对象
    2. final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    3. // 设置账号密码
    4. credentialsProvider.setCredentials(
    5. AuthScope.ANY, new UsernamePasswordCredentials("elastic", "IZ=zWc_zSRJIYFcadYxL"));
    6. Path caCertificatePath = Paths.get("d:/http_ca.crt");
    7. CertificateFactory factory = CertificateFactory.getInstance("X.509");
    8. Certificate trustedCa;
    9. try (InputStream is = Files.newInputStream(caCertificatePath)) {
    10. trustedCa = factory.generateCertificate(is);
    11. }
    12. KeyStore trustStore = KeyStore.getInstance("pkcs12");
    13. trustStore.load(null, null);
    14. trustStore.setCertificateEntry("ca", trustedCa);
    15. SSLContextBuilder sslContextBuilder = SSLContexts.custom()
    16. .loadTrustMaterial(trustStore, null);
    17. final SSLContext sslContext = sslContextBuilder.build();
    18. // 创建 es 客户端
    19. RestClient restClient = RestClient.builder(
    20. new HttpHost("172.18.1.31", 9200, "https"))
    21. .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setSSLContext(sslContext)
    22. .setDefaultCredentialsProvider(credentialsProvider)).build();
    23. // 使用 Jackson 映射器创建传输层
    24. ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
    25. // 创建 API 客户端
    26. ElasticsearchClient esClient = new ElasticsearchClient(transport);
    27. // 创建索引
    28. CreateIndexResponse response = esClient.indices().create(c -> c.index("user"));
    29. Boolean acknowledged = response.acknowledged();
    30. // 响应状态
    31. System.out.println("索引操作:" + acknowledged);
    32. // 关闭 es 客户端
    33. transport.close();
    34. restClient.close();

    } } ``` 操作结果:
    image.png

  1. 查看索引 ```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 {

    1. // 用户认证对象
    2. final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    3. // 设置账号密码
    4. credentialsProvider.setCredentials(
    5. AuthScope.ANY, new UsernamePasswordCredentials("elastic", "wkZQNElpnNj6+QWflIBU"));
    6. Path caCertificatePath = Paths.get("d:/http_ca.crt");
    7. CertificateFactory factory = CertificateFactory.getInstance("X.509");
    8. Certificate trustedCa;
    9. try (InputStream is = Files.newInputStream(caCertificatePath)) {
    10. trustedCa = factory.generateCertificate(is);
    11. }
    12. KeyStore trustStore = KeyStore.getInstance("pkcs12");
    13. trustStore.load(null, null);
    14. trustStore.setCertificateEntry("ca", trustedCa);
    15. SSLContextBuilder sslContextBuilder = SSLContexts.custom()
    16. .loadTrustMaterial(trustStore, null);
    17. final SSLContext sslContext = sslContextBuilder.build();
    18. // 创建 es 客户端
    19. RestClient restClient = RestClient.builder(
    20. new HttpHost("172.18.1.31", 9200, "https"))
    21. .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setSSLContext(sslContext)
    22. .setDefaultCredentialsProvider(credentialsProvider)).build();
    23. // 使用 Jackson 映射器创建传输层
    24. ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
    25. // 创建 API 客户端
    26. ElasticsearchClient esClient = new ElasticsearchClient(transport);
    27. // 查看索引
    28. GetIndexResponse response = esClient.indices().get(c -> c.index("user"));
    29. IndexState user = response.get("user");
    30. // 响应状态
    31. System.out.println(user.aliases());
    32. System.out.println(user.mappings());
    33. System.out.println(user.settings());
    34. // 关闭 es 客户端
    35. transport.close();
    36. restClient.close();

    } } ``` image.png

  1. 删除索引 ```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 {

    1. // 用户认证对象
    2. final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    3. // 设置账号密码
    4. credentialsProvider.setCredentials(
    5. AuthScope.ANY, new UsernamePasswordCredentials("elastic", "wkZQNElpnNj6+QWflIBU"));
    6. Path caCertificatePath = Paths.get("d:/http_ca.crt");
    7. CertificateFactory factory = CertificateFactory.getInstance("X.509");
    8. Certificate trustedCa;
    9. try (InputStream is = Files.newInputStream(caCertificatePath)) {
    10. trustedCa = factory.generateCertificate(is);
    11. }
    12. KeyStore trustStore = KeyStore.getInstance("pkcs12");
    13. trustStore.load(null, null);
    14. trustStore.setCertificateEntry("ca", trustedCa);
    15. SSLContextBuilder sslContextBuilder = SSLContexts.custom()
    16. .loadTrustMaterial(trustStore, null);
    17. final SSLContext sslContext = sslContextBuilder.build();
    18. // 创建 es 客户端
    19. RestClient restClient = RestClient.builder(
    20. new HttpHost("172.18.1.31", 9200, "https"))
    21. .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setSSLContext(sslContext)
    22. .setDefaultCredentialsProvider(credentialsProvider)).build();
    23. // 使用 Jackson 映射器创建传输层
    24. ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
    25. // 创建 API 客户端
    26. ElasticsearchClient esClient = new ElasticsearchClient(transport);
    27. // 删除索引
    28. DeleteIndexResponse response = esClient.indices().delete(c -> c.index("user"));
    29. // 操作结果
    30. Boolean acknowledged = response.acknowledged();
    31. System.out.println("索引操作:" + acknowledged);
    32. // 关闭 es 客户端
    33. transport.close();
    34. restClient.close();

    } } ``` 操作结果:
    image.png

    2.2.5.4 文档操作

  1. 新增文档

创建数据模型

  1. package com.atguigu.es.test;
  2. public class User {
  3. private String name;
  4. private Integer age;
  5. private String sex;
  6. private String id;
  7. public String getName() {
  8. return name;
  9. }
  10. public void setName(String name) {
  11. this.name = name;
  12. }
  13. public Integer getAge() {
  14. return age;
  15. }
  16. public void setAge(Integer age) {
  17. this.age = age;
  18. }
  19. public String getSex() {
  20. return sex;
  21. }
  22. public void setSex(String sex) {
  23. this.sex = sex;
  24. }
  25. public String getId() {
  26. return id;
  27. }
  28. public void setId(String id) {
  29. this.id = id;
  30. }
  31. public User(String name, Integer age, String sex, String id) {
  32. this.name = name;
  33. this.age = age;
  34. this.sex = sex;
  35. this.id = id;
  36. }
  37. public User() {
  38. }
  39. @Override
  40. public String toString() {
  41. return "User{" +
  42. "name='" + name + '\'' +
  43. ", age=" + age +
  44. ", sex='" + sex + '\'' +
  45. ", id='" + id + '\'' +
  46. '}';
  47. }
  48. }

创建数据,添加到文档中

  1. package com.atguigu.es.test.document;
  2. import co.elastic.clients.elasticsearch.ElasticsearchClient;
  3. import co.elastic.clients.elasticsearch.core.IndexResponse;
  4. import co.elastic.clients.json.jackson.JacksonJsonpMapper;
  5. import co.elastic.clients.transport.ElasticsearchTransport;
  6. import co.elastic.clients.transport.rest_client.RestClientTransport;
  7. import com.atguigu.es.test.User;
  8. import org.apache.http.HttpHost;
  9. import org.apache.http.auth.AuthScope;
  10. import org.apache.http.auth.UsernamePasswordCredentials;
  11. import org.apache.http.client.CredentialsProvider;
  12. import org.apache.http.impl.client.BasicCredentialsProvider;
  13. import org.apache.http.ssl.SSLContextBuilder;
  14. import org.apache.http.ssl.SSLContexts;
  15. import org.elasticsearch.client.RestClient;
  16. import javax.net.ssl.SSLContext;
  17. import java.io.InputStream;
  18. import java.nio.file.Files;
  19. import java.nio.file.Path;
  20. import java.nio.file.Paths;
  21. import java.security.KeyStore;
  22. import java.security.cert.Certificate;
  23. import java.security.cert.CertificateFactory;
  24. /**
  25. * @author: zhangxin
  26. * @date: 2022/3/31
  27. */
  28. public class InsertClient {
  29. public static void main(String[] args) throws Exception {
  30. // 用户认证对象
  31. final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
  32. // 设置账号密码
  33. credentialsProvider.setCredentials(
  34. AuthScope.ANY, new UsernamePasswordCredentials("elastic", "wkZQNElpnNj6+QWflIBU"));
  35. Path caCertificatePath = Paths.get("d:/http_ca.crt");
  36. CertificateFactory factory = CertificateFactory.getInstance("X.509");
  37. Certificate trustedCa;
  38. try (InputStream is = Files.newInputStream(caCertificatePath)) {
  39. trustedCa = factory.generateCertificate(is);
  40. }
  41. KeyStore trustStore = KeyStore.getInstance("pkcs12");
  42. trustStore.load(null, null);
  43. trustStore.setCertificateEntry("ca", trustedCa);
  44. SSLContextBuilder sslContextBuilder = SSLContexts.custom()
  45. .loadTrustMaterial(trustStore, null);
  46. final SSLContext sslContext = sslContextBuilder.build();
  47. // 创建 es 客户端
  48. RestClient restClient = RestClient.builder(
  49. new HttpHost("172.18.1.31", 9200, "https"))
  50. .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setSSLContext(sslContext)
  51. .setDefaultCredentialsProvider(credentialsProvider)).build();
  52. // 使用 Jackson 映射器创建传输层
  53. ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
  54. // 创建 API 客户端
  55. ElasticsearchClient esClient = new ElasticsearchClient(transport);
  56. // 新增文档 请求对象
  57. // 创建数据对象
  58. User user = new User();
  59. user.setName("zhangsan");
  60. user.setAge(30);
  61. user.setSex("男");
  62. // 设置索引及唯一性标识
  63. // 客户端发送请求,获取响应对象
  64. IndexResponse response = esClient.index(i -> i.index("user").id("1001").document(user));
  65. // 打印结果信息
  66. System.out.println("_index:" + response.index());
  67. System.out.println("_id:" + response.id());
  68. System.out.println("_result:" + response.result());
  69. // 关闭 es 客户端
  70. transport.close();
  71. restClient.close();
  72. }
  73. }

操作结果:
image.png

  1. 修改文档 ```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 {

    1. // 用户认证对象
    2. final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    3. // 设置账号密码
    4. credentialsProvider.setCredentials(
    5. AuthScope.ANY, new UsernamePasswordCredentials("elastic", "wkZQNElpnNj6+QWflIBU"));
    6. Path caCertificatePath = Paths.get("d:/http_ca.crt");
    7. CertificateFactory factory = CertificateFactory.getInstance("X.509");
    8. Certificate trustedCa;
    9. try (InputStream is = Files.newInputStream(caCertificatePath)) {
    10. trustedCa = factory.generateCertificate(is);
    11. }
    12. KeyStore trustStore = KeyStore.getInstance("pkcs12");
    13. trustStore.load(null, null);
    14. trustStore.setCertificateEntry("ca", trustedCa);
    15. SSLContextBuilder sslContextBuilder = SSLContexts.custom()
    16. .loadTrustMaterial(trustStore, null);
    17. final SSLContext sslContext = sslContextBuilder.build();
    18. // 创建 es 客户端
    19. RestClient restClient = RestClient.builder(
    20. new HttpHost("172.18.1.31", 9200, "https"))
    21. .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setSSLContext(sslContext)
    22. .setDefaultCredentialsProvider(credentialsProvider)).build();
    23. // 使用 Jackson 映射器创建传输层
    24. ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
    25. // 创建 API 客户端
    26. ElasticsearchClient esClient = new ElasticsearchClient(transport);
    27. User user = new User();
    28. user.setName("zhangsan");
    29. user.setAge(30);
    30. user.setSex("女");
    31. // 更新文档
    32. UpdateResponse<User> response = esClient.update(i -> i.index("user").id("1001").doc(user), User.class);
    33. System.out.println("_index:" + response.index());
    34. System.out.println("_id:" + response.id());
    35. System.out.println("_result:" + response.result());
    36. // 关闭 es 客户端
    37. transport.close();
    38. restClient.close();

    } } ``` 执行结果:
    image.png

  1. 查询文档 ```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 {

    1. // 用户认证对象
    2. final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    3. // 设置账号密码
    4. credentialsProvider.setCredentials(
    5. AuthScope.ANY, new UsernamePasswordCredentials("elastic", "wkZQNElpnNj6+QWflIBU"));
    6. Path caCertificatePath = Paths.get("d:/http_ca.crt");
    7. CertificateFactory factory = CertificateFactory.getInstance("X.509");
    8. Certificate trustedCa;
    9. try (InputStream is = Files.newInputStream(caCertificatePath)) {
    10. trustedCa = factory.generateCertificate(is);
    11. }
    12. KeyStore trustStore = KeyStore.getInstance("pkcs12");
    13. trustStore.load(null, null);
    14. trustStore.setCertificateEntry("ca", trustedCa);
    15. SSLContextBuilder sslContextBuilder = SSLContexts.custom()
    16. .loadTrustMaterial(trustStore, null);
    17. final SSLContext sslContext = sslContextBuilder.build();
    18. // 创建 es 客户端
    19. RestClient restClient = RestClient.builder(
    20. new HttpHost("172.18.1.31", 9200, "https"))
    21. .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setSSLContext(sslContext)
    22. .setDefaultCredentialsProvider(credentialsProvider)).build();
    23. // 使用 Jackson 映射器创建传输层
    24. ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
    25. // 创建 API 客户端
    26. ElasticsearchClient esClient = new ElasticsearchClient(transport);
    27. // 设置索引及唯一性标识
    28. // 客户端发送请求,获取响应对象
    29. GetResponse<User> response = esClient.get(i -> i.index("user").id("1001"), User.class);
    30. // 打印结果信息
    31. System.out.println("_index:" + response.index());
    32. System.out.println("source:" + response.source().toString());
    33. System.out.println("_id:" + response.id());
    34. // 关闭 es 客户端
    35. transport.close();
    36. restClient.close();

    } } ``` 执行结果为:
    image.png

  1. 删除文档 ```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 {

    1. // 用户认证对象
    2. final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    3. // 设置账号密码
    4. credentialsProvider.setCredentials(
    5. AuthScope.ANY, new UsernamePasswordCredentials("elastic", "wkZQNElpnNj6+QWflIBU"));
    6. Path caCertificatePath = Paths.get("d:/http_ca.crt");
    7. CertificateFactory factory = CertificateFactory.getInstance("X.509");
    8. Certificate trustedCa;
    9. try (InputStream is = Files.newInputStream(caCertificatePath)) {
    10. trustedCa = factory.generateCertificate(is);
    11. }
    12. KeyStore trustStore = KeyStore.getInstance("pkcs12");
    13. trustStore.load(null, null);
    14. trustStore.setCertificateEntry("ca", trustedCa);
    15. SSLContextBuilder sslContextBuilder = SSLContexts.custom()
    16. .loadTrustMaterial(trustStore, null);
    17. final SSLContext sslContext = sslContextBuilder.build();
    18. // 创建 es 客户端
    19. RestClient restClient = RestClient.builder(
    20. new HttpHost("172.18.1.31", 9200, "https"))
    21. .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setSSLContext(sslContext)
    22. .setDefaultCredentialsProvider(credentialsProvider)).build();
    23. // 使用 Jackson 映射器创建传输层
    24. ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
    25. // 创建 API 客户端
    26. ElasticsearchClient esClient = new ElasticsearchClient(transport);
    27. // 设置索引及唯一性标识
    28. // 客户端发送请求,获取响应对象
    29. DeleteResponse response = esClient.delete(i -> i.index("user").id("1001"));
    30. // 打印结果信息
    31. System.out.println(response.toString());
    32. // 关闭 es 客户端
    33. transport.close();
    34. restClient.close();

    } } ``` 执行结果为:
    image.png

  1. 批量操作

批量新增

  1. package com.atguigu.es.test.document.batch;
  2. import co.elastic.clients.elasticsearch.ElasticsearchClient;
  3. import co.elastic.clients.elasticsearch.core.BulkRequest;
  4. import co.elastic.clients.elasticsearch.core.BulkResponse;
  5. import co.elastic.clients.json.jackson.JacksonJsonpMapper;
  6. import co.elastic.clients.transport.ElasticsearchTransport;
  7. import co.elastic.clients.transport.rest_client.RestClientTransport;
  8. import com.atguigu.es.test.User;
  9. import org.apache.http.HttpHost;
  10. import org.apache.http.auth.AuthScope;
  11. import org.apache.http.auth.UsernamePasswordCredentials;
  12. import org.apache.http.client.CredentialsProvider;
  13. import org.apache.http.impl.client.BasicCredentialsProvider;
  14. import org.apache.http.ssl.SSLContextBuilder;
  15. import org.apache.http.ssl.SSLContexts;
  16. import org.elasticsearch.client.RestClient;
  17. import javax.net.ssl.SSLContext;
  18. import java.io.InputStream;
  19. import java.nio.file.Files;
  20. import java.nio.file.Path;
  21. import java.nio.file.Paths;
  22. import java.security.KeyStore;
  23. import java.security.cert.Certificate;
  24. import java.security.cert.CertificateFactory;
  25. import java.util.ArrayList;
  26. import java.util.List;
  27. import java.util.Random;
  28. import java.util.concurrent.atomic.AtomicInteger;
  29. /**
  30. * @author: zhangxin
  31. * @date: 2022/3/31
  32. */
  33. public class BatchInsertClient {
  34. public static void main(String[] args) throws Exception {
  35. // 用户认证对象
  36. final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
  37. // 设置账号密码
  38. credentialsProvider.setCredentials(
  39. AuthScope.ANY, new UsernamePasswordCredentials("elastic", "wkZQNElpnNj6+QWflIBU"));
  40. Path caCertificatePath = Paths.get("d:/http_ca.crt");
  41. CertificateFactory factory = CertificateFactory.getInstance("X.509");
  42. Certificate trustedCa;
  43. try (InputStream is = Files.newInputStream(caCertificatePath)) {
  44. trustedCa = factory.generateCertificate(is);
  45. }
  46. KeyStore trustStore = KeyStore.getInstance("pkcs12");
  47. trustStore.load(null, null);
  48. trustStore.setCertificateEntry("ca", trustedCa);
  49. SSLContextBuilder sslContextBuilder = SSLContexts.custom()
  50. .loadTrustMaterial(trustStore, null);
  51. final SSLContext sslContext = sslContextBuilder.build();
  52. // 创建 es 客户端
  53. RestClient restClient = RestClient.builder(
  54. new HttpHost("172.18.1.31", 9200, "https"))
  55. .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setSSLContext(sslContext)
  56. .setDefaultCredentialsProvider(credentialsProvider)).build();
  57. // 使用 Jackson 映射器创建传输层
  58. ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
  59. // 创建 API 客户端
  60. ElasticsearchClient esClient = new ElasticsearchClient(transport);
  61. // 新增文档 请求对象
  62. // 创建数据对象
  63. List<User> list = new ArrayList<>();
  64. list.add(new User("zhangsan", 30, "男", "1001"));
  65. list.add(new User("lisi", 30, "男", "1002"));
  66. list.add(new User("wangwu", 30, "男", "1003"));
  67. // 设置索引及唯一性标识
  68. // 客户端发送请求,获取响应对象
  69. BulkRequest.Builder br = new BulkRequest.Builder();
  70. for (User user : list) {
  71. br.operations(op -> op.index(idx -> idx.index("user").id(user.getId()).document(user)));
  72. }
  73. BulkResponse response = esClient.bulk(br.build());
  74. // 打印结果信息
  75. System.out.println("took:" + response.took());
  76. System.out.println("items:" + response.items());
  77. // 关闭 es 客户端
  78. transport.close();
  79. restClient.close();
  80. }
  81. }

执行结果为:
image.png
批量删除:

  1. package com.atguigu.es.test.document.batch;
  2. import co.elastic.clients.elasticsearch.ElasticsearchClient;
  3. import co.elastic.clients.elasticsearch.core.BulkRequest;
  4. import co.elastic.clients.elasticsearch.core.BulkResponse;
  5. import co.elastic.clients.elasticsearch.core.DeleteRequest;
  6. import co.elastic.clients.json.jackson.JacksonJsonpMapper;
  7. import co.elastic.clients.transport.ElasticsearchTransport;
  8. import co.elastic.clients.transport.rest_client.RestClientTransport;
  9. import com.atguigu.es.test.User;
  10. import org.apache.http.HttpHost;
  11. import org.apache.http.auth.AuthScope;
  12. import org.apache.http.auth.UsernamePasswordCredentials;
  13. import org.apache.http.client.CredentialsProvider;
  14. import org.apache.http.impl.client.BasicCredentialsProvider;
  15. import org.apache.http.ssl.SSLContextBuilder;
  16. import org.apache.http.ssl.SSLContexts;
  17. import org.elasticsearch.client.RequestOptions;
  18. import org.elasticsearch.client.RestClient;
  19. import javax.net.ssl.SSLContext;
  20. import java.io.InputStream;
  21. import java.nio.file.Files;
  22. import java.nio.file.Path;
  23. import java.nio.file.Paths;
  24. import java.security.KeyStore;
  25. import java.security.cert.Certificate;
  26. import java.security.cert.CertificateFactory;
  27. import java.util.ArrayList;
  28. import java.util.List;
  29. import java.util.Random;
  30. /**
  31. * @author: zhangxin
  32. * @date: 2022/3/31
  33. */
  34. public class BatchDeleteClient {
  35. public static void main(String[] args) throws Exception {
  36. // 用户认证对象
  37. final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
  38. // 设置账号密码
  39. credentialsProvider.setCredentials(
  40. AuthScope.ANY, new UsernamePasswordCredentials("elastic", "wkZQNElpnNj6+QWflIBU"));
  41. Path caCertificatePath = Paths.get("d:/http_ca.crt");
  42. CertificateFactory factory = CertificateFactory.getInstance("X.509");
  43. Certificate trustedCa;
  44. try (InputStream is = Files.newInputStream(caCertificatePath)) {
  45. trustedCa = factory.generateCertificate(is);
  46. }
  47. KeyStore trustStore = KeyStore.getInstance("pkcs12");
  48. trustStore.load(null, null);
  49. trustStore.setCertificateEntry("ca", trustedCa);
  50. SSLContextBuilder sslContextBuilder = SSLContexts.custom()
  51. .loadTrustMaterial(trustStore, null);
  52. final SSLContext sslContext = sslContextBuilder.build();
  53. // 创建 es 客户端
  54. RestClient restClient = RestClient.builder(
  55. new HttpHost("172.18.1.31", 9200, "https"))
  56. .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setSSLContext(sslContext)
  57. .setDefaultCredentialsProvider(credentialsProvider)).build();
  58. // 使用 Jackson 映射器创建传输层
  59. ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
  60. // 创建 API 客户端
  61. ElasticsearchClient esClient = new ElasticsearchClient(transport);
  62. List<User> list = new ArrayList<>();
  63. list.add(new User("zhangsan", 30, "男", "1001"));
  64. list.add(new User("lisi", 30, "男", "1002"));
  65. list.add(new User("wangwu", 30, "男", "1003"));
  66. // 设置索引及唯一性标识
  67. // 客户端发送请求,获取响应对象
  68. BulkRequest.Builder br = new BulkRequest.Builder();
  69. for (User user : list) {
  70. br.operations(op -> op.delete(idx -> idx.index("user").id(user.getId())));
  71. }
  72. BulkResponse response = esClient.bulk(br.build());
  73. // 打印结果信息
  74. System.out.println("took:" + response.took());
  75. System.out.println("items:" + response.items());
  76. // 关闭 es 客户端
  77. transport.close();
  78. restClient.close();
  79. }
  80. }

执行结果为:
image.png

2.2.5.5 高级查询

  1. 请求体查询

查询所有索引数据

  1. package com.atguigu.es.test.query;
  2. import co.elastic.clients.elasticsearch.ElasticsearchClient;
  3. import co.elastic.clients.elasticsearch._types.query_dsl.Query;
  4. import co.elastic.clients.elasticsearch._types.query_dsl.QueryBuilders;
  5. import co.elastic.clients.elasticsearch.core.SearchRequest;
  6. import co.elastic.clients.elasticsearch.core.SearchResponse;
  7. import co.elastic.clients.elasticsearch.core.search.Hit;
  8. import co.elastic.clients.elasticsearch.indices.GetIndexResponse;
  9. import co.elastic.clients.elasticsearch.indices.IndexState;
  10. import co.elastic.clients.json.jackson.JacksonJsonpMapper;
  11. import co.elastic.clients.transport.ElasticsearchTransport;
  12. import co.elastic.clients.transport.rest_client.RestClientTransport;
  13. import com.atguigu.es.test.User;
  14. import org.apache.http.HttpHost;
  15. import org.apache.http.auth.AuthScope;
  16. import org.apache.http.auth.UsernamePasswordCredentials;
  17. import org.apache.http.client.CredentialsProvider;
  18. import org.apache.http.impl.client.BasicCredentialsProvider;
  19. import org.apache.http.ssl.SSLContextBuilder;
  20. import org.apache.http.ssl.SSLContexts;
  21. import org.elasticsearch.client.RequestOptions;
  22. import org.elasticsearch.client.RestClient;
  23. import javax.net.ssl.SSLContext;
  24. import java.io.InputStream;
  25. import java.nio.file.Files;
  26. import java.nio.file.Path;
  27. import java.nio.file.Paths;
  28. import java.security.KeyStore;
  29. import java.security.cert.Certificate;
  30. import java.security.cert.CertificateFactory;
  31. import java.util.List;
  32. /**
  33. * @author: zhangxin
  34. * @date: 2022/3/31
  35. */
  36. public class AllClient {
  37. private static Query.Builder q;
  38. public static void main(String[] args) throws Exception {
  39. // 用户认证对象
  40. final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
  41. // 设置账号密码
  42. credentialsProvider.setCredentials(
  43. AuthScope.ANY, new UsernamePasswordCredentials("elastic", "wkZQNElpnNj6+QWflIBU"));
  44. Path caCertificatePath = Paths.get("d:/http_ca.crt");
  45. CertificateFactory factory = CertificateFactory.getInstance("X.509");
  46. Certificate trustedCa;
  47. try (InputStream is = Files.newInputStream(caCertificatePath)) {
  48. trustedCa = factory.generateCertificate(is);
  49. }
  50. KeyStore trustStore = KeyStore.getInstance("pkcs12");
  51. trustStore.load(null, null);
  52. trustStore.setCertificateEntry("ca", trustedCa);
  53. SSLContextBuilder sslContextBuilder = SSLContexts.custom()
  54. .loadTrustMaterial(trustStore, null);
  55. final SSLContext sslContext = sslContextBuilder.build();
  56. // 创建 es 客户端
  57. RestClient restClient = RestClient.builder(
  58. new HttpHost("172.18.1.31", 9200, "https"))
  59. .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setSSLContext(sslContext)
  60. .setDefaultCredentialsProvider(credentialsProvider)).build();
  61. // 使用 Jackson 映射器创建传输层
  62. ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
  63. // 创建 API 客户端
  64. ElasticsearchClient esClient = new ElasticsearchClient(transport);
  65. // 创建搜索请求对象
  66. SearchResponse<User> response = esClient.search(s -> s.index("user"), User.class);
  67. // 查询匹配
  68. System.out.println("took:" + response.took());
  69. System.out.println("timeout:" + response.timedOut());
  70. System.out.println("total:" + response.hits().total().value());
  71. System.out.println("MaxScore:" + response.hits().maxScore());
  72. System.out.println("hits========>>");
  73. List<Hit<User>> hits = response.hits().hits();
  74. for (Hit<User> hit: hits) {
  75. User user = hit.source();
  76. // 输出每条查询的结果信息
  77. System.out.println(user);
  78. }
  79. System.out.println("<<========");
  80. // 关闭 es 客户端
  81. transport.close();
  82. restClient.close();
  83. }
  84. }

image.png
term 查询,查询条件为关键字

  1. package com.atguigu.es.test.query;
  2. import co.elastic.clients.elasticsearch.ElasticsearchClient;
  3. import co.elastic.clients.elasticsearch._types.query_dsl.Query;
  4. import co.elastic.clients.elasticsearch._types.query_dsl.QueryBuilders;
  5. import co.elastic.clients.elasticsearch.core.SearchResponse;
  6. import co.elastic.clients.elasticsearch.core.search.Hit;
  7. import co.elastic.clients.json.jackson.JacksonJsonpMapper;
  8. import co.elastic.clients.transport.ElasticsearchTransport;
  9. import co.elastic.clients.transport.rest_client.RestClientTransport;
  10. import com.atguigu.es.test.User;
  11. import org.apache.http.HttpHost;
  12. import org.apache.http.auth.AuthScope;
  13. import org.apache.http.auth.UsernamePasswordCredentials;
  14. import org.apache.http.client.CredentialsProvider;
  15. import org.apache.http.impl.client.BasicCredentialsProvider;
  16. import org.apache.http.ssl.SSLContextBuilder;
  17. import org.apache.http.ssl.SSLContexts;
  18. import org.elasticsearch.client.RestClient;
  19. import javax.net.ssl.SSLContext;
  20. import java.io.InputStream;
  21. import java.nio.file.Files;
  22. import java.nio.file.Path;
  23. import java.nio.file.Paths;
  24. import java.security.KeyStore;
  25. import java.security.cert.Certificate;
  26. import java.security.cert.CertificateFactory;
  27. import java.util.List;
  28. /**
  29. * @author: zhangxin
  30. * @date: 2022/3/31
  31. */
  32. public class TermClient {
  33. private static Query.Builder q;
  34. public static void main(String[] args) throws Exception {
  35. // 用户认证对象
  36. final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
  37. // 设置账号密码
  38. credentialsProvider.setCredentials(
  39. AuthScope.ANY, new UsernamePasswordCredentials("elastic", "wkZQNElpnNj6+QWflIBU"));
  40. Path caCertificatePath = Paths.get("d:/http_ca.crt");
  41. CertificateFactory factory = CertificateFactory.getInstance("X.509");
  42. Certificate trustedCa;
  43. try (InputStream is = Files.newInputStream(caCertificatePath)) {
  44. trustedCa = factory.generateCertificate(is);
  45. }
  46. KeyStore trustStore = KeyStore.getInstance("pkcs12");
  47. trustStore.load(null, null);
  48. trustStore.setCertificateEntry("ca", trustedCa);
  49. SSLContextBuilder sslContextBuilder = SSLContexts.custom()
  50. .loadTrustMaterial(trustStore, null);
  51. final SSLContext sslContext = sslContextBuilder.build();
  52. // 创建 es 客户端
  53. RestClient restClient = RestClient.builder(
  54. new HttpHost("172.18.1.31", 9200, "https"))
  55. .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setSSLContext(sslContext)
  56. .setDefaultCredentialsProvider(credentialsProvider)).build();
  57. // 使用 Jackson 映射器创建传输层
  58. ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
  59. // 创建 API 客户端
  60. ElasticsearchClient esClient = new ElasticsearchClient(transport);
  61. // 创建搜索请求对象
  62. SearchResponse<User> response = esClient.search(s -> s
  63. .index("user")
  64. .query(q -> q.match(t -> t.field("age").query("30"))
  65. ),
  66. User.class
  67. );
  68. // 查询匹配
  69. System.out.println("took:" + response.took());
  70. System.out.println("timeout:" + response.timedOut());
  71. System.out.println("total:" + response.hits().total().value());
  72. System.out.println("MaxScore:" + response.hits().maxScore());
  73. System.out.println("hits========>>");
  74. List<Hit<User>> hits = response.hits().hits();
  75. for (Hit<User> hit : hits) {
  76. User user = hit.source();
  77. // 输出每条查询的结果信息
  78. System.out.println(user);
  79. }
  80. System.out.println("<<========");
  81. // 关闭 es 客户端
  82. transport.close();
  83. restClient.close();
  84. }
  85. }

image.png
分页查询

  1. package com.atguigu.es.test.query;
  2. import co.elastic.clients.elasticsearch.ElasticsearchClient;
  3. import co.elastic.clients.elasticsearch._types.query_dsl.Query;
  4. import co.elastic.clients.elasticsearch.core.SearchResponse;
  5. import co.elastic.clients.elasticsearch.core.search.Hit;
  6. import co.elastic.clients.json.jackson.JacksonJsonpMapper;
  7. import co.elastic.clients.transport.ElasticsearchTransport;
  8. import co.elastic.clients.transport.rest_client.RestClientTransport;
  9. import com.atguigu.es.test.User;
  10. import org.apache.http.HttpHost;
  11. import org.apache.http.auth.AuthScope;
  12. import org.apache.http.auth.UsernamePasswordCredentials;
  13. import org.apache.http.client.CredentialsProvider;
  14. import org.apache.http.impl.client.BasicCredentialsProvider;
  15. import org.apache.http.ssl.SSLContextBuilder;
  16. import org.apache.http.ssl.SSLContexts;
  17. import org.elasticsearch.client.RestClient;
  18. import javax.net.ssl.SSLContext;
  19. import java.io.InputStream;
  20. import java.nio.file.Files;
  21. import java.nio.file.Path;
  22. import java.nio.file.Paths;
  23. import java.security.KeyStore;
  24. import java.security.cert.Certificate;
  25. import java.security.cert.CertificateFactory;
  26. import java.util.List;
  27. /**
  28. * @author: zhangxin
  29. * @date: 2022/3/31
  30. */
  31. public class PageClient {
  32. private static Query.Builder q;
  33. public static void main(String[] args) throws Exception {
  34. // 用户认证对象
  35. final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
  36. // 设置账号密码
  37. credentialsProvider.setCredentials(
  38. AuthScope.ANY, new UsernamePasswordCredentials("elastic", "wkZQNElpnNj6+QWflIBU"));
  39. Path caCertificatePath = Paths.get("d:/http_ca.crt");
  40. CertificateFactory factory = CertificateFactory.getInstance("X.509");
  41. Certificate trustedCa;
  42. try (InputStream is = Files.newInputStream(caCertificatePath)) {
  43. trustedCa = factory.generateCertificate(is);
  44. }
  45. KeyStore trustStore = KeyStore.getInstance("pkcs12");
  46. trustStore.load(null, null);
  47. trustStore.setCertificateEntry("ca", trustedCa);
  48. SSLContextBuilder sslContextBuilder = SSLContexts.custom()
  49. .loadTrustMaterial(trustStore, null);
  50. final SSLContext sslContext = sslContextBuilder.build();
  51. // 创建 es 客户端
  52. RestClient restClient = RestClient.builder(
  53. new HttpHost("172.18.1.31", 9200, "https"))
  54. .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setSSLContext(sslContext)
  55. .setDefaultCredentialsProvider(credentialsProvider)).build();
  56. // 使用 Jackson 映射器创建传输层
  57. ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
  58. // 创建 API 客户端
  59. ElasticsearchClient esClient = new ElasticsearchClient(transport);
  60. // 创建搜索请求对象
  61. SearchResponse<User> response = esClient.search(s -> s.index("user").from(0).size(2), User.class);
  62. // 查询匹配
  63. System.out.println("took:" + response.took());
  64. System.out.println("timeout:" + response.timedOut());
  65. System.out.println("total:" + response.hits().total().value());
  66. System.out.println("MaxScore:" + response.hits().maxScore());
  67. System.out.println("hits========>>");
  68. List<Hit<User>> hits = response.hits().hits();
  69. for (Hit<User> hit : hits) {
  70. User user = hit.source();
  71. // 输出每条查询的结果信息
  72. System.out.println(user);
  73. }
  74. System.out.println("<<========");
  75. // 关闭 es 客户端
  76. transport.close();
  77. restClient.close();
  78. }
  79. }

image.png
数据排序

  1. package com.atguigu.es.test.query;
  2. import co.elastic.clients.elasticsearch.ElasticsearchClient;
  3. import co.elastic.clients.elasticsearch._types.SortOptions;
  4. import co.elastic.clients.elasticsearch._types.SortOrder;
  5. import co.elastic.clients.elasticsearch._types.query_dsl.Query;
  6. import co.elastic.clients.elasticsearch.core.SearchResponse;
  7. import co.elastic.clients.elasticsearch.core.search.Hit;
  8. import co.elastic.clients.json.jackson.JacksonJsonpMapper;
  9. import co.elastic.clients.transport.ElasticsearchTransport;
  10. import co.elastic.clients.transport.rest_client.RestClientTransport;
  11. import com.atguigu.es.test.User;
  12. import org.apache.http.HttpHost;
  13. import org.apache.http.auth.AuthScope;
  14. import org.apache.http.auth.UsernamePasswordCredentials;
  15. import org.apache.http.client.CredentialsProvider;
  16. import org.apache.http.impl.client.BasicCredentialsProvider;
  17. import org.apache.http.ssl.SSLContextBuilder;
  18. import org.apache.http.ssl.SSLContexts;
  19. import org.elasticsearch.client.RestClient;
  20. import javax.net.ssl.SSLContext;
  21. import java.io.InputStream;
  22. import java.nio.file.Files;
  23. import java.nio.file.Path;
  24. import java.nio.file.Paths;
  25. import java.security.KeyStore;
  26. import java.security.cert.Certificate;
  27. import java.security.cert.CertificateFactory;
  28. import java.util.List;
  29. /**
  30. * @author: zhangxin
  31. * @date: 2022/3/31
  32. */
  33. public class SortClient {
  34. private static Query.Builder q;
  35. public static void main(String[] args) throws Exception {
  36. // 用户认证对象
  37. final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
  38. // 设置账号密码
  39. credentialsProvider.setCredentials(
  40. AuthScope.ANY, new UsernamePasswordCredentials("elastic", "wkZQNElpnNj6+QWflIBU"));
  41. Path caCertificatePath = Paths.get("d:/http_ca.crt");
  42. CertificateFactory factory = CertificateFactory.getInstance("X.509");
  43. Certificate trustedCa;
  44. try (InputStream is = Files.newInputStream(caCertificatePath)) {
  45. trustedCa = factory.generateCertificate(is);
  46. }
  47. KeyStore trustStore = KeyStore.getInstance("pkcs12");
  48. trustStore.load(null, null);
  49. trustStore.setCertificateEntry("ca", trustedCa);
  50. SSLContextBuilder sslContextBuilder = SSLContexts.custom()
  51. .loadTrustMaterial(trustStore, null);
  52. final SSLContext sslContext = sslContextBuilder.build();
  53. // 创建 es 客户端
  54. RestClient restClient = RestClient.builder(
  55. new HttpHost("172.18.1.31", 9200, "https"))
  56. .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setSSLContext(sslContext)
  57. .setDefaultCredentialsProvider(credentialsProvider)).build();
  58. // 使用 Jackson 映射器创建传输层
  59. ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
  60. // 创建 API 客户端
  61. ElasticsearchClient esClient = new ElasticsearchClient(transport);
  62. // 创建搜索请求对象
  63. SearchResponse<User> response = esClient.search(s -> s.index("user").sort(so -> so.field(v -> v.field("age").order(SortOrder.Asc))), User.class);
  64. // 查询匹配
  65. System.out.println("took:" + response.took());
  66. System.out.println("timeout:" + response.timedOut());
  67. System.out.println("total:" + response.hits().total().value());
  68. System.out.println("MaxScore:" + response.hits().maxScore());
  69. System.out.println("hits========>>");
  70. List<Hit<User>> hits = response.hits().hits();
  71. for (Hit<User> hit : hits) {
  72. User user = hit.source();
  73. // 输出每条查询的结果信息
  74. System.out.println(user);
  75. }
  76. System.out.println("<<========");
  77. // 关闭 es 客户端
  78. transport.close();
  79. restClient.close();
  80. }
  81. }

image.png
过滤字段

  1. package com.atguigu.es.test.query;
  2. import co.elastic.clients.elasticsearch.ElasticsearchClient;
  3. import co.elastic.clients.elasticsearch._types.query_dsl.Query;
  4. import co.elastic.clients.elasticsearch.core.SearchResponse;
  5. import co.elastic.clients.elasticsearch.core.search.Hit;
  6. import co.elastic.clients.json.jackson.JacksonJsonpMapper;
  7. import co.elastic.clients.transport.ElasticsearchTransport;
  8. import co.elastic.clients.transport.rest_client.RestClientTransport;
  9. import com.atguigu.es.test.User;
  10. import org.apache.http.HttpHost;
  11. import org.apache.http.auth.AuthScope;
  12. import org.apache.http.auth.UsernamePasswordCredentials;
  13. import org.apache.http.client.CredentialsProvider;
  14. import org.apache.http.impl.client.BasicCredentialsProvider;
  15. import org.apache.http.ssl.SSLContextBuilder;
  16. import org.apache.http.ssl.SSLContexts;
  17. import org.elasticsearch.client.RestClient;
  18. import javax.net.ssl.SSLContext;
  19. import java.io.InputStream;
  20. import java.nio.file.Files;
  21. import java.nio.file.Path;
  22. import java.nio.file.Paths;
  23. import java.security.KeyStore;
  24. import java.security.cert.Certificate;
  25. import java.security.cert.CertificateFactory;
  26. import java.util.List;
  27. /**
  28. * @author: zhangxin
  29. * @date: 2022/3/31
  30. */
  31. public class FetchClient {
  32. private static Query.Builder q;
  33. public static void main(String[] args) throws Exception {
  34. // 用户认证对象
  35. final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
  36. // 设置账号密码
  37. credentialsProvider.setCredentials(
  38. AuthScope.ANY, new UsernamePasswordCredentials("elastic", "wkZQNElpnNj6+QWflIBU"));
  39. Path caCertificatePath = Paths.get("d:/http_ca.crt");
  40. CertificateFactory factory = CertificateFactory.getInstance("X.509");
  41. Certificate trustedCa;
  42. try (InputStream is = Files.newInputStream(caCertificatePath)) {
  43. trustedCa = factory.generateCertificate(is);
  44. }
  45. KeyStore trustStore = KeyStore.getInstance("pkcs12");
  46. trustStore.load(null, null);
  47. trustStore.setCertificateEntry("ca", trustedCa);
  48. SSLContextBuilder sslContextBuilder = SSLContexts.custom()
  49. .loadTrustMaterial(trustStore, null);
  50. final SSLContext sslContext = sslContextBuilder.build();
  51. // 创建 es 客户端
  52. RestClient restClient = RestClient.builder(
  53. new HttpHost("172.18.1.31", 9200, "https"))
  54. .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setSSLContext(sslContext)
  55. .setDefaultCredentialsProvider(credentialsProvider)).build();
  56. // 使用 Jackson 映射器创建传输层
  57. ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
  58. // 创建 API 客户端
  59. ElasticsearchClient esClient = new ElasticsearchClient(transport);
  60. // 创建搜索请求对象
  61. SearchResponse<User> response = esClient.search(s -> s.index("user").source(f -> f.filter(m -> m.includes("name", "age"))), User.class);
  62. // 查询匹配
  63. System.out.println("took:" + response.took());
  64. System.out.println("timeout:" + response.timedOut());
  65. System.out.println("total:" + response.hits().total().value());
  66. System.out.println("MaxScore:" + response.hits().maxScore());
  67. System.out.println("hits========>>");
  68. List<Hit<User>> hits = response.hits().hits();
  69. for (Hit<User> hit : hits) {
  70. User user = hit.source();
  71. // 输出每条查询的结果信息
  72. System.out.println(user);
  73. }
  74. System.out.println("<<========");
  75. // 关闭 es 客户端
  76. transport.close();
  77. restClient.close();
  78. }
  79. }

image.png
Bool 查询

  1. package com.atguigu.es.test.query;
  2. import co.elastic.clients.elasticsearch.ElasticsearchClient;
  3. import co.elastic.clients.elasticsearch._types.query_dsl.Query;
  4. import co.elastic.clients.elasticsearch._types.query_dsl.QueryBuilders;
  5. import co.elastic.clients.elasticsearch.core.SearchResponse;
  6. import co.elastic.clients.elasticsearch.core.search.Hit;
  7. import co.elastic.clients.json.jackson.JacksonJsonpMapper;
  8. import co.elastic.clients.transport.ElasticsearchTransport;
  9. import co.elastic.clients.transport.rest_client.RestClientTransport;
  10. import com.atguigu.es.test.User;
  11. import org.apache.http.HttpHost;
  12. import org.apache.http.auth.AuthScope;
  13. import org.apache.http.auth.UsernamePasswordCredentials;
  14. import org.apache.http.client.CredentialsProvider;
  15. import org.apache.http.impl.client.BasicCredentialsProvider;
  16. import org.apache.http.ssl.SSLContextBuilder;
  17. import org.apache.http.ssl.SSLContexts;
  18. import org.elasticsearch.client.RestClient;
  19. import javax.net.ssl.SSLContext;
  20. import java.io.InputStream;
  21. import java.nio.file.Files;
  22. import java.nio.file.Path;
  23. import java.nio.file.Paths;
  24. import java.security.KeyStore;
  25. import java.security.cert.Certificate;
  26. import java.security.cert.CertificateFactory;
  27. import java.util.List;
  28. /**
  29. * @author: zhangxin
  30. * @date: 2022/3/31
  31. */
  32. public class BoolClient {
  33. private static Query.Builder q;
  34. public static void main(String[] args) throws Exception {
  35. // 用户认证对象
  36. final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
  37. // 设置账号密码
  38. credentialsProvider.setCredentials(
  39. AuthScope.ANY, new UsernamePasswordCredentials("elastic", "wkZQNElpnNj6+QWflIBU"));
  40. Path caCertificatePath = Paths.get("d:/http_ca.crt");
  41. CertificateFactory factory = CertificateFactory.getInstance("X.509");
  42. Certificate trustedCa;
  43. try (InputStream is = Files.newInputStream(caCertificatePath)) {
  44. trustedCa = factory.generateCertificate(is);
  45. }
  46. KeyStore trustStore = KeyStore.getInstance("pkcs12");
  47. trustStore.load(null, null);
  48. trustStore.setCertificateEntry("ca", trustedCa);
  49. SSLContextBuilder sslContextBuilder = SSLContexts.custom()
  50. .loadTrustMaterial(trustStore, null);
  51. final SSLContext sslContext = sslContextBuilder.build();
  52. // 创建 es 客户端
  53. RestClient restClient = RestClient.builder(
  54. new HttpHost("172.18.1.31", 9200, "https"))
  55. .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setSSLContext(sslContext)
  56. .setDefaultCredentialsProvider(credentialsProvider)).build();
  57. // 使用 Jackson 映射器创建传输层
  58. ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
  59. // 创建 API 客户端
  60. ElasticsearchClient esClient = new ElasticsearchClient(transport);
  61. // 创建搜索请求对象
  62. SearchResponse<User> response = esClient.search(s -> s
  63. .index("user")
  64. .query(q -> q.bool(b ->
  65. b.must(qu -> qu.match(m -> m.field("age").query("30")))
  66. .mustNot(mn -> mn.match(m -> m.field("name").query("zhangsan")))
  67. .should(sh -> sh.match(m -> m.field("sex").query("男")))
  68. )), User.class);
  69. // 查询匹配
  70. System.out.println("took:" + response.took());
  71. System.out.println("timeout:" + response.timedOut());
  72. System.out.println("total:" + response.hits().total().value());
  73. System.out.println("MaxScore:" + response.hits().maxScore());
  74. System.out.println("hits========>>");
  75. List<Hit<User>> hits = response.hits().hits();
  76. for (Hit<User> hit : hits) {
  77. User user = hit.source();
  78. // 输出每条查询的结果信息
  79. System.out.println(user);
  80. }
  81. System.out.println("<<========");
  82. // 关闭 es 客户端
  83. transport.close();
  84. restClient.close();
  85. }
  86. }

image.png
范围查询

  1. package com.atguigu.es.test.query;
  2. import co.elastic.clients.elasticsearch.ElasticsearchClient;
  3. import co.elastic.clients.elasticsearch._types.query_dsl.Query;
  4. import co.elastic.clients.elasticsearch.core.SearchResponse;
  5. import co.elastic.clients.elasticsearch.core.search.Hit;
  6. import co.elastic.clients.json.JsonData;
  7. import co.elastic.clients.json.jackson.JacksonJsonpMapper;
  8. import co.elastic.clients.transport.ElasticsearchTransport;
  9. import co.elastic.clients.transport.rest_client.RestClientTransport;
  10. import com.atguigu.es.test.User;
  11. import org.apache.http.HttpHost;
  12. import org.apache.http.auth.AuthScope;
  13. import org.apache.http.auth.UsernamePasswordCredentials;
  14. import org.apache.http.client.CredentialsProvider;
  15. import org.apache.http.impl.client.BasicCredentialsProvider;
  16. import org.apache.http.ssl.SSLContextBuilder;
  17. import org.apache.http.ssl.SSLContexts;
  18. import org.elasticsearch.client.RestClient;
  19. import javax.net.ssl.SSLContext;
  20. import java.io.InputStream;
  21. import java.nio.file.Files;
  22. import java.nio.file.Path;
  23. import java.nio.file.Paths;
  24. import java.security.KeyStore;
  25. import java.security.cert.Certificate;
  26. import java.security.cert.CertificateFactory;
  27. import java.util.List;
  28. /**
  29. * @author: zhangxin
  30. * @date: 2022/3/31
  31. */
  32. public class RangeClient {
  33. private static Query.Builder q;
  34. public static void main(String[] args) throws Exception {
  35. // 用户认证对象
  36. final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
  37. // 设置账号密码
  38. credentialsProvider.setCredentials(
  39. AuthScope.ANY, new UsernamePasswordCredentials("elastic", "wkZQNElpnNj6+QWflIBU"));
  40. Path caCertificatePath = Paths.get("d:/http_ca.crt");
  41. CertificateFactory factory = CertificateFactory.getInstance("X.509");
  42. Certificate trustedCa;
  43. try (InputStream is = Files.newInputStream(caCertificatePath)) {
  44. trustedCa = factory.generateCertificate(is);
  45. }
  46. KeyStore trustStore = KeyStore.getInstance("pkcs12");
  47. trustStore.load(null, null);
  48. trustStore.setCertificateEntry("ca", trustedCa);
  49. SSLContextBuilder sslContextBuilder = SSLContexts.custom()
  50. .loadTrustMaterial(trustStore, null);
  51. final SSLContext sslContext = sslContextBuilder.build();
  52. // 创建 es 客户端
  53. RestClient restClient = RestClient.builder(
  54. new HttpHost("172.18.1.31", 9200, "https"))
  55. .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setSSLContext(sslContext)
  56. .setDefaultCredentialsProvider(credentialsProvider)).build();
  57. // 使用 Jackson 映射器创建传输层
  58. ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
  59. // 创建 API 客户端
  60. ElasticsearchClient esClient = new ElasticsearchClient(transport);
  61. // 创建搜索请求对象
  62. SearchResponse<User> response = esClient.search(s -> s.index("user").query(q -> q.range(r -> r.field("age")
  63. .gte(JsonData.of("30")).lte(JsonData.of("40")))), User.class);
  64. // 查询匹配
  65. System.out.println("took:" + response.took());
  66. System.out.println("timeout:" + response.timedOut());
  67. System.out.println("total:" + response.hits().total().value());
  68. System.out.println("MaxScore:" + response.hits().maxScore());
  69. System.out.println("hits========>>");
  70. List<Hit<User>> hits = response.hits().hits();
  71. for (Hit<User> hit : hits) {
  72. User user = hit.source();
  73. // 输出每条查询的结果信息
  74. System.out.println(user);
  75. }
  76. System.out.println("<<========");
  77. // 关闭 es 客户端
  78. transport.close();
  79. restClient.close();
  80. }
  81. }

image.png
模糊查询

  1. package com.atguigu.es.test.query;
  2. import co.elastic.clients.elasticsearch.ElasticsearchClient;
  3. import co.elastic.clients.elasticsearch._types.query_dsl.Query;
  4. import co.elastic.clients.elasticsearch.core.SearchResponse;
  5. import co.elastic.clients.elasticsearch.core.search.Hit;
  6. import co.elastic.clients.json.jackson.JacksonJsonpMapper;
  7. import co.elastic.clients.transport.ElasticsearchTransport;
  8. import co.elastic.clients.transport.rest_client.RestClientTransport;
  9. import com.atguigu.es.test.User;
  10. import org.apache.http.HttpHost;
  11. import org.apache.http.auth.AuthScope;
  12. import org.apache.http.auth.UsernamePasswordCredentials;
  13. import org.apache.http.client.CredentialsProvider;
  14. import org.apache.http.impl.client.BasicCredentialsProvider;
  15. import org.apache.http.ssl.SSLContextBuilder;
  16. import org.apache.http.ssl.SSLContexts;
  17. import org.elasticsearch.client.RestClient;
  18. import javax.net.ssl.SSLContext;
  19. import java.io.InputStream;
  20. import java.nio.file.Files;
  21. import java.nio.file.Path;
  22. import java.nio.file.Paths;
  23. import java.security.KeyStore;
  24. import java.security.cert.Certificate;
  25. import java.security.cert.CertificateFactory;
  26. import java.util.List;
  27. /**
  28. * @author: zhangxin
  29. * @date: 2022/3/31
  30. */
  31. public class FuzzyClient {
  32. private static Query.Builder q;
  33. public static void main(String[] args) throws Exception {
  34. // 用户认证对象
  35. final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
  36. // 设置账号密码
  37. credentialsProvider.setCredentials(
  38. AuthScope.ANY, new UsernamePasswordCredentials("elastic", "wkZQNElpnNj6+QWflIBU"));
  39. Path caCertificatePath = Paths.get("d:/http_ca.crt");
  40. CertificateFactory factory = CertificateFactory.getInstance("X.509");
  41. Certificate trustedCa;
  42. try (InputStream is = Files.newInputStream(caCertificatePath)) {
  43. trustedCa = factory.generateCertificate(is);
  44. }
  45. KeyStore trustStore = KeyStore.getInstance("pkcs12");
  46. trustStore.load(null, null);
  47. trustStore.setCertificateEntry("ca", trustedCa);
  48. SSLContextBuilder sslContextBuilder = SSLContexts.custom()
  49. .loadTrustMaterial(trustStore, null);
  50. final SSLContext sslContext = sslContextBuilder.build();
  51. // 创建 es 客户端
  52. RestClient restClient = RestClient.builder(
  53. new HttpHost("172.18.1.31", 9200, "https"))
  54. .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setSSLContext(sslContext)
  55. .setDefaultCredentialsProvider(credentialsProvider)).build();
  56. // 使用 Jackson 映射器创建传输层
  57. ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
  58. // 创建 API 客户端
  59. ElasticsearchClient esClient = new ElasticsearchClient(transport);
  60. // 创建搜索请求对象
  61. SearchResponse<User> response = esClient.search(s -> s.index("user")
  62. .query(q -> q.fuzzy(f -> f.field("name").value("zhangsan").fuzziness("1"))), User.class);
  63. // 查询匹配
  64. System.out.println("took:" + response.took());
  65. System.out.println("timeout:" + response.timedOut());
  66. System.out.println("total:" + response.hits().total().value());
  67. System.out.println("MaxScore:" + response.hits().maxScore());
  68. System.out.println("hits========>>");
  69. List<Hit<User>> hits = response.hits().hits();
  70. for (Hit<User> hit : hits) {
  71. User user = hit.source();
  72. // 输出每条查询的结果信息
  73. System.out.println(user);
  74. }
  75. System.out.println("<<========");
  76. // 关闭 es 客户端
  77. transport.close();
  78. restClient.close();
  79. }
  80. }

image.png

  1. 高亮查询 ```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 {

    1. // 用户认证对象
    2. final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    3. // 设置账号密码
    4. credentialsProvider.setCredentials(
    5. AuthScope.ANY, new UsernamePasswordCredentials("elastic", "wkZQNElpnNj6+QWflIBU"));
    6. Path caCertificatePath = Paths.get("d:/http_ca.crt");
    7. CertificateFactory factory = CertificateFactory.getInstance("X.509");
    8. Certificate trustedCa;
    9. try (InputStream is = Files.newInputStream(caCertificatePath)) {
    10. trustedCa = factory.generateCertificate(is);
    11. }
    12. KeyStore trustStore = KeyStore.getInstance("pkcs12");
    13. trustStore.load(null, null);
    14. trustStore.setCertificateEntry("ca", trustedCa);
    15. SSLContextBuilder sslContextBuilder = SSLContexts.custom()
    16. .loadTrustMaterial(trustStore, null);
    17. final SSLContext sslContext = sslContextBuilder.build();
    18. // 创建 es 客户端
    19. RestClient restClient = RestClient.builder(
    20. new HttpHost("172.18.1.31", 9200, "https"))
    21. .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setSSLContext(sslContext)
    22. .setDefaultCredentialsProvider(credentialsProvider)).build();
    23. // 使用 Jackson 映射器创建传输层
    24. ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
    25. // 创建 API 客户端
    26. ElasticsearchClient esClient = new ElasticsearchClient(transport);
    27. // 创建搜索请求对象
    28. SearchResponse<User> response = esClient.search(s -> s.index("user")
    29. .query(q -> q.term(t -> t.field("name").value("zhangsan")))
    30. .highlight(h -> h.fields("name", hh -> hh.preTags("<font color='red'>").postTags("</font>"))
    31. ), User.class);
    32. // 查询匹配
    33. System.out.println("took:" + response.took());
    34. System.out.println("timeout:" + response.timedOut());
    35. System.out.println("total:" + response.hits().total().value());
    36. System.out.println("MaxScore:" + response.hits().maxScore());
    37. System.out.println("hits========>>");
    38. List<Hit<User>> hits = response.hits().hits();
    39. for (Hit<User> hit : hits) {
    40. System.out.println(hit.highlight().get("name").get(0));
    41. User user = hit.source();
    42. // 输出每条查询的结果信息
    43. System.out.println(user);
    44. }
    45. System.out.println("<<========");
    46. // 关闭 es 客户端
    47. transport.close();
    48. restClient.close();

    } } ``` image.png

  1. 聚合查询

最大年龄

  1. package com.atguigu.es.test.query.aggregation;
  2. import co.elastic.clients.elasticsearch.ElasticsearchClient;
  3. import co.elastic.clients.elasticsearch._types.aggregations.HistogramBucket;
  4. import co.elastic.clients.elasticsearch._types.aggregations.MaxAggregate;
  5. import co.elastic.clients.elasticsearch._types.query_dsl.Query;
  6. import co.elastic.clients.elasticsearch.core.SearchResponse;
  7. import co.elastic.clients.elasticsearch.core.search.Hit;
  8. import co.elastic.clients.json.jackson.JacksonJsonpMapper;
  9. import co.elastic.clients.transport.ElasticsearchTransport;
  10. import co.elastic.clients.transport.rest_client.RestClientTransport;
  11. import com.atguigu.es.test.User;
  12. import org.apache.http.HttpHost;
  13. import org.apache.http.auth.AuthScope;
  14. import org.apache.http.auth.UsernamePasswordCredentials;
  15. import org.apache.http.client.CredentialsProvider;
  16. import org.apache.http.impl.client.BasicCredentialsProvider;
  17. import org.apache.http.ssl.SSLContextBuilder;
  18. import org.apache.http.ssl.SSLContexts;
  19. import org.elasticsearch.client.RestClient;
  20. import javax.net.ssl.SSLContext;
  21. import java.io.InputStream;
  22. import java.nio.file.Files;
  23. import java.nio.file.Path;
  24. import java.nio.file.Paths;
  25. import java.security.KeyStore;
  26. import java.security.cert.Certificate;
  27. import java.security.cert.CertificateFactory;
  28. import java.util.List;
  29. /**
  30. * @author: zhangxin
  31. * @date: 2022/3/31
  32. */
  33. public class AggregagionClient {
  34. private static Query.Builder q;
  35. public static void main(String[] args) throws Exception {
  36. // 用户认证对象
  37. final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
  38. // 设置账号密码
  39. credentialsProvider.setCredentials(
  40. AuthScope.ANY, new UsernamePasswordCredentials("elastic", "wkZQNElpnNj6+QWflIBU"));
  41. Path caCertificatePath = Paths.get("d:/http_ca.crt");
  42. CertificateFactory factory = CertificateFactory.getInstance("X.509");
  43. Certificate trustedCa;
  44. try (InputStream is = Files.newInputStream(caCertificatePath)) {
  45. trustedCa = factory.generateCertificate(is);
  46. }
  47. KeyStore trustStore = KeyStore.getInstance("pkcs12");
  48. trustStore.load(null, null);
  49. trustStore.setCertificateEntry("ca", trustedCa);
  50. SSLContextBuilder sslContextBuilder = SSLContexts.custom()
  51. .loadTrustMaterial(trustStore, null);
  52. final SSLContext sslContext = sslContextBuilder.build();
  53. // 创建 es 客户端
  54. RestClient restClient = RestClient.builder(
  55. new HttpHost("172.18.1.31", 9200, "https"))
  56. .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setSSLContext(sslContext)
  57. .setDefaultCredentialsProvider(credentialsProvider)).build();
  58. // 使用 Jackson 映射器创建传输层
  59. ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
  60. // 创建 API 客户端
  61. ElasticsearchClient esClient = new ElasticsearchClient(transport);
  62. // 创建搜索请求对象
  63. SearchResponse<User> response = esClient.search(s -> s.index("user").aggregations("maxAge", agg -> agg.max(ag -> ag.field("age"))), User.class);
  64. // 查询匹配
  65. System.out.println("took:" + response.took());
  66. System.out.println("timeout:" + response.timedOut());
  67. System.out.println("total:" + response.hits().total().value());
  68. System.out.println("MaxScore:" + response.hits().maxScore());
  69. System.out.println("hits========>>");
  70. MaxAggregate maxAge = response.aggregations().get("maxAge").max();
  71. System.out.println("最大年龄" + maxAge.value() + "岁");
  72. System.out.println("<<========");
  73. // 关闭 es 客户端
  74. transport.close();
  75. restClient.close();
  76. }
  77. }

image.png
分组统计

  1. package com.atguigu.es.test.query.aggregation;
  2. import co.elastic.clients.elasticsearch.ElasticsearchClient;
  3. import co.elastic.clients.elasticsearch._types.aggregations.LongTermsBucket;
  4. import co.elastic.clients.elasticsearch._types.query_dsl.Query;
  5. import co.elastic.clients.elasticsearch.core.SearchResponse;
  6. import co.elastic.clients.elasticsearch.core.search.Hit;
  7. import co.elastic.clients.json.jackson.JacksonJsonpMapper;
  8. import co.elastic.clients.transport.ElasticsearchTransport;
  9. import co.elastic.clients.transport.rest_client.RestClientTransport;
  10. import com.atguigu.es.test.User;
  11. import org.apache.http.HttpHost;
  12. import org.apache.http.auth.AuthScope;
  13. import org.apache.http.auth.UsernamePasswordCredentials;
  14. import org.apache.http.client.CredentialsProvider;
  15. import org.apache.http.impl.client.BasicCredentialsProvider;
  16. import org.apache.http.ssl.SSLContextBuilder;
  17. import org.apache.http.ssl.SSLContexts;
  18. import org.elasticsearch.client.RestClient;
  19. import javax.net.ssl.SSLContext;
  20. import java.io.InputStream;
  21. import java.nio.file.Files;
  22. import java.nio.file.Path;
  23. import java.nio.file.Paths;
  24. import java.security.KeyStore;
  25. import java.security.cert.Certificate;
  26. import java.security.cert.CertificateFactory;
  27. import java.util.List;
  28. /**
  29. * @author: zhangxin
  30. * @date: 2022/3/31
  31. */
  32. public class GroupClient {
  33. private static Query.Builder q;
  34. public static void main(String[] args) throws Exception {
  35. // 用户认证对象
  36. final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
  37. // 设置账号密码
  38. credentialsProvider.setCredentials(
  39. AuthScope.ANY, new UsernamePasswordCredentials("elastic", "wkZQNElpnNj6+QWflIBU"));
  40. Path caCertificatePath = Paths.get("d:/http_ca.crt");
  41. CertificateFactory factory = CertificateFactory.getInstance("X.509");
  42. Certificate trustedCa;
  43. try (InputStream is = Files.newInputStream(caCertificatePath)) {
  44. trustedCa = factory.generateCertificate(is);
  45. }
  46. KeyStore trustStore = KeyStore.getInstance("pkcs12");
  47. trustStore.load(null, null);
  48. trustStore.setCertificateEntry("ca", trustedCa);
  49. SSLContextBuilder sslContextBuilder = SSLContexts.custom()
  50. .loadTrustMaterial(trustStore, null);
  51. final SSLContext sslContext = sslContextBuilder.build();
  52. // 创建 es 客户端
  53. RestClient restClient = RestClient.builder(
  54. new HttpHost("172.18.1.31", 9200, "https"))
  55. .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setSSLContext(sslContext)
  56. .setDefaultCredentialsProvider(credentialsProvider)).build();
  57. // 使用 Jackson 映射器创建传输层
  58. ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
  59. // 创建 API 客户端
  60. ElasticsearchClient esClient = new ElasticsearchClient(transport);
  61. // 创建搜索请求对象
  62. SearchResponse<User> response = esClient.search(s -> s.index("user").aggregations("age groupby", agg -> agg.terms(ag -> ag.field("age"))), User.class);
  63. // 查询匹配
  64. System.out.println("took:" + response.took());
  65. System.out.println("timeout:" + response.timedOut());
  66. System.out.println("total:" + response.hits().total().value());
  67. System.out.println("MaxScore:" + response.hits().maxScore());
  68. System.out.println("hits========>>");
  69. List<LongTermsBucket> buckets = response.aggregations().get("age groupby").lterms().buckets().array();
  70. for (LongTermsBucket bucket : buckets) {
  71. System.out.println(bucket.key() + "岁有" + bucket.docCount() + "人");
  72. }
  73. System.out.println("<<========");
  74. // 关闭 es 客户端
  75. transport.close();
  76. restClient.close();
  77. }
  78. }

image.png