您当前的位置: 首页 >  ar

Dongguo丶

暂无认证

  • 1浏览

    0关注

    472博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Elasticsearch入门

Dongguo丶 发布时间:2021-10-30 00:17:45 ,浏览量:1

文章目录
  • Elasticsearch 安装
    • 下载软件
    • 安装软件
  • Elasticsearch 基本操作
    • RESTful
    • 客户端安装
    • 数据格式
    • HTTP 操作
      • 索引操作
        • 1) 创建索引
        • 2) 查看所有索引
        • 3) 查看单个索引
        • 4) 删除索引
      • 文档操作
        • 1) 创建文档
        • 2) 查看文档
        • 3) 修改文档
        • 4) 修改字段
        • 5) 删除文档
        • 6) 条件删除文档
        • 条件查询
        • 全量查询
        • 分页查询
        • 查询指定字段
        • 查询排序
        • 多条件查询
        • 范围查询
        • 全文检索
        • 完全匹配
        • 高亮查询
        • 聚合查询
    • 映射操作
      • 1) 创建映射
      • 2) 查看映射
    • Java API 操作
      • 创建 Maven 项目
      • 客户端对象
      • 索引操作
        • 1) 创建索引
        • 2) 查看索引
        • 3) 删除索引
      • 文档操作
        • 1) 新增文档
        • 2) 修改文档
        • 3) 查询文档
        • 4) 删除文档
        • 5) 批量操作
      • 高级查询
        • 1) 请求体查询
        • 2) 高亮查询
        • 3) 聚合查询

Elasticsearch 安装 下载软件

Elasticsearch 的官方地址: https://www.elastic.co/cn/ Elasticsearch 最新的版本是 7.15.1(截止 2021.10.28),我们选择 7.15.0 版本(最新版本半 年前的版本) 下载地址: https://www.elastic.co/cn/downloads/past-releases#elasticsearch

image-20211028201204207

image-20211028201046737

Elasticsearch 分为 Linux 和 Windows 版本,基于我们主要学习的是 Elasticsearch 的 Java 客户端的使用,所以使用的是安装较为简便的 Windows 版本。

安装软件

Windows 版的 Elasticsearch 的安装很简单,解压即安装完毕,解压后的 Elasticsearch 的 目录结构如下

image-20211028201502404

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

进入 bin 文件目录,点击 elasticsearch.bat 文件启动 ES 服务

image-20211028203810599

注意: 9300 端口为 Elasticsearch 集群间组件的通信端口, 9200 端口为浏览器访问的 http 协议 RESTful 端口。

启动报错,试过网上的解决办法仍然没有解决,但是访问地址能够成功,暂且打个标记TODO

报错信息

master 报错日志信息 :elastic ssl.SSLHandshakeException: no cipher suites in common
node 节点报错日志信息 :[2020-08-28T03:51:07,537][WARN ][o.e.t.OutboundHandler    ] [elasticsearch-data-0] send message failed [channel: Netty4TcpChannel{localAddress=0.0.0.0/0.0.0.0:40314, remoteAddress=elasticsearch-discovery/10.107.243.185:9300}]
javax.net.ssl.SSLException: Received fatal alert: handshake_failure

报的是ssl 错误,原因没有证书,es 使用x-pack启用了 ssl需生成证书, 制作证书参考下面网址 https://www.elastic.co/guide/en/elasticsearch/reference/6.3/configuring-tls.html#node-certificates

打开浏览器(推荐使用谷歌浏览器),输入地址: http://localhost:9200,测试结果

image-20211028203615146

Elasticsearch 基本操作 RESTful

REST 指的是一组架构约束条件和原则。满足这些约束条件和原则的应用程序或设计就 是 RESTful。 Web 应用程序最重要的 REST 原则是,客户端和服务器之间的交互在请求之 间是无状态的。从客户端到服务器的每个请求都必须包含理解请求所必需的信息。如果服务 器在请求之间的任何时间点重启,客户端不会得到通知。此外,无状态请求可以由任何可用 服务器回答,这十分适合云计算之类的环境。客户端可以缓存数据以改进性能。 在服务器端,应用程序状态和功能可以分为各种资源。资源是一个有趣的概念实体,它 向客户端公开。资源的例子有:应用程序对象、数据库记录、算法等等。每个资源都使用 URI (Universal Resource Identifier) 得到一个唯一的地址。所有资源都共享统一的接口,以便在客 户端和服务器之间传输状态。使用的是标准的 HTTP 方法,比如 GET、 PUT、 POST 和 DELETE。 在 REST 样式的 Web 服务中,每个资源都有一个地址。资源本身都是方法调用的目 标,方法列表对所有资源都是一样的。这些方法都是标准方法,包括 HTTP GET、 POST、 PUT、 DELETE,还可能包括 HEAD 和 OPTIONS。简单的理解就是,如果想要访问互联 网上的资源,就必须向资源所在的服务器发出请求,请求体中必须包含资源的网络路径, 以 及对资源进行的操作(增删改查)。

客户端安装

如果直接通过浏览器向 Elasticsearch 服务器发请求,那么需要在发送的请求中包含 HTTP 标准的方法,而 HTTP 的大部分特性且仅支持 GET 和 POST 方法。所以为了能方便 地进行客户端的访问,可以使用 Postman 软件 Postman 是一款强大的网页调试工具,提供功能强大的 Web API 和 HTTP 请求调试。 软件功能强大,界面简洁明晰、操作方便快捷,设计得很人性化。 Postman 中文版能够发送 任何类型的 HTTP 请求 (GET, HEAD, POST, PUT…),不仅能够表单提交,且可以附带任意 类型请求体。

Postman 官网: https://www.getpostman.com Postman 下载: https://www.getpostman.com/apps

image-20211028204227883

数据格式

Elasticsearch 是面向文档型数据库,一条数据在这里就是一个文档。 为了方便大家理解, 我们将 Elasticsearch 里存储文档数据和关系型数据库 MySQL 存储数据的概念进行一个类比

image-20211028204250290

ES 里的 Index 可以看做一个库,而 Types 相当于表, Documents 则相当于表的行。 这里 Types 的概念已经被逐渐弱化, Elasticsearch 6.X 中,一个 index 下已经只能包含一个 type, Elasticsearch 7.X 中, Type 的概念已经被删除了。

倒排索引

HTTP 操作 索引操作 1) 创建索引

对比关系型数据库,创建索引就等同于创建数据库

创建shopping索引

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

image-20211028204626941

请求后,服务器返回响应

image-20211028204707823

{
"acknowledged"【响应结果】 : true, # true 操作成功
"shards_acknowledged"【分片结果】 : true, # 分片操作成功
"index"【索引名称】 : "shopping"
}
# 注意:创建索引库的分片数默认 1 片,在 7.0.0 之前的 Elasticsearch 版本中,默认 5 片

如果重复添加索引,会返回错误信息 “index [shopping/8FORQzKESB6DJHuV9SpBeg] already exists”,

{
    "error": {
        "root_cause": [
            {
                "type": "resource_already_exists_exception",
                "reason": "index [shopping/8FORQzKESB6DJHuV9SpBeg] already exists",
                "index_uuid": "8FORQzKESB6DJHuV9SpBeg",
                "index": "shopping"
            }
        ],
        "type": "resource_already_exists_exception",
        "reason": "index [shopping/8FORQzKESB6DJHuV9SpBeg] already exists",
        "index_uuid": "8FORQzKESB6DJHuV9SpBeg",
        "index": "shopping"
    },
    "status": 400
}

put具有幂等性,创建索引不支持post

image-20211028215944526

2) 查看所有索引

在 Postman 中,向 ES 服务器发 GET 请求 : http://127.0.0.1:9200/_cat/indices?v

image-20211028204935391

这里请求路径中的_cat 表示查看的意思, indices 表示索引,所以整体含义就是查看当前 ES 服务器中的所有索引,就好像 MySQL 中的 show tables 的感觉,服务器响应结果如下

image-20211028205045447

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

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

image-20211028205132740

查看索引向 ES 服务器发送的请求路径和创建索引是一致的。但是 HTTP 方法不一致。这里 可以体会一下 RESTful 的意义, 请求后,服务器响应结果如下:

{
    "shopping": {
        "aliases": {},
        "mappings": {},
        "settings": {
            "index": {
                "routing": {
                    "allocation": {
                        "include": {
                            "_tier_preference": "data_content"
                        }
                    }
                },
                "number_of_shards": "1",
                "provided_name": "shopping",
                "creation_date": "1635425170469",
                "number_of_replicas": "1",
                "uuid": "8FORQzKESB6DJHuV9SpBeg",
                "version": {
                    "created": "7150099"
                }
            }
        }
    }
}

说明:

{
	"shopping"【
	索引名】: {
		"aliases"【
		别名】: {},
		"mappings"【
		映射】: {},
		"settings"【
		设置】: {
			"index"【
			设置 - 索引】: {
				"creation_date"【
				设置 - 索引 - 创建时间】: "1614265373911",
				"number_of_shards"【
				设置 - 索引 - 主分片数量】: "1",
				"number_of_replicas"【
				设置 - 索引 - 副分片数量】: "1",
				"uuid"【
				设置 - 索引 - 唯一标识】: "eI5wemRERTumxGCc1bAk2A",
				"version"【
				设置 - 索引 - 版本】: {
					"created": "7080099"
				},
				"provided_name"【
				设置 - 索引 - 名称】: "shopping"
			}
		}
	}
}
4) 删除索引

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

image-20211028205409659

响应

image-20211028205436925

重新访问索引时,服务器返回响应: 索引不存在

image-20211028205505091

文档操作 1) 创建文档

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

{
"title":"小米手机",
"category":"小米",
"images":"http://www.dongguo.com/xm.jpg",
"price":3999.00
}

image-20211028210141951

此处发送请求的方式必须为 POST,不能是 PUT,否则会发生错误

image-20211028220449996

服务器响应结果如下:

{
    "_index": "shopping",
    "_type": "phone",
    "_id": "FqD6xnwBJtrLfHHyk4LG",
    "_version": 1,
    "result": "created",
    "_shards": {
        "total": 2,
        "successful": 1,
        "failed": 0
    },
    "_seq_no": 0,
    "_primary_term": 1
}
{
	"_index"【
	索引】: "shopping",
		"_type"【
	类型 - 文档】: "_doc",
		"_id"【
	唯一标识】: "Xhsa2ncBlvF_7lxyCE9G", #可以类比为 MySQL 中的主键, 随机生成 "_version"【
	版本】: 1,
		"result"【
	结果】: "created", #这里的 create 表示创建成功 "_shards"【
	分片】: {
			"total"【
			分片 - 总数】: 2,
			"successful"【
			分片 - 成功】: 1,
			"failed"【
			分片 - 失败】: 0
		},
		"_seq_no": 0,
		"_primary_term": 1
}

上面的数据创建后,由于没有指定数据唯一性标识(ID),默认情况下, ES 服务器会随机 生成一个。创建内容相同的文档,id是不同的,这也是为什么不支持put的原因,put具有幂等性

如果想要自定义唯一性标识,需要在创建时指定: http://127.0.0.1:9200/shopping/phone/1

{
"title":"华为手机",
"category":"华为",
"images":"http://www.dongguo.com/xm.jpg",
"price":4999.00
}

image-20211028210034737

{
    "_index": "shopping",
    "_type": "phone",
    "_id": "1  ",
    "_version": 1,
    "result": "created",
    "_shards": {
        "total": 2,
        "successful": 1,
        "failed": 0
    },
    "_seq_no": 1,
    "_primary_term": 1
}

_id为1了

此处需要注意:如果增加数据时明确数据主键,那么请求方式也可以为 PUT

2) 查看文档

主键查询

查看文档时,需要指明文档的唯一性标识,类似于 MySQL 中数据的主键查询 在 Postman 中,向 ES 服务器发 GET 请求 : http://127.0.0.1:9200/shopping/phone/1

image-20211028210506309

查询成功后,服务器响应结果:

{
    "_index": "shopping",
    "_type": "phone",
    "_id": "1  ",
    "_version": 1,
    "_seq_no": 1,
    "_primary_term": 1,
    "found": true,
    "_source": {
        "title": "华为手机",
        "category": "华为",
        "images": "http://www.dongguo.com/xm.jpg",
        "price": 4999.00
    }
}
{
	"_index"【
	索引】: "shopping",
		"_type"【
	文档类型】: "_doc",
		"_id": "1",
		"_version": 2,
		"_seq_no": 2,
		"_primary_term": 2,
		"found"【
	查询结果】: true, #true 表示查找到, false 表示未查找到 "_source"【
	文档源信息】: {
		"title": "华为手机",
		"category": "华为",
		"images": "http://www.gulixueyuan.com/hw.jpg",
		"price": 4999.00
	}
}

全查询

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

image-20211028221107088

查询成功后,服务器响应结果:

{
    "took": 460,
    "timed_out": false,
    "_shards": {
        "total": 1,
        "successful": 1,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 2,
            "relation": "eq"
        },
        "max_score": 1.0,
        "hits": [
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "FqD6xnwBJtrLfHHyk4LG",
                "_score": 1.0,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.gulixueyuan.com/xm.jpg",
                    "price": 3999.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "1  ",
                "_score": 1.0,
                "_source": {
                    "title": "华为手机",
                    "category": "华为",
                    "images": "http://www.dongguo.com/hw.jpg",
                    "price": 4999.00
                }
            }
        ]
    }
}
3) 修改文档

全量修改

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

{
"title":"华为手机",
"category":"华为",
"images":"http://www.dongguo.com/hw.jpg",
"price":4999.00
}

image-20211028210854571

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

{
    "_index": "shopping",
    "_type": "phone",
    "_id": "1  ",
    "_version": 2,
    "result": "updated",
    "_shards": {
        "total": 2,
        "successful": 1,
        "failed": 0
    },
    "_seq_no": 2,
    "_primary_term": 1
}
{
	"_index": "shopping",
	"_type": "_doc",
	"_id": "1",
	"_version"【
	版本】: 2,
	"result"【
	结果】: "updated",
	#updated 表示数据被更新 "_shards": {
		"total": 2,
		"successful": 1,
		"failed": 0
	},
	"_seq_no": 2,
	"_primary_term": 2
}
4) 修改字段

局部修改

修改数据时,也可以只修改某一给条数据的局部信息

在 Postman 中,向 ES 服务器发 POST 请求 : http://127.0.0.1:9200/shopping/phone/1 请求体内容为:

{
	"doc": {
		"price": 3000.00
	}
}

image-20211028211259909

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

{
    "_index": "shopping",
    "_type": "phone",
    "_id": "1",
    "_version": 3,
    "result": "updated",
    "_shards": {
        "total": 2,
        "successful": 1,
        "failed": 0
    },
    "_seq_no": 5,
    "_primary_term": 1
}

根据唯一性标识,查询文档数据,文档数据已经更新

image-20211028211347028

{
    "_index": "shopping",
    "_type": "phone",
    "_id": "1",
    "_version": 3,
    "_seq_no": 5,
    "_primary_term": 1,
    "found": true,
    "_source": {
        "title": "华为手机",
        "category": "华为",
        "images": "http://www.dongguo.com/hw.jpg",
        "price": 3000.0
    }
}
5) 删除文档

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

image-20211028211717228

删除成功,服务器响应结果:

{
    "_index": "shopping",
    "_type": "phone",
    "_id": "1",
    "_version": 4,
    "result": "deleted",
    "_shards": {
        "total": 2,
        "successful": 1,
        "failed": 0
    },
    "_seq_no": 6,
    "_primary_term": 1
}
{
	"_index": "shopping",
	"_type": "_doc",
	"_id": "1",
	"_version"【
	版本】: 4,
	#对数据的操作, 都会更新版本 "result"【
	结果】: "deleted",
	#deleted 表示数据被标记为删除 "_shards": {
		"total": 2,
		"successful": 1,
		"failed": 0
	},
	"_seq_no": 4,
	"_primary_term": 2
}

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

image-20211028211823339

{
    "_index": "shopping",
    "_type": "phone",
    "_id": "1",
    "found": false
}

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

image-20211028211913394

{
    "_index": "shopping",
    "_type": "phone",
    "_id": "1",
    "_version": 1,
    "result": "not_found",
    "_shards": {
        "total": 2,
        "successful": 1,
        "failed": 0
    },
    "_seq_no": 7,
    "_primary_term": 1
}
{
	"_index": "shopping",
	"_type": "_doc",
	"_id": "1",
	"_version": 1,
	"result"【
	结果】: "not_found",
	#not_found 表示未查找到 "_shards": {
		"total": 2,
		"successful": 1,
		"failed": 0
	},
	"_seq_no": 5,
	"_primary_term": 2
}
6) 条件删除文档

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

{
"title":"小米手机",
"category":"小米",
"images":"http://www.dongguo.com/xm.jpg",
"price":4000.00
} 
{
"title":"华为手机",
"category":"华为",
"images":"http://www.dongguo.com/hw.jpg",
"price":4000.00
}

image-20211028212107400

image-20211028212127757

向ES 服务器发 POST 请求 : http://127.0.0.1:9200/shopping/_delete_by_query

请求体内容为:

{
	"query": {
		"match": {
			"price": 4000.00
		}
	}
}

image-20211028212300789

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

{
    "took": 175,
    "timed_out": false,
    "total": 2,
    "deleted": 2,
    "batches": 1,
    "version_conflicts": 0,
    "noops": 0,
    "retries": {
        "bulk": 0,
        "search": 0
    },
    "throttled_millis": 0,
    "requests_per_second": -1.0,
    "throttled_until_millis": 0,
    "failures": []
}
{
	"took"【
	耗时】: 175,
		"timed_out"【
	是否超时】: false,
		"total"【
	总数】: 2,
		"deleted"【
	删除数量】: 2,
		"batches": 1,
		"version_conflicts": 0,
		"noops": 0,
		"retries": {
			"bulk": 0,
			"search": 0
		},
		"throttled_millis": 0,
		"requests_per_second": -1.0,
		"throttled_until_millis": 0,
		"failures": []
}
条件查询

创建10条数据

image-20211028225642547

查询get http://127.0.0.1:9200/shopping/phone/_search?q=category:小米

image-20211028225717895

响应结果:

{
    "took": 12,
    "timed_out": false,
    "_shards": {
        "total": 1,
        "successful": 1,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 10,
            "relation": "eq"
        },
        "max_score": 0.42714816,
        "hits": [
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "1",
                "_score": 0.42714816,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "GKBex3wBJtrLfHHyFoJt",
                "_score": 0.42714816,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "GaBex3wBJtrLfHHyJIJ2",
                "_score": 0.42714816,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "GqBex3wBJtrLfHHyKYJN",
                "_score": 0.42714816,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "G6Bex3wBJtrLfHHyLILA",
                "_score": 0.42714816,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "HKBex3wBJtrLfHHyMYIB",
                "_score": 0.42714816,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "HaBex3wBJtrLfHHyNIIl",
                "_score": 0.42714816,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "HqBex3wBJtrLfHHyN4KX",
                "_score": 0.42714816,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "H6Bex3wBJtrLfHHyO4Lc",
                "_score": 0.42714816,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "IKBex3wBJtrLfHHyP4Jq",
                "_score": 0.42714816,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            }
        ]
    }
}

使用Params传递参数,有中文很容易出现乱码问题,改成使用请求体传递参数

{
    "query" : {
        "match" : {
            "category" : "小米"
        }
    }
}

image-20211028225814675

响应结果

{
    "took": 13,
    "timed_out": false,
    "_shards": {
        "total": 1,
        "successful": 1,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 10,
            "relation": "eq"
        },
        "max_score": 0.42714816,
        "hits": [
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "1",
                "_score": 0.42714816,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "GKBex3wBJtrLfHHyFoJt",
                "_score": 0.42714816,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "GaBex3wBJtrLfHHyJIJ2",
                "_score": 0.42714816,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "GqBex3wBJtrLfHHyKYJN",
                "_score": 0.42714816,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "G6Bex3wBJtrLfHHyLILA",
                "_score": 0.42714816,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "HKBex3wBJtrLfHHyMYIB",
                "_score": 0.42714816,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "HaBex3wBJtrLfHHyNIIl",
                "_score": 0.42714816,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "HqBex3wBJtrLfHHyN4KX",
                "_score": 0.42714816,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "H6Bex3wBJtrLfHHyO4Lc",
                "_score": 0.42714816,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "IKBex3wBJtrLfHHyP4Jq",
                "_score": 0.42714816,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            }
        ]
    }
}
全量查询
{
    "query" : {
        "match_all" : {
     
        }
    }
}

image-20211028225411703

分页查询

如果数据量过多,那么就要使用到分页了

{
    "query" : {
        "match_all" : {
     
        }
    },
    "from" : 0,
    "size" : 2
}

image-20211028230158985

from = (页码-1)*每页数据条数

响应结果

{
    "took": 5,
    "timed_out": false,
    "_shards": {
        "total": 1,
        "successful": 1,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 12,
            "relation": "eq"
        },
        "max_score": 1.0,
        "hits": [
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "1  ",
                "_score": 1.0,
                "_source": {
                    "title": "华为手机",
                    "category": "华为",
                    "images": "http://www.dongguo.com/hw.jpg",
                    "price": 4999.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "1",
                "_score": 1.0,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            }
        ]
    }
}
查询指定字段

比如只想查看title

{
    "query" : {
        "match_all" : {
     
        }
    },
    "from" : 0,
    "size" : 2,
    "_source" : ["title"]
}

image-20211028230646261

响应结果

{
    "took": 108,
    "timed_out": false,
    "_shards": {
        "total": 1,
        "successful": 1,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 12,
            "relation": "eq"
        },
        "max_score": 1.0,
        "hits": [
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "1  ",
                "_score": 1.0,
                "_source": {
                    "title": "华为手机"
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "1",
                "_score": 1.0,
                "_source": {
                    "title": "小米手机"
                }
            }
        ]
    }
}
查询排序
{
    "query" : {
        "match_all" : {
     
        }
    },
    "from" : 0,
    "size" : 2,
    "sort" : {
        "price" : {
            "order" : "desc"
        }
    }
}

image-20211028230934408

响应结果

{
    "took": 1142,
    "timed_out": false,
    "_shards": {
        "total": 1,
        "successful": 1,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 12,
            "relation": "eq"
        },
        "max_score": null,
        "hits": [
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "1  ",
                "_score": null,
                "_source": {
                    "title": "华为手机",
                    "category": "华为",
                    "images": "http://www.dongguo.com/hw.jpg",
                    "price": 4999.00
                },
                "sort": [
                    4999.0
                ]
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "1",
                "_score": null,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                },
                "sort": [
                    4000.0
                ]
            }
        ]
    }
}
多条件查询

bool 多条件

must 多个条件同时成立

{
    "query" : {
       "bool" : {
           "must" : [
               {
                   "match" : {
                       "category" : "小米"
                   }
               }
           ]
       }
    }
}

image-20211028231614652

响应结果

{
    "took": 20,
    "timed_out": false,
    "_shards": {
        "total": 1,
        "successful": 1,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 10,
            "relation": "eq"
        },
        "max_score": 0.42714816,
        "hits": [
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "1",
                "_score": 0.42714816,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "GKBex3wBJtrLfHHyFoJt",
                "_score": 0.42714816,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "GaBex3wBJtrLfHHyJIJ2",
                "_score": 0.42714816,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "GqBex3wBJtrLfHHyKYJN",
                "_score": 0.42714816,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "G6Bex3wBJtrLfHHyLILA",
                "_score": 0.42714816,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "HKBex3wBJtrLfHHyMYIB",
                "_score": 0.42714816,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "HaBex3wBJtrLfHHyNIIl",
                "_score": 0.42714816,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "HqBex3wBJtrLfHHyN4KX",
                "_score": 0.42714816,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "H6Bex3wBJtrLfHHyO4Lc",
                "_score": 0.42714816,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "IKBex3wBJtrLfHHyP4Jq",
                "_score": 0.42714816,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            }
        ]
    }
}

这些数据都相同 修改一个数据

{
"title":"小米手机",
"category":"小米",
"images":"http://www.dongguo.com/xm.jpg",
"price":3999.00
}

image-20211028232751804

多个条件同时成立查询

{
    "query" : {
       "bool" : {
           "must" : [
               {
                   "match" : {
                       "category" : "小米"
                   }
               },
               {
                   "match" : {
                       "price" : 3999.00
                   }
               }
           ]
       }
    }
}

image-20211028232639108

响应结果

{
    "took": 9,
    "timed_out": false,
    "_shards": {
        "total": 1,
        "successful": 1,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 1,
            "relation": "eq"
        },
        "max_score": 1.3934206,
        "hits": [
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "1",
                "_score": 1.3934206,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 3999.00
                }
            }
        ]
    }
}

多个条件或者查询

{
    "query" : {
       "bool" : {
           "should" : [
               {
                   "match" : {
                       "category" : "小米"
                   }
               },
               {
                   "match" : {
                       "category" : "华为"
                   }
               }
           ]
       }
    }
}

image-20211028233120746

响应结果

{
    "took": 18,
    "timed_out": false,
    "_shards": {
        "total": 1,
        "successful": 1,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 12,
            "relation": "eq"
        },
        "max_score": 3.4455333,
        "hits": [
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "1  ",
                "_score": 3.4455333,
                "_source": {
                    "title": "华为手机",
                    "category": "华为",
                    "images": "http://www.dongguo.com/hw.jpg",
                    "price": 4999.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "2",
                "_score": 3.4455333,
                "_source": {
                    "title": "华为手机",
                    "category": "华为",
                    "images": "http://www.dongguo.com/hw.jpg",
                    "price": 4000.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "GKBex3wBJtrLfHHyFoJt",
                "_score": 0.39342058,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "GaBex3wBJtrLfHHyJIJ2",
                "_score": 0.39342058,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "GqBex3wBJtrLfHHyKYJN",
                "_score": 0.39342058,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "G6Bex3wBJtrLfHHyLILA",
                "_score": 0.39342058,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "HKBex3wBJtrLfHHyMYIB",
                "_score": 0.39342058,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "HaBex3wBJtrLfHHyNIIl",
                "_score": 0.39342058,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "HqBex3wBJtrLfHHyN4KX",
                "_score": 0.39342058,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "H6Bex3wBJtrLfHHyO4Lc",
                "_score": 0.39342058,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            }
        ]
    }
}
范围查询
{
    "query" : {
       "bool" : {
           "should" : [
               {
                   "match" : {
                       "category" : "小米"
                   }
               },
               {
                   "match" : {
                       "category" : "华为"
                   }
               }
           ],
           "filter" : {
               "range" : {
                   "price" :{
                       "gt" : 4000.00
                   }
               }
           }
       }
    }
}

响应结果

{
    "took": 177,
    "timed_out": false,
    "_shards": {
        "total": 1,
        "successful": 1,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 1,
            "relation": "eq"
        },
        "max_score": 3.4455333,
        "hits": [
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "1  ",
                "_score": 3.4455333,
                "_source": {
                    "title": "华为手机",
                    "category": "华为",
                    "images": "http://www.dongguo.com/hw.jpg",
                    "price": 4999.00
                }
            }
        ]
    }
}
全文检索

ES将关键字进行了分词

{
    "query" : {
      "match" : {
          "category" : "米"
      }
    }
}

image-20211028233745124

{
    "took": 17,
    "timed_out": false,
    "_shards": {
        "total": 1,
        "successful": 1,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 10,
            "relation": "eq"
        },
        "max_score": 0.19671029,
        "hits": [
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "GKBex3wBJtrLfHHyFoJt",
                "_score": 0.19671029,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "GaBex3wBJtrLfHHyJIJ2",
                "_score": 0.19671029,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "GqBex3wBJtrLfHHyKYJN",
                "_score": 0.19671029,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "G6Bex3wBJtrLfHHyLILA",
                "_score": 0.19671029,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "HKBex3wBJtrLfHHyMYIB",
                "_score": 0.19671029,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "HaBex3wBJtrLfHHyNIIl",
                "_score": 0.19671029,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "HqBex3wBJtrLfHHyN4KX",
                "_score": 0.19671029,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "H6Bex3wBJtrLfHHyO4Lc",
                "_score": 0.19671029,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "IKBex3wBJtrLfHHyP4Jq",
                "_score": 0.19671029,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "1",
                "_score": 0.19671029,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 3999.00
                }
            }
        ]
    }
}

将小华分词为 小 、 华 、小华

{
    "query" : {
      "match" : {
          "category" : "小华"
      }
    }
}

响应结果

{
    "took": 16,
    "timed_out": false,
    "_shards": {
        "total": 1,
        "successful": 1,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 12,
            "relation": "eq"
        },
        "max_score": 1.7227666,
        "hits": [
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "1  ",
                "_score": 1.7227666,
                "_source": {
                    "title": "华为手机",
                    "category": "华为",
                    "images": "http://www.dongguo.com/hw.jpg",
                    "price": 4999.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "2",
                "_score": 1.7227666,
                "_source": {
                    "title": "华为手机",
                    "category": "华为",
                    "images": "http://www.dongguo.com/hw.jpg",
                    "price": 4000.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "GKBex3wBJtrLfHHyFoJt",
                "_score": 0.19671029,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "GaBex3wBJtrLfHHyJIJ2",
                "_score": 0.19671029,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "GqBex3wBJtrLfHHyKYJN",
                "_score": 0.19671029,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "G6Bex3wBJtrLfHHyLILA",
                "_score": 0.19671029,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "HKBex3wBJtrLfHHyMYIB",
                "_score": 0.19671029,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "HaBex3wBJtrLfHHyNIIl",
                "_score": 0.19671029,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "HqBex3wBJtrLfHHyN4KX",
                "_score": 0.19671029,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "H6Bex3wBJtrLfHHyO4Lc",
                "_score": 0.19671029,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            }
        ]
    }
}
完全匹配
{
    "query" : {
      "match_phrase" : {
          "category" : "小华"
      }
    }
}

响应结果

{
    "took": 398,
    "timed_out": false,
    "_shards": {
        "total": 1,
        "successful": 1,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 0,
            "relation": "eq"
        },
        "max_score": null,
        "hits": []
    }
}
高亮查询
{
    "query" : {
      "match_phrase" : {
          "category" : "小米"
      }
    },
    "highlight" : {
        "fields" : {
            "category" : {}
        }
    }
}

响应结果

{
    "took": 1060,
    "timed_out": false,
    "_shards": {
        "total": 1,
        "successful": 1,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 10,
            "relation": "eq"
        },
        "max_score": 0.39342058,
        "hits": [
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "GKBex3wBJtrLfHHyFoJt",
                "_score": 0.39342058,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                },
                "highlight": {
                    "category": [
                        "小米"
                    ]
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "GaBex3wBJtrLfHHyJIJ2",
                "_score": 0.39342058,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                },
                "highlight": {
                    "category": [
                        "小米"
                    ]
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "GqBex3wBJtrLfHHyKYJN",
                "_score": 0.39342058,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                },
                "highlight": {
                    "category": [
                        "小米"
                    ]
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "G6Bex3wBJtrLfHHyLILA",
                "_score": 0.39342058,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                },
                "highlight": {
                    "category": [
                        "小米"
                    ]
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "HKBex3wBJtrLfHHyMYIB",
                "_score": 0.39342058,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                },
                "highlight": {
                    "category": [
                        "小米"
                    ]
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "HaBex3wBJtrLfHHyNIIl",
                "_score": 0.39342058,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                },
                "highlight": {
                    "category": [
                        "小米"
                    ]
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "HqBex3wBJtrLfHHyN4KX",
                "_score": 0.39342058,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                },
                "highlight": {
                    "category": [
                        "小米"
                    ]
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "H6Bex3wBJtrLfHHyO4Lc",
                "_score": 0.39342058,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                },
                "highlight": {
                    "category": [
                        "小米"
                    ]
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "IKBex3wBJtrLfHHyP4Jq",
                "_score": 0.39342058,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                },
                "highlight": {
                    "category": [
                        "小米"
                    ]
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "1",
                "_score": 0.39342058,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 3999.00
                },
                "highlight": {
                    "category": [
                        "小米"
                    ]
                }
            }
        ]
    }
}
聚合查询

分组统计

{
    "aggs" : {//聚合操作
        "price_group" : {//名称,可随意
            "terms" : {//分组
                "field" : "price"//分组字段
            }
        }
    }
}

响应结果

{
    "took": 460,
    "timed_out": false,
    "_shards": {
        "total": 1,
        "successful": 1,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 12,
            "relation": "eq"
        },
        "max_score": 1.0,
        "hits": [
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "1  ",
                "_score": 1.0,
                "_source": {
                    "title": "华为手机",
                    "category": "华为",
                    "images": "http://www.dongguo.com/hw.jpg",
                    "price": 4999.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "2",
                "_score": 1.0,
                "_source": {
                    "title": "华为手机",
                    "category": "华为",
                    "images": "http://www.dongguo.com/hw.jpg",
                    "price": 4000.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "GKBex3wBJtrLfHHyFoJt",
                "_score": 1.0,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "GaBex3wBJtrLfHHyJIJ2",
                "_score": 1.0,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "GqBex3wBJtrLfHHyKYJN",
                "_score": 1.0,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "G6Bex3wBJtrLfHHyLILA",
                "_score": 1.0,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "HKBex3wBJtrLfHHyMYIB",
                "_score": 1.0,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "HaBex3wBJtrLfHHyNIIl",
                "_score": 1.0,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "HqBex3wBJtrLfHHyN4KX",
                "_score": 1.0,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            },
            {
                "_index": "shopping",
                "_type": "phone",
                "_id": "H6Bex3wBJtrLfHHyO4Lc",
                "_score": 1.0,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.dongguo.com/xm.jpg",
                    "price": 4000.00
                }
            }
        ]
    },
    "aggregations": {
        "price_group": {
            "doc_count_error_upper_bound": 0,
            "sum_other_doc_count": 0,
            "buckets": [
                {
                    "key": 4000.0,
                    "doc_count": 10
                },
                {
                    "key": 3999.0,
                    "doc_count": 1
                },
                {
                    "key": 4999.0,
                    "doc_count": 1
                }
            ]
        }
    }
}

对price相同价格做了统计

{
    "aggs" : {//聚合操作
        "price_group" : {//名称,可随意
            "terms" : {//分组
                "field" : "price"//分组字段
            }
        }
    },
    "size" : 0//表示不显示原始数据
}

响应结果

{
    "took": 137,
    "timed_out": false,
    "_shards": {
        "total": 1,
        "successful": 1,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 12,
            "relation": "eq"
        },
        "max_score": null,
        "hits": []
    },
    "aggregations": {
        "price_group": {
            "doc_count_error_upper_bound": 0,
            "sum_other_doc_count": 0,
            "buckets": [
                {
                    "key": 4000.0,
                    "doc_count": 10
                },
                {
                    "key": 3999.0,
                    "doc_count": 1
                },
                {
                    "key": 4999.0,
                    "doc_count": 1
                }
            ]
        }
    }
}

求平均值

{
    "aggs" : {//聚合操作
        "price_avg" : {//名称,可随意
            "avg" : {//平均值
                "field" : "price"//平均字段
            }
        }
    },
    "size" : 0//表示不显示原始数据
}

响应结果

{
    "took": 32,
    "timed_out": false,
    "_shards": {
        "total": 1,
        "successful": 1,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 12,
            "relation": "eq"
        },
        "max_score": null,
        "hits": []
    },
    "aggregations": {
        "price_avg": {
            "value": 4083.1666666666665
        }
    }
}
映射操作

有了索引库,等于有了数据库中的 database。

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

1) 创建映射

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

{
	"properties": {
		"name": {
			"type": "text",
			"index": true
		},
		"sex": {
			"type": "keyword",
			"index": true
		},
		"tel": {
			"type": "keyword",
			"index": false
		}
	}
}

创建索引

image-20211029071610189

没有索引无法直接创建映射

image-20211029072026314

服务器响应结果如下:

image-20211028213923795

映射数据说明:  字段名:任意填写,下面指定许多属性,例如: 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 分词器

2) 查看映射

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

image-20211029072211959

服务器响应结果如下:

{
    "user": {
        "mappings": {
            "properties": {
                "name": {
                    "type": "text"
                },
                "sex": {
                    "type": "keyword"
                },
                "tel": {
                    "type": "keyword",
                    "index": false
                }
            }
        }
    }
}

创建数据

put http://127.0.0.1:9200/user/_create/1001

{
	"name" : "张三",
    "sex" : "男生",
    "tel" : "123456789"
}

image-20211029072955789

响应结果

{
    "_index": "user",
    "_type": "_doc",
    "_id": "1001",
    "_version": 1,
    "result": "created",
    "_shards": {
        "total": 2,
        "successful": 1,
        "failed": 0
    },
    "_seq_no": 0,
    "_primary_term": 1
}

全文检索

http://127.0.0.1:9200/user/_search

{
	"query" : {
        "match" : {
            "name" : "张"
        }
    }
}

image-20211029073301126

响应结果

{
    "took": 2485,
    "timed_out": false,
    "_shards": {
        "total": 1,
        "successful": 1,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 1,
            "relation": "eq"
        },
        "max_score": 0.2876821,
        "hits": [
            {
                "_index": "user",
                "_type": "_doc",
                "_id": "1001",
                "_score": 0.2876821,
                "_source": {
                    "name": "张三",
                    "sex": "男生",
                    "tel": "123456789"
                }
            }
        ]
    }
}

name的映射是index 可分词

image-20211029073522319

响应结果

{
    "took": 24,
    "timed_out": false,
    "_shards": {
        "total": 1,
        "successful": 1,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 0,
            "relation": "eq"
        },
        "max_score": null,
        "hits": []
    }
}

sex的映射是keyword,不可分词

image-20211029073627003

响应结果

{
    "took": 15,
    "timed_out": false,
    "_shards": {
        "total": 1,
        "successful": 1,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 1,
            "relation": "eq"
        },
        "max_score": 0.2876821,
        "hits": [
            {
                "_index": "user",
                "_type": "_doc",
                "_id": "1001",
                "_score": 0.2876821,
                "_source": {
                    "name": "张三",
                    "sex": "男生",
                    "tel": "123456789"
                }
            }
        ]
    }
}

tel的映射type是keyword 不能分词 ,index是false表示无法被查询

image-20211029073906931

响应结果

{
    "error": {
        "root_cause": [
            {
                "type": "query_shard_exception",
                "reason": "failed to create query: Cannot search on field [tel] since it is not indexed.",
                "index_uuid": "mWuXvUjUQ3asIfcYmmMB_w",
                "index": "user"
            }
        ],
        "type": "search_phase_execution_exception",
        "reason": "all shards failed",
        "phase": "query",
        "grouped": true,
        "failed_shards": [
            {
                "shard": 0,
                "index": "user",
                "node": "Yemd-7jpQSOJ5cbvq0uuYg",
                "reason": {
                    "type": "query_shard_exception",
                    "reason": "failed to create query: Cannot search on field [tel] since it is not indexed.",
                    "index_uuid": "mWuXvUjUQ3asIfcYmmMB_w",
                    "index": "user",
                    "caused_by": {
                        "type": "illegal_argument_exception",
                        "reason": "Cannot search on field [tel] since it is not indexed."
                    }
                }
            }
        ]
    },
    "status": 400
}
Java API 操作

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

创建 Maven 项目

我们在 IDEA 开发工具中创建 Maven 项目(模块也可)ES

image-20211029074707556

修改 pom 文件,增加 Maven 依赖关系


    
        org.elasticsearch
        elasticsearch
        7.8.0
    
    
    
        org.elasticsearch.client
        elasticsearch-rest-high-level-client
        7.8.0
    
    
    
        org.apache.logging.log4j
        log4j-api
        2.8.2
    
    
        org.apache.logging.log4j
        log4j-core
        2.8.2
    
    
        com.fasterxml.jackson.core
        jackson-databind
        2.9.9
    
    
    
        junit
        junit
        4.12
    
     
         org.projectlombok
         lombok
     

创建日志类

客户端对象

创建 com.es.elasticSearch.Elasticsearch01类,代码中创建 Elasticsearch 客户端对象 因为早期版本的客户端对象已经不再推荐使用,且在未来版本中会被删除,所以这里我们采 用高级 REST 客户端对象

    public static void main(String[] args) throws IOException {
        // 创建客户端对象
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http"))
        );

        // 关闭客户端连接
        client.close();
    }

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

image-20211029194638865

索引操作

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

1) 创建索引
package com.es.elasticSearch;

import com.es.esjest.esservice.EsService;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * @author Dongguo
 * @date 2021/10/29 0029-19:29
 * @description:
 */
public class Elasticsearch02 {
    private final static Logger logger = LoggerFactory.getLogger(EsService.class);

    public static void main(String[] args) throws IOException {
        // 创建客户端对象
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http"))
        );
        // 创建索引 - 请求对象
        CreateIndexRequest request = new CreateIndexRequest("user001");
        // 发送请求,获取响应
        CreateIndexResponse response = client.indices().create(request,
                RequestOptions.DEFAULT);
        boolean acknowledged = response.isAcknowledged();
        // 响应状态
        logger.info("result:"+acknowledged);
        // 关闭客户端连接
        client.close();
    }
}

操作结果:

image-20211029204748959

2) 查看索引
package com.es.elasticSearch;

import com.es.esjest.esservice.EsService;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.client.indices.GetIndexResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * @author Dongguo
 * @date 2021/10/29 0029-19:29
 * @description:
 */
public class Elasticsearch03 {
    private final static Logger logger = LoggerFactory.getLogger(EsService.class);

    public static void main(String[] args) throws IOException {
        // 创建客户端对象
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http"))
        );
        // 查询索引 - 请求对象
        GetIndexRequest request = new GetIndexRequest("user001");
        // 发送请求,获取响应
        GetIndexResponse response = client.indices().get(request,
                RequestOptions.DEFAULT);
        logger.info("aliases:"+response.getAliases());
        logger.info("mappings:"+response.getMappings());
        logger.info("settings:"+response.getSettings());
        // 关闭客户端连接
        client.close();
    }
}

操作结果:

image-20211029205834696

3) 删除索引
package com.es.elasticSearch;

import com.es.esjest.esservice.EsService;
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.client.indices.GetIndexResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * @author Dongguo
 * @date 2021/10/29 0029-19:29
 * @description:
 */
public class Elasticsearch04 {
    private final static Logger logger = LoggerFactory.getLogger(EsService.class);

    public static void main(String[] args) throws IOException {
        // 创建客户端对象
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http"))
        );
        // 删除索引 - 请求对象
        DeleteIndexRequest request = new DeleteIndexRequest("user001");
        // 发送请求,获取响应
        AcknowledgedResponse response = client.indices().delete(request,
                RequestOptions.DEFAULT);
        // 操作结果
        logger.info("操作结果 : " + response.isAcknowledged());
        // 关闭客户端连接
        client.close();
    }
}

操作结果:

image-20211029205954536

文档操作 1) 新增文档
package com.es.elasticSearch;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

/**
 * @author Dongguo
 * @date 2021/10/29 0029-21:02
 * @description:
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class User {
    private String name;
    private Integer age;
    private String sex;
}

创建数据,添加到文档中

package com.es.elasticSearch;

import com.es.esjest.esservice.EsService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * @author Dongguo
 * @date 2021/10/29 0029-19:29
 * @description:
 */
public class Elasticsearch05 {
    private final static Logger logger = LoggerFactory.getLogger(EsService.class);

    public static void main(String[] args) throws IOException {
        // 创建客户端对象
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http"))
        );
        // 新增文档 - 请求对象
        IndexRequest request = new IndexRequest();
        // 设置索引及唯一性标识
        request.index("user").id("1001");
        // 创建数据对象
        User user = new User();
        user.setName("zhangsan");
        user.setAge(18);
        user.setSex("男");
        ObjectMapper objectMapper = new ObjectMapper();
        String productJson = objectMapper.writeValueAsString(user);
        // 添加文档数据,数据格式为 JSON 格式
        request.source(productJson, XContentType.JSON);
        // 客户端发送请求,获取响应对象
        IndexResponse response = client.index(request, RequestOptions.DEFAULT);
        //3.打印结果信息
        logger.info("_index:" + response.getIndex());
        logger.info("_id:" + response.getId());
        logger.info("_result:" + response.getResult());
        // 关闭客户端连接
        client.close();
    }
}

操作结果:

image-20211029210656263

2) 修改文档
package com.es.elasticSearch;

import com.es.esjest.esservice.EsService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * @author Dongguo
 * @date 2021/10/29 0029-19:29
 * @description:
 */
public class Elasticsearch06 {
    private final static Logger logger = LoggerFactory.getLogger(EsService.class);

    public static void main(String[] args) throws IOException {
        // 创建客户端对象
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http"))
        );
        // 修改文档 - 请求对象
        UpdateRequest request = new UpdateRequest();
        // 配置修改参数
        request.index("user").id("1001");
        // 设置请求体,对数据进行修改
        request.doc(XContentType.JSON, "sex", "女");
        // 客户端发送请求,获取响应对象
        UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
        logger.info("_index:" + response.getIndex());
        logger.info("_id:" + response.getId());
        logger.info("_result:" + response.getResult());
        // 关闭客户端连接
        client.close();
    }
}

执行结果:

image-20211029211119628

3) 查询文档
package com.es.elasticSearch;

import com.es.esjest.esservice.EsService;
import org.apache.http.HttpHost;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * @author Dongguo
 * @date 2021/10/29 0029-19:29
 * @description:
 */
public class Elasticsearch07 {
    private final static Logger logger = LoggerFactory.getLogger(EsService.class);

    public static void main(String[] args) throws IOException {
        // 创建客户端对象
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http"))
        );
        //1.创建请求对象
        GetRequest request = new GetRequest().index("user").id("1001");
        //2.客户端发送请求,获取响应对象
        GetResponse response = client.get(request, RequestOptions.DEFAULT);
        //3.打印结果信息
        logger.info("_index:" + response.getIndex());
        logger.info("_type:" + response.getType());
        logger.info("_id:" + response.getId());
        logger.info("source:" + response.getSourceAsString());
        // 关闭客户端连接
        client.close();
    }
}

执行结果为:

image-20211029211351438

4) 删除文档
package com.es.elasticSearch;

import com.es.esjest.esservice.EsService;
import org.apache.http.HttpHost;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * @author Dongguo
 * @date 2021/10/29 0029-19:29
 * @description:
 */
public class Elasticsearch08 {
    private final static Logger logger = LoggerFactory.getLogger(EsService.class);

    public static void main(String[] args) throws IOException {
        // 创建客户端对象
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http"))
        );
        //创建请求对象
        DeleteRequest request = new DeleteRequest().index("user").id("1001");
        //客户端发送请求,获取响应对象
        DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);
        //打印信息
        logger.info(response.toString());
        // 关闭客户端连接
        client.close();
    }
}

执行结果为:

image-20211029211739339

5) 批量操作

 批量新增:

package com.es.elasticSearch;

import com.es.esjest.esservice.EsService;
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * @author Dongguo
 * @date 2021/10/29 0029-19:29
 * @description:
 */
public class Elasticsearch09 {
    private final static Logger logger = LoggerFactory.getLogger(EsService.class);

    public static void main(String[] args) throws IOException {
        // 创建客户端对象
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http"))
        );
        //创建批量新增请求对象
        BulkRequest request = new BulkRequest();
        request.add(new
                IndexRequest().index("user").id("1001").source(XContentType.JSON, "name",
                "zhangsan"));
        request.add(new
        IndexRequest().index("user").id("1002").source(XContentType.JSON, "name",
                "lisi"));
        request.add(new
                IndexRequest().index("user").id("1003").source(XContentType.JSON, "name",
                "wangwu"));
        //客户端发送请求,获取响应对象
        BulkResponse responses = client.bulk(request, RequestOptions.DEFAULT);
        //打印结果信息
        logger.info("took:" + responses.getTook());
        logger.info("items:" + responses.getItems());
        // 关闭客户端连接
        client.close();
    }
}

执行结果为:

image-20211029212250104

 批量删除:

package com.es.elasticSearch;

import com.es.esjest.esservice.EsService;
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * @author Dongguo
 * @date 2021/10/29 0029-19:29
 * @description:
 */
public class Elasticsearch10 {
    private final static Logger logger = LoggerFactory.getLogger(EsService.class);

    public static void main(String[] args) throws IOException {
        // 创建客户端对象
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http"))
        );
        //创建批量删除请求对象
        BulkRequest request = new BulkRequest();
        request.add(new DeleteRequest().index("user").id("1001"));
        request.add(new DeleteRequest().index("user").id("1002"));
        request.add(new DeleteRequest().index("user").id("1003"));
        //客户端发送请求,获取响应对象
        BulkResponse responses = client.bulk(request, RequestOptions.DEFAULT);
        //打印结果信息
        logger.info("took:" + responses.getTook());
        logger.info("items:" + responses.getItems());

        // 关闭客户端连接
        client.close();
    }
}

执行结果为:

image-20211029212753850

高级查询 1) 请求体查询

批量插入数据,使用请求体进行查询

package com.es.elasticSearch;

import com.es.esjest.esservice.EsService;
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * @author Dongguo
 * @date 2021/10/29 0029-19:29
 * @description:
 */
public class Elasticsearch09 {
    private final static Logger logger = LoggerFactory.getLogger(EsService.class);

    public static void main(String[] args) throws IOException {
        // 创建客户端对象
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http"))
        );
        //创建批量新增请求对象
        BulkRequest request = new BulkRequest();
        request.add(new IndexRequest().index("user").id("1001").source(XContentType.JSON, "name", "zhangsan","age",18,"sex","男"));
        request.add(new IndexRequest().index("user").id("1002").source(XContentType.JSON, "name", "lisi","age",20,"sex","女"));
        request.add(new IndexRequest().index("user").id("1003").source(XContentType.JSON, "name", "wangwu","age",40,"sex","男"));
        request.add(new IndexRequest().index("user").id("1004").source(XContentType.JSON, "name", "zhaoliu","age",22,"sex","女"));
        request.add(new IndexRequest().index("user").id("1005").source(XContentType.JSON, "name", "tianqi","age",22,"sex","男"));
        //客户端发送请求,获取响应对象
        BulkResponse responses = client.bulk(request, RequestOptions.DEFAULT);
        //打印结果信息
        logger.info("took:" + responses.getTook());
        logger.info("items:" + responses.getItems());
        // 关闭客户端连接
        client.close();
    }
}

 查询所有索引数据

package com.es.elasticSearch;

import com.es.esjest.esservice.EsService;
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * @author Dongguo
 * @date 2021/10/29 0029-19:29
 * @description:
 */
public class Elasticsearch11 {
    private final static Logger logger = LoggerFactory.getLogger(EsService.class);

    public static void main(String[] args) throws IOException {
        // 创建客户端对象
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http"))
        );
        // 创建搜索请求对象
        SearchRequest request = new SearchRequest();
        request.indices("user");
        // 构建查询的请求体
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        // 查询所有数据
        sourceBuilder.query(QueryBuilders.matchAllQuery());
        request.source(sourceBuilder);
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        // 查询匹配
        SearchHits hits = response.getHits();
        logger.info("took:" + response.getTook());
        logger.info("timeout:" + response.isTimedOut());
        logger.info("total:" + hits.getTotalHits());
        logger.info("MaxScore:" + hits.getMaxScore());
        logger.info("hits start========>>");
        for (SearchHit hit : hits) {
            //输出每条查询的结果信息
            logger.info(hit.getSourceAsString());
        }
        logger.info("            
关注
打赏
1638062488
查看更多评论
0.0912s