参考博客 参考视频 官方网址 官方文档 Elasticsearch 7.8.0下载页面

Windows 版的 Elasticsearch 压缩包,解压即安装完毕,解压后的 Elasticsearch 的目录结构如下 :
目录 含义

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

注意: 9300 端口为 Elasticsearch 集群间组件的通信端口, 9200 端口为浏览器访问的 http协议 RESTful 端口。
打开浏览器,输入地址: http://localhost:9200,测试返回结果,返回结果如下:

  1. {
  2. "name" : "DESKTOP-LNJQ0VF",
  3. "cluster_name" : "elasticsearch",
  4. "cluster_uuid" : "nCZqBhfdT1-pw8Yas4QU9w",
  5. "version" : {
  6. "number" : "7.8.0",
  7. "build_flavor" : "default",
  8. "build_type" : "zip",
  9. "build_hash" : "757314695644ea9a1dc2fecd26d1a43856725e65",
  10. "build_date" : "2020-06-14T19:35:50.234439Z",
  11. "build_snapshot" : false,
  12. "lucene_version" : "8.5.1",
  13. "minimum_wire_compatibility_version" : "6.8.0",
  14. "minimum_index_compatibility_version" : "6.0.0-beta1"
  15. },
  16. "tagline" : "You Know, for Search"
  17. }

入门-倒排索引
正排索引(传统)

id content
1001 my name is zhang san
1002 my name is li si

倒排索引

keyword id
name 1001, 1002
zhang 1001

Elasticsearch 是面向文档型数据库,一条数据在这里就是一个文档。 为了方便大家理解,我们将 Elasticsearch 里存储文档数据和关系型数据库 MySQL 存储数据的概念进行一个类比
elastic search 入门 - 图1
ES 里的 Index 可以看做一个库,而 Types 相当于表, Documents 则相当于表的行。这里 Types 的概念已经被逐渐弱化, Elasticsearch 6.X 中,一个 index 下已经只能包含一个type, Elasticsearch 7.X 中, Type 的概念已经被删除了。

入门-HTTP

入门-HTTP-索引-创建

对比关系型数据库,创建索引就等同于创建数据库。
在 Postman 中,向 ES 服务器发 PUT 请求 : http://127.0.0.1:9200/shopping
请求后,服务器返回响应:

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

如果重复发 PUT 请求 : http://127.0.0.1:9200/shopping 添加索引,会返回错误信息 :

  1. {
  2. "error": {
  3. "root_cause": [
  4. {
  5. "type": "resource_already_exists_exception",
  6. "reason": "index [shopping/J0WlEhh4R7aDrfIc3AkwWQ] already exists",
  7. "index_uuid": "J0WlEhh4R7aDrfIc3AkwWQ",
  8. "index": "shopping"
  9. }
  10. ],
  11. "type": "resource_already_exists_exception",
  12. "reason": "index [shopping/J0WlEhh4R7aDrfIc3AkwWQ] already exists",
  13. "index_uuid": "J0WlEhh4R7aDrfIc3AkwWQ",
  14. "index": "shopping"
  15. },
  16. "status": 400
  17. }

入门-HTTP-索引-查询 & 删除

查看所有索引
在 Postman 中,向 ES 服务器发 GET 请求 : http://127.0.0.1:9200/_cat/indices?v

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

  1. health status index uuid pri rep docs.count docs.deleted store.size pri.store.size
  2. yellow open shopping J0WlEhh4R7aDrfIc3AkwWQ 1 1 0 0 208b 208b

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

查看单个索引

在 Postman 中,向 ES 服务器发 GET 请求 : http://127.0.0.1:9200/shopping
返回结果如下:

  1. {
  2. "shopping": {//索引名
  3. "aliases": {},//别名
  4. "mappings": {},//映射
  5. "settings": {//设置
  6. "index": {//设置 - 索引
  7. "creation_date": "1617861426847",//设置 - 索引 - 创建时间
  8. "number_of_shards": "1",//设置 - 索引 - 主分片数量
  9. "number_of_replicas": "1",//设置 - 索引 - 主分片数量
  10. "uuid": "J0WlEhh4R7aDrfIc3AkwWQ",//设置 - 索引 - 主分片数量
  11. "version": {//设置 - 索引 - 主分片数量
  12. "created": "7080099"
  13. },
  14. "provided_name": "shopping"//设置 - 索引 - 主分片数量
  15. }
  16. }
  17. }
  18. }

删除索引

在 Postman 中,向 ES 服务器发 DELETE 请求 : http://127.0.0.1:9200/shopping
返回结果如下:

  1. {
  2. "acknowledged": true
  3. }

再次查看所有索引,GET http://127.0.0.1:9200/_cat/indices?v,返回结果如下:

  1. health status index uuid pri rep docs.count docs.deleted store.size pri.store.size

入门-HTTP-文档-创建(Put & Post)

假设索引已经创建好了,接下来我们来创建文档,并添加数据。这里的文档可以类比为关系型数据库中的表数据,添加的数据格式为 JSON 格式

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

elastic search 入门 - 图2
注意,此处发送请求的方式必须为 POST,不能是 PUT,否则会发生错误 。

  1. {
  2. "_index": "shopping",//索引
  3. "_type": "_doc",//类型-文档
  4. "_id": "ANQqsHgBaKNfVnMbhZYU",//唯一标识,可以类比为 MySQL 中的主键,随机生成
  5. "_version": 1,//版本
  6. "result": "created",//结果,这里的 create 表示创建成功
  7. "_shards": {//
  8. "total": 2,//分片 - 总数
  9. "successful": 1,//分片 - 总数
  10. "failed": 0//分片 - 总数
  11. },
  12. "_seq_no": 0,
  13. "_primary_term": 1
  14. }

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

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

返回结果如下:

  1. {
  2. "_index": "shopping",
  3. "_type": "_doc",
  4. "_id": "1",//<------------------自定义唯一性标识
  5. "_version": 1,
  6. "result": "created",
  7. "_shards": {
  8. "total": 2,
  9. "successful": 1,
  10. "failed": 0
  11. },
  12. "_seq_no": 1,
  13. "_primary_term": 1
  14. }

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

入门-HTTP-查询-主键查询 & 全查询

查看文档时,需要指明文档的唯一性标识,类似于 MySQL 中数据的主键查询

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

  1. {
  2. "_index": "shopping",
  3. "_type": "_doc",
  4. "_id": "1",
  5. "_version": 1,
  6. "_seq_no": 1,
  7. "_primary_term": 1,
  8. "found": true,
  9. "_source": {
  10. "title": "小米手机",
  11. "category": "小米",
  12. "images": "http://www.gulixueyuan.com/xm.jpg",
  13. "price": 3999
  14. }
  15. }

查找不存在的内容,向 ES 服务器发 GET 请求 : http://127.0.0.1:9200/shopping/_doc/1001。

  1. {
  2. "_index": "shopping",
  3. "_type": "_doc",
  4. "_id": "1001",
  5. "found": false
  6. }

查看索引下所有数据,向 ES 服务器发 GET 请求 : http://127.0.0.1:9200/shopping/_search。

  1. {
  2. "took": 133,
  3. "timed_out": false,
  4. "_shards": {
  5. "total": 1,
  6. "successful": 1,
  7. "skipped": 0,
  8. "failed": 0
  9. },
  10. "hits": {
  11. "total": {
  12. "value": 2,
  13. "relation": "eq"
  14. },
  15. "max_score": 1,
  16. "hits": [
  17. {
  18. "_index": "shopping",
  19. "_type": "_doc",
  20. "_id": "ANQqsHgBaKNfVnMbhZYU",
  21. "_score": 1,
  22. "_source": {
  23. "title": "小米手机",
  24. "category": "小米",
  25. "images": "http://www.gulixueyuan.com/xm.jpg",
  26. "price": 3999
  27. }
  28. },
  29. {
  30. "_index": "shopping",
  31. "_type": "_doc",
  32. "_id": "1",
  33. "_score": 1,
  34. "_source": {
  35. "title": "小米手机",
  36. "category": "小米",
  37. "images": "http://www.gulixueyuan.com/xm.jpg",
  38. "price": 3999
  39. }
  40. }
  41. ]
  42. }
  43. }

入门-HTTP-全量修改 & 局部修改 & 删除

全量修改

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

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

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

  1. {
  2. "_index": "shopping",
  3. "_type": "_doc",
  4. "_id": "1",
  5. "_version": 2,
  6. "result": "updated",//<-----------updated 表示数据被更新
  7. "_shards": {
  8. "total": 2,
  9. "successful": 1,
  10. "failed": 0
  11. },
  12. "_seq_no": 2,
  13. "_primary_term": 1
  14. }

局部修改

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

  1. {
  2. "doc": {
  3. "title":"小米手机",
  4. "category":"小米"
  5. }
  6. }

返回结果如下:

  1. {
  2. "_index": "shopping",
  3. "_type": "_doc",
  4. "_id": "1",
  5. "_version": 3,
  6. "result": "updated",//<-----------updated 表示数据被更新
  7. "_shards": {
  8. "total": 2,
  9. "successful": 1,
  10. "failed": 0
  11. },
  12. "_seq_no": 3,
  13. "_primary_term": 1
  14. }

在 Postman 中,向 ES 服务器发 GET请求 : http://127.0.0.1:9200/shopping/_doc/1,查看修改内容:

  1. {
  2. "_index": "shopping",
  3. "_type": "_doc",
  4. "_id": "1",
  5. "_version": 3,
  6. "_seq_no": 3,
  7. "_primary_term": 1,
  8. "found": true,
  9. "_source": {
  10. "title": "小米手机",
  11. "category": "小米",
  12. "images": "http://www.gulixueyuan.com/hw.jpg",
  13. "price": 1999
  14. }
  15. }

删除

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

  1. {
  2. "_index": "shopping",
  3. "_type": "_doc",
  4. "_id": "1",
  5. "_version": 4,
  6. "result": "deleted",//<---删除成功
  7. "_shards": {
  8. "total": 2,
  9. "successful": 1,
  10. "failed": 0
  11. },
  12. "_seq_no": 4,
  13. "_primary_term": 1
  14. }

在 Postman 中,向 ES 服务器发 GET请求 : http://127.0.0.1:9200/shopping/_doc/1,查看是否删除成功:

  1. {
  2. "_index": "shopping",
  3. "_type": "_doc",
  4. "_id": "1",
  5. "found": false
  6. }

入门-HTTP-条件查询 & 分页查询 & 查询排序

条件查询

假设有以下文档内容,(在 Postman 中,向 ES 服务器发 GET请求 : http://127.0.0.1:9200/shopping/_search):

  1. {
  2. "took": 5,
  3. "timed_out": false,
  4. "_shards": {
  5. "total": 1,
  6. "successful": 1,
  7. "skipped": 0,
  8. "failed": 0
  9. },
  10. "hits": {
  11. "total": {
  12. "value": 6,
  13. "relation": "eq"
  14. },
  15. "max_score": 1,
  16. "hits": [
  17. {
  18. "_index": "shopping",
  19. "_type": "_doc",
  20. "_id": "ANQqsHgBaKNfVnMbhZYU",
  21. "_score": 1,
  22. "_source": {
  23. "title": "小米手机",
  24. "category": "小米",
  25. "images": "http://www.gulixueyuan.com/xm.jpg",
  26. "price": 3999
  27. }
  28. },
  29. {
  30. "_index": "shopping",
  31. "_type": "_doc",
  32. "_id": "A9R5sHgBaKNfVnMb25Ya",
  33. "_score": 1,
  34. "_source": {
  35. "title": "小米手机",
  36. "category": "小米",
  37. "images": "http://www.gulixueyuan.com/xm.jpg",
  38. "price": 1999
  39. }
  40. },
  41. {
  42. "_index": "shopping",
  43. "_type": "_doc",
  44. "_id": "BNR5sHgBaKNfVnMb7pal",
  45. "_score": 1,
  46. "_source": {
  47. "title": "小米手机",
  48. "category": "小米",
  49. "images": "http://www.gulixueyuan.com/xm.jpg",
  50. "price": 1999
  51. }
  52. },
  53. {
  54. "_index": "shopping",
  55. "_type": "_doc",
  56. "_id": "BtR6sHgBaKNfVnMbX5Y5",
  57. "_score": 1,
  58. "_source": {
  59. "title": "华为手机",
  60. "category": "华为",
  61. "images": "http://www.gulixueyuan.com/xm.jpg",
  62. "price": 1999
  63. }
  64. },
  65. {
  66. "_index": "shopping",
  67. "_type": "_doc",
  68. "_id": "B9R6sHgBaKNfVnMbZpZ6",
  69. "_score": 1,
  70. "_source": {
  71. "title": "华为手机",
  72. "category": "华为",
  73. "images": "http://www.gulixueyuan.com/xm.jpg",
  74. "price": 1999
  75. }
  76. },
  77. {
  78. "_index": "shopping",
  79. "_type": "_doc",
  80. "_id": "CdR7sHgBaKNfVnMbsJb9",
  81. "_score": 1,
  82. "_source": {
  83. "title": "华为手机",
  84. "category": "华为",
  85. "images": "http://www.gulixueyuan.com/xm.jpg",
  86. "price": 1999
  87. }
  88. }
  89. ]
  90. }
  91. }

URL带参查询

查找category为小米的文档,在 Postman 中,向 ES 服务器发 GET请求 : http://127.0.0.1:9200/shopping/_search?q=category:小米,返回结果如下:

  1. {
  2. "took": 94,
  3. "timed_out": false,
  4. "_shards": {
  5. "total": 1,
  6. "successful": 1,
  7. "skipped": 0,
  8. "failed": 0
  9. },
  10. "hits": {
  11. "total": {
  12. "value": 3,
  13. "relation": "eq"
  14. },
  15. "max_score": 1.3862942,
  16. "hits": [
  17. {
  18. "_index": "shopping",
  19. "_type": "_doc",
  20. "_id": "ANQqsHgBaKNfVnMbhZYU",
  21. "_score": 1.3862942,
  22. "_source": {
  23. "title": "小米手机",
  24. "category": "小米",
  25. "images": "http://www.gulixueyuan.com/xm.jpg",
  26. "price": 3999
  27. }
  28. },
  29. {
  30. "_index": "shopping",
  31. "_type": "_doc",
  32. "_id": "A9R5sHgBaKNfVnMb25Ya",
  33. "_score": 1.3862942,
  34. "_source": {
  35. "title": "小米手机",
  36. "category": "小米",
  37. "images": "http://www.gulixueyuan.com/xm.jpg",
  38. "price": 1999
  39. }
  40. },
  41. {
  42. "_index": "shopping",
  43. "_type": "_doc",
  44. "_id": "BNR5sHgBaKNfVnMb7pal",
  45. "_score": 1.3862942,
  46. "_source": {
  47. "title": "小米手机",
  48. "category": "小米",
  49. "images": "http://www.gulixueyuan.com/xm.jpg",
  50. "price": 1999
  51. }
  52. }
  53. ]
  54. }
  55. }

上述为URL带参数形式查询,这很容易让不善者心怀恶意,或者参数值出现中文会出现乱码情况。为了避免这些情况,我们可用使用带JSON请求体请求进行查询。

请求体带参查询

接下带JSON请求体,还是查找category为小米的文档,在 Postman 中,向 ES 服务器发 GET请求 : http://127.0.0.1:9200/shopping/_search,附带JSON体如下:

  1. {
  2. "query":{
  3. "match":{
  4. "category":"小米"
  5. }
  6. }
  7. }

返回结果如下:

  1. {
  2. "took": 3,
  3. "timed_out": false,
  4. "_shards": {
  5. "total": 1,
  6. "successful": 1,
  7. "skipped": 0,
  8. "failed": 0
  9. },
  10. "hits": {
  11. "total": {
  12. "value": 3,
  13. "relation": "eq"
  14. },
  15. "max_score": 1.3862942,
  16. "hits": [
  17. {
  18. "_index": "shopping",
  19. "_type": "_doc",
  20. "_id": "ANQqsHgBaKNfVnMbhZYU",
  21. "_score": 1.3862942,
  22. "_source": {
  23. "title": "小米手机",
  24. "category": "小米",
  25. "images": "http://www.gulixueyuan.com/xm.jpg",
  26. "price": 3999
  27. }
  28. },
  29. {
  30. "_index": "shopping",
  31. "_type": "_doc",
  32. "_id": "A9R5sHgBaKNfVnMb25Ya",
  33. "_score": 1.3862942,
  34. "_source": {
  35. "title": "小米手机",
  36. "category": "小米",
  37. "images": "http://www.gulixueyuan.com/xm.jpg",
  38. "price": 1999
  39. }
  40. },
  41. {
  42. "_index": "shopping",
  43. "_type": "_doc",
  44. "_id": "BNR5sHgBaKNfVnMb7pal",
  45. "_score": 1.3862942,
  46. "_source": {
  47. "title": "小米手机",
  48. "category": "小米",
  49. "images": "http://www.gulixueyuan.com/xm.jpg",
  50. "price": 1999
  51. }
  52. }
  53. ]
  54. }
  55. }

带请求体方式的查找所有内容

查找所有文档内容,也可以这样,在 Postman 中,向 ES 服务器发 GET请求 : http://127.0.0.1:9200/shopping/_search,附带JSON体如下:

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

则返回所有文档内容:

  1. {
  2. "took": 2,
  3. "timed_out": false,
  4. "_shards": {
  5. "total": 1,
  6. "successful": 1,
  7. "skipped": 0,
  8. "failed": 0
  9. },
  10. "hits": {
  11. "total": {
  12. "value": 6,
  13. "relation": "eq"
  14. },
  15. "max_score": 1,
  16. "hits": [
  17. {
  18. "_index": "shopping",
  19. "_type": "_doc",
  20. "_id": "ANQqsHgBaKNfVnMbhZYU",
  21. "_score": 1,
  22. "_source": {
  23. "title": "小米手机",
  24. "category": "小米",
  25. "images": "http://www.gulixueyuan.com/xm.jpg",
  26. "price": 3999
  27. }
  28. },
  29. {
  30. "_index": "shopping",
  31. "_type": "_doc",
  32. "_id": "A9R5sHgBaKNfVnMb25Ya",
  33. "_score": 1,
  34. "_source": {
  35. "title": "小米手机",
  36. "category": "小米",
  37. "images": "http://www.gulixueyuan.com/xm.jpg",
  38. "price": 1999
  39. }
  40. },
  41. {
  42. "_index": "shopping",
  43. "_type": "_doc",
  44. "_id": "BNR5sHgBaKNfVnMb7pal",
  45. "_score": 1,
  46. "_source": {
  47. "title": "小米手机",
  48. "category": "小米",
  49. "images": "http://www.gulixueyuan.com/xm.jpg",
  50. "price": 1999
  51. }
  52. },
  53. {
  54. "_index": "shopping",
  55. "_type": "_doc",
  56. "_id": "BtR6sHgBaKNfVnMbX5Y5",
  57. "_score": 1,
  58. "_source": {
  59. "title": "华为手机",
  60. "category": "华为",
  61. "images": "http://www.gulixueyuan.com/xm.jpg",
  62. "price": 1999
  63. }
  64. },
  65. {
  66. "_index": "shopping",
  67. "_type": "_doc",
  68. "_id": "B9R6sHgBaKNfVnMbZpZ6",
  69. "_score": 1,
  70. "_source": {
  71. "title": "华为手机",
  72. "category": "华为",
  73. "images": "http://www.gulixueyuan.com/xm.jpg",
  74. "price": 1999
  75. }
  76. },
  77. {
  78. "_index": "shopping",
  79. "_type": "_doc",
  80. "_id": "CdR7sHgBaKNfVnMbsJb9",
  81. "_score": 1,
  82. "_source": {
  83. "title": "华为手机",
  84. "category": "华为",
  85. "images": "http://www.gulixueyuan.com/xm.jpg",
  86. "price": 1999
  87. }
  88. }
  89. ]
  90. }
  91. }

查询指定字段

如果你想查询指定字段,在 Postman 中,向 ES 服务器发 GET请求 : http://127.0.0.1:9200/shopping/_search,附带JSON体如下:

  1. {
  2. "query":{
  3. "match_all":{}
  4. },
  5. "_source":["title"]
  6. }

返回结果如下:

  1. {
  2. "took": 5,
  3. "timed_out": false,
  4. "_shards": {
  5. "total": 1,
  6. "successful": 1,
  7. "skipped": 0,
  8. "failed": 0
  9. },
  10. "hits": {
  11. "total": {
  12. "value": 6,
  13. "relation": "eq"
  14. },
  15. "max_score": 1,
  16. "hits": [
  17. {
  18. "_index": "shopping",
  19. "_type": "_doc",
  20. "_id": "ANQqsHgBaKNfVnMbhZYU",
  21. "_score": 1,
  22. "_source": {
  23. "title": "小米手机"
  24. }
  25. },
  26. {
  27. "_index": "shopping",
  28. "_type": "_doc",
  29. "_id": "A9R5sHgBaKNfVnMb25Ya",
  30. "_score": 1,
  31. "_source": {
  32. "title": "小米手机"
  33. }
  34. },
  35. {
  36. "_index": "shopping",
  37. "_type": "_doc",
  38. "_id": "BNR5sHgBaKNfVnMb7pal",
  39. "_score": 1,
  40. "_source": {
  41. "title": "小米手机"
  42. }
  43. },
  44. {
  45. "_index": "shopping",
  46. "_type": "_doc",
  47. "_id": "BtR6sHgBaKNfVnMbX5Y5",
  48. "_score": 1,
  49. "_source": {
  50. "title": "华为手机"
  51. }
  52. },
  53. {
  54. "_index": "shopping",
  55. "_type": "_doc",
  56. "_id": "B9R6sHgBaKNfVnMbZpZ6",
  57. "_score": 1,
  58. "_source": {
  59. "title": "华为手机"
  60. }
  61. },
  62. {
  63. "_index": "shopping",
  64. "_type": "_doc",
  65. "_id": "CdR7sHgBaKNfVnMbsJb9",
  66. "_score": 1,
  67. "_source": {
  68. "title": "华为手机"
  69. }
  70. }
  71. ]
  72. }
  73. }

分页查询

在 Postman 中,向 ES 服务器发 GET请求 : http://127.0.0.1:9200/shopping/_search,附带JSON体如下:

  1. {
  2. "query":{
  3. "match_all":{}
  4. },
  5. "from":0,
  6. "size":2
  7. }

返回结果如下:

  1. {
  2. "took": 1,
  3. "timed_out": false,
  4. "_shards": {
  5. "total": 1,
  6. "successful": 1,
  7. "skipped": 0,
  8. "failed": 0
  9. },
  10. "hits": {
  11. "total": {
  12. "value": 6,
  13. "relation": "eq"
  14. },
  15. "max_score": 1,
  16. "hits": [
  17. {
  18. "_index": "shopping",
  19. "_type": "_doc",
  20. "_id": "ANQqsHgBaKNfVnMbhZYU",
  21. "_score": 1,
  22. "_source": {
  23. "title": "小米手机",
  24. "category": "小米",
  25. "images": "http://www.gulixueyuan.com/xm.jpg",
  26. "price": 3999
  27. }
  28. },
  29. {
  30. "_index": "shopping",
  31. "_type": "_doc",
  32. "_id": "A9R5sHgBaKNfVnMb25Ya",
  33. "_score": 1,
  34. "_source": {
  35. "title": "小米手机",
  36. "category": "小米",
  37. "images": "http://www.gulixueyuan.com/xm.jpg",
  38. "price": 1999
  39. }
  40. }
  41. ]
  42. }
  43. }

查询排序

如果你想通过排序查出价格最高的手机,在 Postman 中,向 ES 服务器发 GET请求 : http://127.0.0.1:9200/shopping/_search,附带JSON体如下:

  1. {
  2. "query":{
  3. "match_all":{}
  4. },
  5. "sort":{
  6. "price":{
  7. "order":"desc"
  8. }
  9. }
  10. }

返回结果如下:

  1. {
  2. "took": 96,
  3. "timed_out": false,
  4. "_shards": {
  5. "total": 1,
  6. "successful": 1,
  7. "skipped": 0,
  8. "failed": 0
  9. },
  10. "hits": {
  11. "total": {
  12. "value": 6,
  13. "relation": "eq"
  14. },
  15. "max_score": null,
  16. "hits": [
  17. {
  18. "_index": "shopping",
  19. "_type": "_doc",
  20. "_id": "ANQqsHgBaKNfVnMbhZYU",
  21. "_score": null,
  22. "_source": {
  23. "title": "小米手机",
  24. "category": "小米",
  25. "images": "http://www.gulixueyuan.com/xm.jpg",
  26. "price": 3999
  27. },
  28. "sort": [
  29. 3999
  30. ]
  31. },
  32. {
  33. "_index": "shopping",
  34. "_type": "_doc",
  35. "_id": "A9R5sHgBaKNfVnMb25Ya",
  36. "_score": null,
  37. "_source": {
  38. "title": "小米手机",
  39. "category": "小米",
  40. "images": "http://www.gulixueyuan.com/xm.jpg",
  41. "price": 1999
  42. },
  43. "sort": [
  44. 1999
  45. ]
  46. },
  47. {
  48. "_index": "shopping",
  49. "_type": "_doc",
  50. "_id": "BNR5sHgBaKNfVnMb7pal",
  51. "_score": null,
  52. "_source": {
  53. "title": "小米手机",
  54. "category": "小米",
  55. "images": "http://www.gulixueyuan.com/xm.jpg",
  56. "price": 1999
  57. },
  58. "sort": [
  59. 1999
  60. ]
  61. },
  62. {
  63. "_index": "shopping",
  64. "_type": "_doc",
  65. "_id": "BtR6sHgBaKNfVnMbX5Y5",
  66. "_score": null,
  67. "_source": {
  68. "title": "华为手机",
  69. "category": "华为",
  70. "images": "http://www.gulixueyuan.com/xm.jpg",
  71. "price": 1999
  72. },
  73. "sort": [
  74. 1999
  75. ]
  76. },
  77. {
  78. "_index": "shopping",
  79. "_type": "_doc",
  80. "_id": "B9R6sHgBaKNfVnMbZpZ6",
  81. "_score": null,
  82. "_source": {
  83. "title": "华为手机",
  84. "category": "华为",
  85. "images": "http://www.gulixueyuan.com/xm.jpg",
  86. "price": 1999
  87. },
  88. "sort": [
  89. 1999
  90. ]
  91. },
  92. {
  93. "_index": "shopping",
  94. "_type": "_doc",
  95. "_id": "CdR7sHgBaKNfVnMbsJb9",
  96. "_score": null,
  97. "_source": {
  98. "title": "华为手机",
  99. "category": "华为",
  100. "images": "http://www.gulixueyuan.com/xm.jpg",
  101. "price": 1999
  102. },
  103. "sort": [
  104. 1999
  105. ]
  106. }
  107. ]
  108. }
  109. }

入门-HTTP-多条件查询 & 范围查询

多条件查询

假设想找出小米牌子,价格为3999元的。(must相当于数据库的&&)

  1. {
  2. "query":{
  3. "bool":{
  4. "must":[{
  5. "match":{
  6. "category":"小米"
  7. }
  8. },{
  9. "match":{
  10. "price":3999.00
  11. }
  12. }]
  13. }
  14. }
  15. }

返回结果如下:

  1. {
  2. "took": 134,
  3. "timed_out": false,
  4. "_shards": {
  5. "total": 1,
  6. "successful": 1,
  7. "skipped": 0,
  8. "failed": 0
  9. },
  10. "hits": {
  11. "total": {
  12. "value": 1,
  13. "relation": "eq"
  14. },
  15. "max_score": 2.3862944,
  16. "hits": [
  17. {
  18. "_index": "shopping",
  19. "_type": "_doc",
  20. "_id": "ANQqsHgBaKNfVnMbhZYU",
  21. "_score": 2.3862944,
  22. "_source": {
  23. "title": "小米手机",
  24. "category": "小米",
  25. "images": "http://www.gulixueyuan.com/xm.jpg",
  26. "price": 3999
  27. }
  28. }
  29. ]
  30. }
  31. }

假设想找出小米和华为的牌子。(should相当于数据库的||)
在 Postman 中,向 ES 服务器发 GET请求 : http://127.0.0.1:9200/shopping/_search,附带JSON体如下:

  1. {
  2. "query":{
  3. "bool":{
  4. "should":[{
  5. "match":{
  6. "category":"小米"
  7. }
  8. },{
  9. "match":{
  10. "category":"华为"
  11. }
  12. }]
  13. },
  14. "filter":{
  15. "range":{
  16. "price":{
  17. "gt":2000
  18. }
  19. }
  20. }
  21. }
  22. }

返回结果如下:

  1. {
  2. "took": 8,
  3. "timed_out": false,
  4. "_shards": {
  5. "total": 1,
  6. "successful": 1,
  7. "skipped": 0,
  8. "failed": 0
  9. },
  10. "hits": {
  11. "total": {
  12. "value": 6,
  13. "relation": "eq"
  14. },
  15. "max_score": 1.3862942,
  16. "hits": [
  17. {
  18. "_index": "shopping",
  19. "_type": "_doc",
  20. "_id": "ANQqsHgBaKNfVnMbhZYU",
  21. "_score": 1.3862942,
  22. "_source": {
  23. "title": "小米手机",
  24. "category": "小米",
  25. "images": "http://www.gulixueyuan.com/xm.jpg",
  26. "price": 3999
  27. }
  28. },
  29. {
  30. "_index": "shopping",
  31. "_type": "_doc",
  32. "_id": "A9R5sHgBaKNfVnMb25Ya",
  33. "_score": 1.3862942,
  34. "_source": {
  35. "title": "小米手机",
  36. "category": "小米",
  37. "images": "http://www.gulixueyuan.com/xm.jpg",
  38. "price": 1999
  39. }
  40. },
  41. {
  42. "_index": "shopping",
  43. "_type": "_doc",
  44. "_id": "BNR5sHgBaKNfVnMb7pal",
  45. "_score": 1.3862942,
  46. "_source": {
  47. "title": "小米手机",
  48. "category": "小米",
  49. "images": "http://www.gulixueyuan.com/xm.jpg",
  50. "price": 1999
  51. }
  52. },
  53. {
  54. "_index": "shopping",
  55. "_type": "_doc",
  56. "_id": "BtR6sHgBaKNfVnMbX5Y5",
  57. "_score": 1.3862942,
  58. "_source": {
  59. "title": "华为手机",
  60. "category": "华为",
  61. "images": "http://www.gulixueyuan.com/xm.jpg",
  62. "price": 1999
  63. }
  64. },
  65. {
  66. "_index": "shopping",
  67. "_type": "_doc",
  68. "_id": "B9R6sHgBaKNfVnMbZpZ6",
  69. "_score": 1.3862942,
  70. "_source": {
  71. "title": "华为手机",
  72. "category": "华为",
  73. "images": "http://www.gulixueyuan.com/xm.jpg",
  74. "price": 1999
  75. }
  76. },
  77. {
  78. "_index": "shopping",
  79. "_type": "_doc",
  80. "_id": "CdR7sHgBaKNfVnMbsJb9",
  81. "_score": 1.3862942,
  82. "_source": {
  83. "title": "华为手机",
  84. "category": "华为",
  85. "images": "http://www.gulixueyuan.com/xm.jpg",
  86. "price": 1999
  87. }
  88. }
  89. ]
  90. }
  91. }

范围查询

假设想找出小米和华为的牌子,价格大于2000元的手机。
在 Postman 中,向 ES 服务器发 GET请求 : http://127.0.0.1:9200/shopping/_search,附带JSON体如下:

  1. {
  2. "query":{
  3. "bool":{
  4. "should":[{
  5. "match":{
  6. "category":"小米"
  7. }
  8. },{
  9. "match":{
  10. "category":"华为"
  11. }
  12. }],
  13. "filter":{
  14. "range":{
  15. "price":{
  16. "gt":2000
  17. }
  18. }
  19. }
  20. }
  21. }
  22. }

返回结果如下:

  1. {
  2. "took": 72,
  3. "timed_out": false,
  4. "_shards": {
  5. "total": 1,
  6. "successful": 1,
  7. "skipped": 0,
  8. "failed": 0
  9. },
  10. "hits": {
  11. "total": {
  12. "value": 1,
  13. "relation": "eq"
  14. },
  15. "max_score": 1.3862942,
  16. "hits": [
  17. {
  18. "_index": "shopping",
  19. "_type": "_doc",
  20. "_id": "ANQqsHgBaKNfVnMbhZYU",
  21. "_score": 1.3862942,
  22. "_source": {
  23. "title": "小米手机",
  24. "category": "小米",
  25. "images": "http://www.gulixueyuan.com/xm.jpg",
  26. "price": 3999
  27. }
  28. }
  29. ]
  30. }
  31. }

入门-HTTP-全文检索 & 完全匹配 & 高亮查询

全文检索

这功能像搜索引擎那样,如品牌输入“小华”,返回结果带回品牌有“小米”和华为的。
在 Postman 中,向 ES 服务器发 GET请求 : http://127.0.0.1:9200/shopping/_search,附带JSON体如下:

  1. {
  2. "query":{
  3. "match":{
  4. "category" : "小华"
  5. }
  6. }
  7. }

返回结果如下:

  1. {
  2. "took": 7,
  3. "timed_out": false,
  4. "_shards": {
  5. "total": 1,
  6. "successful": 1,
  7. "skipped": 0,
  8. "failed": 0
  9. },
  10. "hits": {
  11. "total": {
  12. "value": 6,
  13. "relation": "eq"
  14. },
  15. "max_score": 0.6931471,
  16. "hits": [
  17. {
  18. "_index": "shopping",
  19. "_type": "_doc",
  20. "_id": "ANQqsHgBaKNfVnMbhZYU",
  21. "_score": 0.6931471,
  22. "_source": {
  23. "title": "小米手机",
  24. "category": "小米",
  25. "images": "http://www.gulixueyuan.com/xm.jpg",
  26. "price": 3999
  27. }
  28. },
  29. {
  30. "_index": "shopping",
  31. "_type": "_doc",
  32. "_id": "A9R5sHgBaKNfVnMb25Ya",
  33. "_score": 0.6931471,
  34. "_source": {
  35. "title": "小米手机",
  36. "category": "小米",
  37. "images": "http://www.gulixueyuan.com/xm.jpg",
  38. "price": 1999
  39. }
  40. },
  41. {
  42. "_index": "shopping",
  43. "_type": "_doc",
  44. "_id": "BNR5sHgBaKNfVnMb7pal",
  45. "_score": 0.6931471,
  46. "_source": {
  47. "title": "小米手机",
  48. "category": "小米",
  49. "images": "http://www.gulixueyuan.com/xm.jpg",
  50. "price": 1999
  51. }
  52. },
  53. {
  54. "_index": "shopping",
  55. "_type": "_doc",
  56. "_id": "BtR6sHgBaKNfVnMbX5Y5",
  57. "_score": 0.6931471,
  58. "_source": {
  59. "title": "华为手机",
  60. "category": "华为",
  61. "images": "http://www.gulixueyuan.com/xm.jpg",
  62. "price": 1999
  63. }
  64. },
  65. {
  66. "_index": "shopping",
  67. "_type": "_doc",
  68. "_id": "B9R6sHgBaKNfVnMbZpZ6",
  69. "_score": 0.6931471,
  70. "_source": {
  71. "title": "华为手机",
  72. "category": "华为",
  73. "images": "http://www.gulixueyuan.com/xm.jpg",
  74. "price": 1999
  75. }
  76. },
  77. {
  78. "_index": "shopping",
  79. "_type": "_doc",
  80. "_id": "CdR7sHgBaKNfVnMbsJb9",
  81. "_score": 0.6931471,
  82. "_source": {
  83. "title": "华为手机",
  84. "category": "华为",
  85. "images": "http://www.gulixueyuan.com/xm.jpg",
  86. "price": 1999
  87. }
  88. }
  89. ]
  90. }
  91. }

完全匹配

在 Postman 中,向 ES 服务器发 GET请求 : http://127.0.0.1:9200/shopping/_search,附带JSON体如下:

  1. {
  2. "query":{
  3. "match_phrase":{
  4. "category" : "为"
  5. }
  6. }
  7. }

返回结果如下:

  1. {
  2. "took": 2,
  3. "timed_out": false,
  4. "_shards": {
  5. "total": 1,
  6. "successful": 1,
  7. "skipped": 0,
  8. "failed": 0
  9. },
  10. "hits": {
  11. "total": {
  12. "value": 3,
  13. "relation": "eq"
  14. },
  15. "max_score": 0.6931471,
  16. "hits": [
  17. {
  18. "_index": "shopping",
  19. "_type": "_doc",
  20. "_id": "BtR6sHgBaKNfVnMbX5Y5",
  21. "_score": 0.6931471,
  22. "_source": {
  23. "title": "华为手机",
  24. "category": "华为",
  25. "images": "http://www.gulixueyuan.com/xm.jpg",
  26. "price": 1999
  27. }
  28. },
  29. {
  30. "_index": "shopping",
  31. "_type": "_doc",
  32. "_id": "B9R6sHgBaKNfVnMbZpZ6",
  33. "_score": 0.6931471,
  34. "_source": {
  35. "title": "华为手机",
  36. "category": "华为",
  37. "images": "http://www.gulixueyuan.com/xm.jpg",
  38. "price": 1999
  39. }
  40. },
  41. {
  42. "_index": "shopping",
  43. "_type": "_doc",
  44. "_id": "CdR7sHgBaKNfVnMbsJb9",
  45. "_score": 0.6931471,
  46. "_source": {
  47. "title": "华为手机",
  48. "category": "华为",
  49. "images": "http://www.gulixueyuan.com/xm.jpg",
  50. "price": 1999
  51. }
  52. }
  53. ]
  54. }
  55. }

高亮查询

在 Postman 中,向 ES 服务器发 GET请求 : http://127.0.0.1:9200/shopping/_search,附带JSON体如下:

  1. {
  2. "query":{
  3. "match_phrase":{
  4. "category" : "为"
  5. }
  6. },
  7. "highlight":{
  8. "fields":{
  9. "category":{}//<----高亮这字段
  10. }
  11. }
  12. }

返回结果如下:

  1. {
  2. "took": 100,
  3. "timed_out": false,
  4. "_shards": {
  5. "total": 1,
  6. "successful": 1,
  7. "skipped": 0,
  8. "failed": 0
  9. },
  10. "hits": {
  11. "total": {
  12. "value": 3,
  13. "relation": "eq"
  14. },
  15. "max_score": 0.6931471,
  16. "hits": [
  17. {
  18. "_index": "shopping",
  19. "_type": "_doc",
  20. "_id": "BtR6sHgBaKNfVnMbX5Y5",
  21. "_score": 0.6931471,
  22. "_source": {
  23. "title": "华为手机",
  24. "category": "华为",
  25. "images": "http://www.gulixueyuan.com/xm.jpg",
  26. "price": 1999
  27. },
  28. "highlight": {
  29. "category": [
  30. "华<em>为</em>"//<------高亮一个为字。
  31. ]
  32. }
  33. },
  34. {
  35. "_index": "shopping",
  36. "_type": "_doc",
  37. "_id": "B9R6sHgBaKNfVnMbZpZ6",
  38. "_score": 0.6931471,
  39. "_source": {
  40. "title": "华为手机",
  41. "category": "华为",
  42. "images": "http://www.gulixueyuan.com/xm.jpg",
  43. "price": 1999
  44. },
  45. "highlight": {
  46. "category": [
  47. "华<em>为</em>"
  48. ]
  49. }
  50. },
  51. {
  52. "_index": "shopping",
  53. "_type": "_doc",
  54. "_id": "CdR7sHgBaKNfVnMbsJb9",
  55. "_score": 0.6931471,
  56. "_source": {
  57. "title": "华为手机",
  58. "category": "华为",
  59. "images": "http://www.gulixueyuan.com/xm.jpg",
  60. "price": 1999
  61. },
  62. "highlight": {
  63. "category": [
  64. "华<em>为</em>"
  65. ]
  66. }
  67. }
  68. ]
  69. }
  70. }

入门-HTTP-聚合查询

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

接下来按price字段进行分组:

在 Postman 中,向 ES 服务器发 GET请求 : http://127.0.0.1:9200/shopping/_search,附带JSON体如下:

  1. {
  2. "aggs":{//聚合操作
  3. "price_group":{//名称,随意起名
  4. "terms":{//分组
  5. "field":"price"//分组字段
  6. }
  7. }
  8. }
  9. }

返回结果如下:

  1. {
  2. "took": 63,
  3. "timed_out": false,
  4. "_shards": {
  5. "total": 1,
  6. "successful": 1,
  7. "skipped": 0,
  8. "failed": 0
  9. },
  10. "hits": {
  11. "total": {
  12. "value": 6,
  13. "relation": "eq"
  14. },
  15. "max_score": 1,
  16. "hits": [
  17. {
  18. "_index": "shopping",
  19. "_type": "_doc",
  20. "_id": "ANQqsHgBaKNfVnMbhZYU",
  21. "_score": 1,
  22. "_source": {
  23. "title": "小米手机",
  24. "category": "小米",
  25. "images": "http://www.gulixueyuan.com/xm.jpg",
  26. "price": 3999
  27. }
  28. },
  29. {
  30. "_index": "shopping",
  31. "_type": "_doc",
  32. "_id": "A9R5sHgBaKNfVnMb25Ya",
  33. "_score": 1,
  34. "_source": {
  35. "title": "小米手机",
  36. "category": "小米",
  37. "images": "http://www.gulixueyuan.com/xm.jpg",
  38. "price": 1999
  39. }
  40. },
  41. {
  42. "_index": "shopping",
  43. "_type": "_doc",
  44. "_id": "BNR5sHgBaKNfVnMb7pal",
  45. "_score": 1,
  46. "_source": {
  47. "title": "小米手机",
  48. "category": "小米",
  49. "images": "http://www.gulixueyuan.com/xm.jpg",
  50. "price": 1999
  51. }
  52. },
  53. {
  54. "_index": "shopping",
  55. "_type": "_doc",
  56. "_id": "BtR6sHgBaKNfVnMbX5Y5",
  57. "_score": 1,
  58. "_source": {
  59. "title": "华为手机",
  60. "category": "华为",
  61. "images": "http://www.gulixueyuan.com/xm.jpg",
  62. "price": 1999
  63. }
  64. },
  65. {
  66. "_index": "shopping",
  67. "_type": "_doc",
  68. "_id": "B9R6sHgBaKNfVnMbZpZ6",
  69. "_score": 1,
  70. "_source": {
  71. "title": "华为手机",
  72. "category": "华为",
  73. "images": "http://www.gulixueyuan.com/xm.jpg",
  74. "price": 1999
  75. }
  76. },
  77. {
  78. "_index": "shopping",
  79. "_type": "_doc",
  80. "_id": "CdR7sHgBaKNfVnMbsJb9",
  81. "_score": 1,
  82. "_source": {
  83. "title": "华为手机",
  84. "category": "华为",
  85. "images": "http://www.gulixueyuan.com/xm.jpg",
  86. "price": 1999
  87. }
  88. }
  89. ]
  90. },
  91. "aggregations": {
  92. "price_group": {
  93. "doc_count_error_upper_bound": 0,
  94. "sum_other_doc_count": 0,
  95. "buckets": [
  96. {
  97. "key": 1999,
  98. "doc_count": 5
  99. },
  100. {
  101. "key": 3999,
  102. "doc_count": 1
  103. }
  104. ]
  105. }
  106. }
  107. }

上面返回结果会附带原始数据的。若不想要不附带原始数据的结果,在 Postman 中,向 ES 服务器发 GET请求 : http://127.0.0.1:9200/shopping/_search,附带JSON体如下:

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

返回结果如下:

  1. {
  2. "took": 60,
  3. "timed_out": false,
  4. "_shards": {
  5. "total": 1,
  6. "successful": 1,
  7. "skipped": 0,
  8. "failed": 0
  9. },
  10. "hits": {
  11. "total": {
  12. "value": 6,
  13. "relation": "eq"
  14. },
  15. "max_score": null,
  16. "hits": []
  17. },
  18. "aggregations": {
  19. "price_group": {
  20. "doc_count_error_upper_bound": 0,
  21. "sum_other_doc_count": 0,
  22. "buckets": [
  23. {
  24. "key": 1999,
  25. "doc_count": 5
  26. },
  27. {
  28. "key": 3999,
  29. "doc_count": 1
  30. }
  31. ]
  32. }
  33. }
  34. }

若想对所有手机价格求平均值
在 Postman 中,向 ES 服务器发 GET请求 : http://127.0.0.1:9200/shopping/_search,附带JSON体如下:

  1. {
  2. "aggs":{
  3. "price_avg":{//名称,随意起名
  4. "avg":{//求平均
  5. "field":"price"
  6. }
  7. }
  8. },
  9. "size":0
  10. }

返回结果如下:

  1. {
  2. "took": 14,
  3. "timed_out": false,
  4. "_shards": {
  5. "total": 1,
  6. "successful": 1,
  7. "skipped": 0,
  8. "failed": 0
  9. },
  10. "hits": {
  11. "total": {
  12. "value": 6,
  13. "relation": "eq"
  14. },
  15. "max_score": null,
  16. "hits": []
  17. },
  18. "aggregations": {
  19. "price_avg": {
  20. "value": 2332.3333333333335
  21. }
  22. }
  23. }

入门-HTTP-映射关系

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

接下来就需要建索引库(index)中的映射了,类似于数据库(database)中的表结构(table)。

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

先创建一个索引:

  1. PUT http://127.0.0.1:9200/user

返回结果:

  1. {
  2. "acknowledged": true,
  3. "shards_acknowledged": true,
  4. "index": "user"
  5. }

创建映射

  1. # PUT http://127.0.0.1:9200/user/_mapping
  2. {
  3. "properties": {
  4. "name":{
  5. "type": "text",
  6. "index": true
  7. },
  8. "sex":{
  9. "type": "keyword",
  10. "index": true
  11. },
  12. "tel":{
  13. "type": "keyword",
  14. "index": false
  15. }
  16. }
  17. }

返回结果如下:

  1. {
  2. "acknowledged": true
  3. }

查询映射

  1. #GET http://127.0.0.1:9200/user/_mapping
  2. 返回结果如下:
  3. {
  4. "user": {
  5. "mappings": {
  6. "properties": {
  7. "name": {
  8. "type": "text"
  9. },
  10. "sex": {
  11. "type": "keyword"
  12. },
  13. "tel": {
  14. "type": "keyword",
  15. "index": false
  16. }
  17. }
  18. }
  19. }
  20. }

增加数据

  1. #PUT http://127.0.0.1:9200/user/_create/1001
  2. {
  3. "name":"小米",
  4. "sex":"男的",
  5. "tel":"1111"
  6. }
  7. 返回结果如下:
  8. {
  9. "_index": "user",
  10. "_type": "_doc",
  11. "_id": "1001",
  12. "_version": 1,
  13. "result": "created",
  14. "_shards": {
  15. "total": 2,
  16. "successful": 1,
  17. "failed": 0
  18. },
  19. "_seq_no": 0,
  20. "_primary_term": 1
  21. }

查找name含有”小“数据:

  1. #GET http://127.0.0.1:9200/user/_search
  2. {
  3. "query":{
  4. "match":{
  5. "name":"小"
  6. }
  7. }
  8. }
  9. 返回结果如下:
  10. {
  11. "took": 495,
  12. "timed_out": false,
  13. "_shards": {
  14. "total": 1,
  15. "successful": 1,
  16. "skipped": 0,
  17. "failed": 0
  18. },
  19. "hits": {
  20. "total": {
  21. "value": 1,
  22. "relation": "eq"
  23. },
  24. "max_score": 0.2876821,
  25. "hits": [
  26. {
  27. "_index": "user",
  28. "_type": "_doc",
  29. "_id": "1001",
  30. "_score": 0.2876821,
  31. "_source": {
  32. "name": "小米",
  33. "sex": "男的",
  34. "tel": "1111"
  35. }
  36. }
  37. ]
  38. }
  39. }

查找sex含有”男“数据:

  1. #GET http://127.0.0.1:9200/user/_search
  2. {
  3. "query":{
  4. "match":{
  5. "sex":"男"
  6. }
  7. }
  8. }
  9. 返回结果如下:
  10. {
  11. "took": 1,
  12. "timed_out": false,
  13. "_shards": {
  14. "total": 1,
  15. "successful": 1,
  16. "skipped": 0,
  17. "failed": 0
  18. },
  19. "hits": {
  20. "total": {
  21. "value": 0,
  22. "relation": "eq"
  23. },
  24. "max_score": null,
  25. "hits": []
  26. }
  27. }

入门-JavaAPI

入门-JavaAPI-环境准备

新建Maven工程。
添加依赖:

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.elasticsearch</groupId>
  4. <artifactId>elasticsearch</artifactId>
  5. <version>7.8.0</version>
  6. </dependency>
  7. <!-- elasticsearch 的客户端 -->
  8. <dependency>
  9. <groupId>org.elasticsearch.client</groupId>
  10. <artifactId>elasticsearch-rest-high-level-client</artifactId>
  11. <version>7.8.0</version>
  12. </dependency>
  13. <!-- elasticsearch 依赖 2.x log4j -->
  14. <dependency>
  15. <groupId>org.apache.logging.log4j</groupId>
  16. <artifactId>log4j-api</artifactId>
  17. <version>2.8.2</version>
  18. </dependency>
  19. <dependency>
  20. <groupId>org.apache.logging.log4j</groupId>
  21. <artifactId>log4j-core</artifactId>
  22. <version>2.8.2</version>
  23. </dependency>
  24. <dependency>
  25. <groupId>com.fasterxml.jackson.core</groupId>
  26. <artifactId>jackson-databind</artifactId>
  27. <version>2.9.9</version>
  28. </dependency>
  29. <!-- junit 单元测试 -->
  30. <dependency>
  31. <groupId>junit</groupId>
  32. <artifactId>junit</artifactId>
  33. <version>4.12</version>
  34. </dependency>
  35. </dependencies>

HelloElasticsearch

  1. import java.io.IOException;
  2. import org.apache.http.HttpHost;
  3. import org.elasticsearch.client.RestClient;
  4. import org.elasticsearch.client.RestHighLevelClient;
  5. public class HelloElasticsearch {
  6. public static void main(String[] args) throws IOException {
  7. // 创建客户端对象
  8. RestHighLevelClient client = new RestHighLevelClient(
  9. RestClient.builder(new HttpHost("localhost", 9200, "http")));
  10. // ...
  11. System.out.println(client);
  12. // 关闭客户端连接
  13. client.close();
  14. }
  15. }

入门-JavaAPI-索引-创建

  1. import org.apache.http.HttpHost;
  2. import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
  3. import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
  4. import org.elasticsearch.client.RequestOptions;
  5. import org.elasticsearch.client.RestClient;
  6. import org.elasticsearch.client.RestHighLevelClient;
  7. import java.io.IOException;
  8. public class CreateIndex {
  9. public static void main(String[] args) throws IOException {
  10. // 创建客户端对象
  11. RestHighLevelClient client = new RestHighLevelClient(
  12. RestClient.builder(new HttpHost("localhost", 9200, "http")));
  13. // 创建索引 - 请求对象
  14. CreateIndexRequest request = new CreateIndexRequest("user2");
  15. // 发送请求,获取响应
  16. CreateIndexResponse response = client.indices().create(request,
  17. RequestOptions.DEFAULT);
  18. boolean acknowledged = response.isAcknowledged();
  19. // 响应状态
  20. System.out.println("操作状态 = " + acknowledged);
  21. // 关闭客户端连接
  22. client.close();
  23. }
  24. }
  25. 后台打印:
  26. 四月 09, 2021 2:12:08 下午 org.elasticsearch.client.RestClient logResponse
  27. 警告: request [PUT http://localhost:9200/user2?master_timeout=30s&include_type_name=true&timeout=30s] returned 1 warnings: [299 Elasticsearch-7.8.0-757314695644ea9a1dc2fecd26d1a43856725e65 "[types removal] Using include_type_name in create index requests is deprecated. The parameter will be removed in the next major version."]
  28. 操作状态 = true

入门-JavaAPI-索引-查询 & 删除

查询

  1. import org.apache.http.HttpHost;
  2. import org.elasticsearch.client.RequestOptions;
  3. import org.elasticsearch.client.RestClient;
  4. import org.elasticsearch.client.RestHighLevelClient;
  5. import org.elasticsearch.client.indices.GetIndexRequest;
  6. import org.elasticsearch.client.indices.GetIndexResponse;
  7. import java.io.IOException;
  8. public class SearchIndex {
  9. public static void main(String[] args) throws IOException {
  10. // 创建客户端对象
  11. RestHighLevelClient client = new RestHighLevelClient(
  12. RestClient.builder(new HttpHost("localhost", 9200, "http")));
  13. // 查询索引 - 请求对象
  14. GetIndexRequest request = new GetIndexRequest("user2");
  15. // 发送请求,获取响应
  16. GetIndexResponse response = client.indices().get(request,
  17. RequestOptions.DEFAULT);
  18. System.out.println("aliases:"+response.getAliases());
  19. System.out.println("mappings:"+response.getMappings());
  20. System.out.println("settings:"+response.getSettings());
  21. client.close();
  22. }
  23. }
  24. 后台打印:
  25. aliases:{user2=[]}
  26. mappings:{user2=org.elasticsearch.cluster.metadata.MappingMetadata@ad700514}
  27. settings:{user2={"index.creation_date":"1617948726976","index.number_of_replicas":"1","index.number_of_shards":"1","index.provided_name":"user2","index.uuid":"UGZ1ntcySnK6hWyP2qoVpQ","index.version.created":"7080099"}}
  28. Process finished with exit code 0

删除

  1. import org.apache.http.HttpHost;
  2. import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
  3. import org.elasticsearch.action.support.master.AcknowledgedResponse;
  4. import org.elasticsearch.client.RequestOptions;
  5. import org.elasticsearch.client.RestClient;
  6. import org.elasticsearch.client.RestHighLevelClient;
  7. import java.io.IOException;
  8. public class DeleteIndex {
  9. public static void main(String[] args) throws IOException {
  10. RestHighLevelClient client = new RestHighLevelClient(
  11. RestClient.builder(new HttpHost("localhost", 9200, "http")));
  12. // 删除索引 - 请求对象
  13. DeleteIndexRequest request = new DeleteIndexRequest("user2");
  14. // 发送请求,获取响应
  15. AcknowledgedResponse response = client.indices().delete(request,RequestOptions.DEFAULT);
  16. // 操作结果
  17. System.out.println("操作结果 : " + response.isAcknowledged());
  18. client.close();
  19. }
  20. }

入门-JavaAPI-文档-新增 & 修改

重构

上文由于频繁使用以下连接Elasticsearch和关闭它的代码,于是对它进行重构。

  1. public class SomeClass {
  2. public static void main(String[] args) throws IOException {
  3. RestHighLevelClient client = new RestHighLevelClient(
  4. RestClient.builder(new HttpHost("localhost", 9200, "http")));
  5. ...
  6. client.close();
  7. }
  8. }

重构后的代码:

  1. import org.elasticsearch.client.RestHighLevelClient;
  2. public interface ElasticsearchTask {
  3. void doSomething(RestHighLevelClient client) throws Exception;
  4. }
  1. public class ConnectElasticsearch{
  2. public static void connect(ElasticsearchTask task){
  3. // 创建客户端对象
  4. RestHighLevelClient client = new RestHighLevelClient(
  5. RestClient.builder(new HttpHost("localhost", 9200, "http")));
  6. try {
  7. task.doSomething(client);
  8. // 关闭客户端连接
  9. client.close();
  10. } catch (Exception e) {
  11. e.printStackTrace();
  12. }
  13. }
  14. }

接下来,如果想让Elasticsearch完成一些操作,就编写一个lambda式即可。

  1. public class SomeClass {
  2. public static void main(String[] args) {
  3. ConnectElasticsearch.connect(client -> {
  4. //do something
  5. });
  6. }
  7. }

新增

  1. import com.fasterxml.jackson.databind.ObjectMapper;
  2. import com.lun.elasticsearch.hello.ConnectElasticsearch;
  3. import com.lun.elasticsearch.model.User;
  4. import org.elasticsearch.action.index.IndexRequest;
  5. import org.elasticsearch.action.index.IndexResponse;
  6. import org.elasticsearch.client.RequestOptions;
  7. import org.elasticsearch.common.xcontent.XContentType;
  8. public class InsertDoc {
  9. public static void main(String[] args) {
  10. ConnectElasticsearch.connect(client -> {
  11. // 新增文档 - 请求对象
  12. IndexRequest request = new IndexRequest();
  13. // 设置索引及唯一性标识
  14. request.index("user").id("1001");
  15. // 创建数据对象
  16. User user = new User();
  17. user.setName("zhangsan");
  18. user.setAge(30);
  19. user.setSex("男");
  20. ObjectMapper objectMapper = new ObjectMapper();
  21. String productJson = objectMapper.writeValueAsString(user);
  22. // 添加文档数据,数据格式为 JSON 格式
  23. request.source(productJson, XContentType.JSON);
  24. // 客户端发送请求,获取响应对象
  25. IndexResponse response = client.index(request, RequestOptions.DEFAULT);
  26. 3.打印结果信息
  27. System.out.println("_index:" + response.getIndex());
  28. System.out.println("_id:" + response.getId());
  29. System.out.println("_result:" + response.getResult());
  30. });
  31. }
  32. }

修改

  1. import com.lun.elasticsearch.hello.ConnectElasticsearch;
  2. import org.elasticsearch.action.update.UpdateRequest;
  3. import org.elasticsearch.action.update.UpdateResponse;
  4. import org.elasticsearch.client.RequestOptions;
  5. import org.elasticsearch.common.xcontent.XContentType;
  6. public class UpdateDoc {
  7. public static void main(String[] args) {
  8. ConnectElasticsearch.connect(client -> {
  9. // 修改文档 - 请求对象
  10. UpdateRequest request = new UpdateRequest();
  11. // 配置修改参数
  12. request.index("user").id("1001");
  13. // 设置请求体,对数据进行修改
  14. request.doc(XContentType.JSON, "sex", "女");
  15. // 客户端发送请求,获取响应对象
  16. UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
  17. System.out.println("_index:" + response.getIndex());
  18. System.out.println("_id:" + response.getId());
  19. System.out.println("_result:" + response.getResult());
  20. });
  21. }
  22. }

入门-JavaAPI-文档-查询 & 删除

查询

  1. import com.lun.elasticsearch.hello.ConnectElasticsearch;
  2. import org.elasticsearch.action.get.GetRequest;
  3. import org.elasticsearch.action.get.GetResponse;
  4. import org.elasticsearch.client.RequestOptions;
  5. public class GetDoc {
  6. public static void main(String[] args) {
  7. ConnectElasticsearch.connect(client -> {
  8. //1.创建请求对象
  9. GetRequest request = new GetRequest().index("user").id("1001");
  10. //2.客户端发送请求,获取响应对象
  11. GetResponse response = client.get(request, RequestOptions.DEFAULT);
  12. 3.打印结果信息
  13. System.out.println("_index:" + response.getIndex());
  14. System.out.println("_type:" + response.getType());
  15. System.out.println("_id:" + response.getId());
  16. System.out.println("source:" + response.getSourceAsString());
  17. });
  18. }
  19. }

删除

  1. import com.lun.elasticsearch.hello.ConnectElasticsearch;
  2. import org.elasticsearch.action.delete.DeleteRequest;
  3. import org.elasticsearch.action.delete.DeleteResponse;
  4. import org.elasticsearch.client.RequestOptions;
  5. public class DeleteDoc {
  6. public static void main(String[] args) {
  7. ConnectElasticsearch.connect(client -> {
  8. //创建请求对象
  9. DeleteRequest request = new DeleteRequest().index("user").id("1001");
  10. //客户端发送请求,获取响应对象
  11. DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);
  12. //打印信息
  13. System.out.println(response.toString());
  14. });
  15. }
  16. }

入门-JavaAPI-文档-批量新增 & 批量删除\

批量新增

  1. import com.lun.elasticsearch.hello.ConnectElasticsearch;
  2. import org.elasticsearch.action.bulk.BulkRequest;
  3. import org.elasticsearch.action.bulk.BulkResponse;
  4. import org.elasticsearch.action.index.IndexRequest;
  5. import org.elasticsearch.client.RequestOptions;
  6. import org.elasticsearch.common.xcontent.XContentType;
  7. public class BatchInsertDoc {
  8. public static void main(String[] args) {
  9. ConnectElasticsearch.connect(client -> {
  10. //创建批量新增请求对象
  11. BulkRequest request = new BulkRequest();
  12. request.add(new
  13. IndexRequest().index("user").id("1001").source(XContentType.JSON, "name",
  14. "zhangsan"));
  15. request.add(new
  16. IndexRequest().index("user").id("1002").source(XContentType.JSON, "name",
  17. "lisi"));
  18. request.add(new
  19. IndexRequest().index("user").id("1003").source(XContentType.JSON, "name",
  20. "wangwu"));
  21. //客户端发送请求,获取响应对象
  22. BulkResponse responses = client.bulk(request, RequestOptions.DEFAULT);
  23. //打印结果信息
  24. System.out.println("took:" + responses.getTook());
  25. System.out.println("items:" + responses.getItems());
  26. });
  27. }
  28. }

批量删除

  1. import com.lun.elasticsearch.hello.ConnectElasticsearch;
  2. import org.elasticsearch.action.bulk.BulkRequest;
  3. import org.elasticsearch.action.bulk.BulkResponse;
  4. import org.elasticsearch.action.delete.DeleteRequest;
  5. import org.elasticsearch.client.RequestOptions;
  6. public class BatchDeleteDoc {
  7. public static void main(String[] args) {
  8. ConnectElasticsearch.connect(client -> {
  9. //创建批量删除请求对象
  10. BulkRequest request = new BulkRequest();
  11. request.add(new DeleteRequest().index("user").id("1001"));
  12. request.add(new DeleteRequest().index("user").id("1002"));
  13. request.add(new DeleteRequest().index("user").id("1003"));
  14. //客户端发送请求,获取响应对象
  15. BulkResponse responses = client.bulk(request, RequestOptions.DEFAULT);
  16. //打印结果信息
  17. System.out.println("took:" + responses.getTook());
  18. System.out.println("items:" + responses.getItems());
  19. });
  20. }
  21. }

入门-JavaAPI-文档-高级查询-全量查询

先批量增加数据

  1. public class BatchInsertDoc {
  2. public static void main(String[] args) {
  3. ConnectElasticsearch.connect(client -> {
  4. //创建批量新增请求对象
  5. BulkRequest request = new BulkRequest();
  6. request.add(new IndexRequest().index("user").id("1001").source(XContentType.JSON, "name", "zhangsan", "age", "10", "sex","女"));
  7. request.add(new IndexRequest().index("user").id("1002").source(XContentType.JSON, "name", "lisi", "age", "30", "sex","女"));
  8. request.add(new IndexRequest().index("user").id("1003").source(XContentType.JSON, "name", "wangwu1", "age", "40", "sex","男"));
  9. request.add(new IndexRequest().index("user").id("1004").source(XContentType.JSON, "name", "wangwu2", "age", "20", "sex","女"));
  10. request.add(new IndexRequest().index("user").id("1005").source(XContentType.JSON, "name", "wangwu3", "age", "50", "sex","男"));
  11. request.add(new IndexRequest().index("user").id("1006").source(XContentType.JSON, "name", "wangwu4", "age", "20", "sex","男"));
  12. //客户端发送请求,获取响应对象
  13. BulkResponse responses = client.bulk(request, RequestOptions.DEFAULT);
  14. //打印结果信息
  15. System.out.println("took:" + responses.getTook());
  16. System.out.println("items:" + responses.getItems());
  17. });
  18. }
  19. }

查询所有索引数据

  1. import com.lun.elasticsearch.hello.ConnectElasticsearch;
  2. import org.elasticsearch.action.search.SearchRequest;
  3. import org.elasticsearch.action.search.SearchResponse;
  4. import org.elasticsearch.client.RequestOptions;
  5. import org.elasticsearch.index.query.QueryBuilders;
  6. import org.elasticsearch.search.SearchHit;
  7. import org.elasticsearch.search.SearchHits;
  8. import org.elasticsearch.search.builder.SearchSourceBuilder;
  9. public class QueryDoc {
  10. public static void main(String[] args) {
  11. ConnectElasticsearch.connect(client -> {
  12. // 创建搜索请求对象
  13. SearchRequest request = new SearchRequest();
  14. request.indices("user");
  15. // 构建查询的请求体
  16. SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
  17. // 查询所有数据
  18. sourceBuilder.query(QueryBuilders.matchAllQuery());
  19. request.source(sourceBuilder);
  20. SearchResponse response = client.search(request, RequestOptions.DEFAULT);
  21. // 查询匹配
  22. SearchHits hits = response.getHits();
  23. System.out.println("took:" + response.getTook());
  24. System.out.println("timeout:" + response.isTimedOut());
  25. System.out.println("total:" + hits.getTotalHits());
  26. System.out.println("MaxScore:" + hits.getMaxScore());
  27. System.out.println("hits========>>");
  28. for (SearchHit hit : hits) {
  29. //输出每条查询的结果信息
  30. System.out.println(hit.getSourceAsString());
  31. }
  32. System.out.println("<<========");
  33. });
  34. }
  35. }

入门-JavaAPI-文档-高级查询-分页查询 & 条件查询 & 查询排序

条件查询

  1. import com.lun.elasticsearch.hello.ConnectElasticsearch;
  2. import com.lun.elasticsearch.hello.ElasticsearchTask;
  3. import org.elasticsearch.action.search.SearchRequest;
  4. import org.elasticsearch.action.search.SearchResponse;
  5. import org.elasticsearch.client.RequestOptions;
  6. import org.elasticsearch.index.query.QueryBuilders;
  7. import org.elasticsearch.search.SearchHit;
  8. import org.elasticsearch.search.SearchHits;
  9. import org.elasticsearch.search.builder.SearchSourceBuilder;
  10. import org.elasticsearch.search.sort.SortOrder;
  11. public class QueryDoc {
  12. public static final ElasticsearchTask SEARCH_BY_CONDITION = client -> {
  13. // 创建搜索请求对象
  14. SearchRequest request = new SearchRequest();
  15. request.indices("user");
  16. // 构建查询的请求体
  17. SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
  18. sourceBuilder.query(QueryBuilders.termQuery("age", "30"));
  19. request.source(sourceBuilder);
  20. SearchResponse response = client.search(request, RequestOptions.DEFAULT);
  21. // 查询匹配
  22. SearchHits hits = response.getHits();
  23. System.out.println("took:" + response.getTook());
  24. System.out.println("timeout:" + response.isTimedOut());
  25. System.out.println("total:" + hits.getTotalHits());
  26. System.out.println("MaxScore:" + hits.getMaxScore());
  27. System.out.println("hits========>>");
  28. for (SearchHit hit : hits) {
  29. //输出每条查询的结果信息
  30. System.out.println(hit.getSourceAsString());
  31. }
  32. System.out.println("<<========");
  33. };
  34. public static void main(String[] args) {
  35. ConnectElasticsearch.connect(SEARCH_BY_CONDITION);
  36. }
  37. }

分页查询

  1. import com.lun.elasticsearch.hello.ConnectElasticsearch;
  2. import com.lun.elasticsearch.hello.ElasticsearchTask;
  3. import org.elasticsearch.action.search.SearchRequest;
  4. import org.elasticsearch.action.search.SearchResponse;
  5. import org.elasticsearch.client.RequestOptions;
  6. import org.elasticsearch.index.query.QueryBuilders;
  7. import org.elasticsearch.search.SearchHit;
  8. import org.elasticsearch.search.SearchHits;
  9. import org.elasticsearch.search.builder.SearchSourceBuilder;
  10. import org.elasticsearch.search.sort.SortOrder;
  11. public class QueryDoc {
  12. public static final ElasticsearchTask SEARCH_BY_PAGING = client -> {
  13. // 创建搜索请求对象
  14. SearchRequest request = new SearchRequest();
  15. request.indices("user");
  16. // 构建查询的请求体
  17. SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
  18. sourceBuilder.query(QueryBuilders.matchAllQuery());
  19. // 分页查询
  20. // 当前页其实索引(第一条数据的顺序号), from
  21. sourceBuilder.from(0);
  22. // 每页显示多少条 size
  23. sourceBuilder.size(2);
  24. request.source(sourceBuilder);
  25. SearchResponse response = client.search(request, RequestOptions.DEFAULT);
  26. // 查询匹配
  27. SearchHits hits = response.getHits();
  28. System.out.println("took:" + response.getTook());
  29. System.out.println("timeout:" + response.isTimedOut());
  30. System.out.println("total:" + hits.getTotalHits());
  31. System.out.println("MaxScore:" + hits.getMaxScore());
  32. System.out.println("hits========>>");
  33. for (SearchHit hit : hits) {
  34. //输出每条查询的结果信息
  35. System.out.println(hit.getSourceAsString());
  36. }
  37. System.out.println("<<========");
  38. };
  39. public static void main(String[] args) {
  40. ConnectElasticsearch.connect(SEARCH_BY_CONDITION);
  41. }
  42. }

查询排序

  1. import com.lun.elasticsearch.hello.ConnectElasticsearch;
  2. import com.lun.elasticsearch.hello.ElasticsearchTask;
  3. import org.elasticsearch.action.search.SearchRequest;
  4. import org.elasticsearch.action.search.SearchResponse;
  5. import org.elasticsearch.client.RequestOptions;
  6. import org.elasticsearch.index.query.QueryBuilders;
  7. import org.elasticsearch.search.SearchHit;
  8. import org.elasticsearch.search.SearchHits;
  9. import org.elasticsearch.search.builder.SearchSourceBuilder;
  10. import org.elasticsearch.search.sort.SortOrder;
  11. public class QueryDoc {
  12. public static final ElasticsearchTask SEARCH_WITH_ORDER = client -> {
  13. // 创建搜索请求对象
  14. SearchRequest request = new SearchRequest();
  15. request.indices("user");
  16. // 构建查询的请求体
  17. SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
  18. sourceBuilder.query(QueryBuilders.matchAllQuery());
  19. // 排序
  20. sourceBuilder.sort("age", SortOrder.ASC);
  21. request.source(sourceBuilder);
  22. SearchResponse response = client.search(request, RequestOptions.DEFAULT);
  23. // 查询匹配
  24. SearchHits hits = response.getHits();
  25. System.out.println("took:" + response.getTook());
  26. System.out.println("timeout:" + response.isTimedOut());
  27. System.out.println("total:" + hits.getTotalHits());
  28. System.out.println("MaxScore:" + hits.getMaxScore());
  29. System.out.println("hits========>>");
  30. for (SearchHit hit : hits) {
  31. //输出每条查询的结果信息
  32. System.out.println(hit.getSourceAsString());
  33. }
  34. System.out.println("<<========");
  35. };
  36. public static void main(String[] args) {
  37. ConnectElasticsearch.connect(SEARCH_WITH_ORDER);
  38. }
  39. }

入门-JavaAPI-文档-高级查询-组合查询 & 范围查询

组合查询

  1. import com.lun.elasticsearch.hello.ConnectElasticsearch;
  2. import com.lun.elasticsearch.hello.ElasticsearchTask;
  3. import org.elasticsearch.action.search.SearchRequest;
  4. import org.elasticsearch.action.search.SearchResponse;
  5. import org.elasticsearch.client.RequestOptions;
  6. import org.elasticsearch.index.query.BoolQueryBuilder;
  7. import org.elasticsearch.index.query.QueryBuilders;
  8. import org.elasticsearch.search.SearchHit;
  9. import org.elasticsearch.search.SearchHits;
  10. import org.elasticsearch.search.builder.SearchSourceBuilder;
  11. import org.elasticsearch.search.sort.SortOrder;
  12. public class QueryDoc {
  13. public static final ElasticsearchTask SEARCH_BY_BOOL_CONDITION = client -> {
  14. // 创建搜索请求对象
  15. SearchRequest request = new SearchRequest();
  16. request.indices("user");
  17. // 构建查询的请求体
  18. SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
  19. BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
  20. // 必须包含
  21. boolQueryBuilder.must(QueryBuilders.matchQuery("age", "30"));
  22. // 一定不含
  23. boolQueryBuilder.mustNot(QueryBuilders.matchQuery("name", "zhangsan"));
  24. // 可能包含
  25. boolQueryBuilder.should(QueryBuilders.matchQuery("sex", "男"));
  26. sourceBuilder.query(boolQueryBuilder);
  27. request.source(sourceBuilder);
  28. SearchResponse response = client.search(request, RequestOptions.DEFAULT);
  29. // 查询匹配
  30. SearchHits hits = response.getHits();
  31. System.out.println("took:" + response.getTook());
  32. System.out.println("timeout:" + response.isTimedOut());
  33. System.out.println("total:" + hits.getTotalHits());
  34. System.out.println("MaxScore:" + hits.getMaxScore());
  35. System.out.println("hits========>>");
  36. for (SearchHit hit : hits) {
  37. //输出每条查询的结果信息
  38. System.out.println(hit.getSourceAsString());
  39. }
  40. System.out.println("<<========");
  41. };
  42. public static void main(String[] args) {
  43. ConnectElasticsearch.connect(SEARCH_BY_BOOL_CONDITION);
  44. }
  45. }

范围查询

  1. import com.lun.elasticsearch.hello.ConnectElasticsearch;
  2. import com.lun.elasticsearch.hello.ElasticsearchTask;
  3. import org.elasticsearch.action.search.SearchRequest;
  4. import org.elasticsearch.action.search.SearchResponse;
  5. import org.elasticsearch.client.RequestOptions;
  6. import org.elasticsearch.index.query.BoolQueryBuilder;
  7. import org.elasticsearch.index.query.QueryBuilders;
  8. import org.elasticsearch.index.query.RangeQueryBuilder;
  9. import org.elasticsearch.search.SearchHit;
  10. import org.elasticsearch.search.SearchHits;
  11. import org.elasticsearch.search.builder.SearchSourceBuilder;
  12. import org.elasticsearch.search.sort.SortOrder;
  13. public class QueryDoc {
  14. public static final ElasticsearchTask SEARCH_BY_RANGE = client -> {
  15. // 创建搜索请求对象
  16. SearchRequest request = new SearchRequest();
  17. request.indices("user");
  18. // 构建查询的请求体
  19. SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
  20. RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("age");
  21. // 大于等于
  22. //rangeQuery.gte("30");
  23. // 小于等于
  24. rangeQuery.lte("40");
  25. sourceBuilder.query(rangeQuery);
  26. request.source(sourceBuilder);
  27. SearchResponse response = client.search(request, RequestOptions.DEFAULT);
  28. // 查询匹配
  29. SearchHits hits = response.getHits();
  30. System.out.println("took:" + response.getTook());
  31. System.out.println("timeout:" + response.isTimedOut());
  32. System.out.println("total:" + hits.getTotalHits());
  33. System.out.println("MaxScore:" + hits.getMaxScore());
  34. System.out.println("hits========>>");
  35. for (SearchHit hit : hits) {
  36. //输出每条查询的结果信息
  37. System.out.println(hit.getSourceAsString());
  38. }
  39. System.out.println("<<========");
  40. };
  41. public static void main(String[] args) {
  42. ConnectElasticsearch.connect(SEARCH_BY_RANGE);
  43. }
  44. }

入门-JavaAPI-文档-高级查询-模糊查询 & 高亮查询

模糊查询

  1. import com.lun.elasticsearch.hello.ConnectElasticsearch;
  2. import com.lun.elasticsearch.hello.ElasticsearchTask;
  3. import org.elasticsearch.action.search.SearchRequest;
  4. import org.elasticsearch.action.search.SearchResponse;
  5. import org.elasticsearch.client.RequestOptions;
  6. import org.elasticsearch.common.unit.Fuzziness;
  7. import org.elasticsearch.index.query.BoolQueryBuilder;
  8. import org.elasticsearch.index.query.QueryBuilders;
  9. import org.elasticsearch.index.query.RangeQueryBuilder;
  10. import org.elasticsearch.search.SearchHit;
  11. import org.elasticsearch.search.SearchHits;
  12. import org.elasticsearch.search.builder.SearchSourceBuilder;
  13. import org.elasticsearch.search.sort.SortOrder;
  14. public class QueryDoc {
  15. public static final ElasticsearchTask SEARCH_BY_FUZZY_CONDITION = client -> {
  16. // 创建搜索请求对象
  17. SearchRequest request = new SearchRequest();
  18. request.indices("user");
  19. // 构建查询的请求体
  20. SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
  21. sourceBuilder.query(QueryBuilders.fuzzyQuery("name","wangwu").fuzziness(Fuzziness.ONE));
  22. request.source(sourceBuilder);
  23. SearchResponse response = client.search(request, RequestOptions.DEFAULT);
  24. // 查询匹配
  25. SearchHits hits = response.getHits();
  26. System.out.println("took:" + response.getTook());
  27. System.out.println("timeout:" + response.isTimedOut());
  28. System.out.println("total:" + hits.getTotalHits());
  29. System.out.println("MaxScore:" + hits.getMaxScore());
  30. System.out.println("hits========>>");
  31. for (SearchHit hit : hits) {
  32. //输出每条查询的结果信息
  33. System.out.println(hit.getSourceAsString());
  34. }
  35. System.out.println("<<========");
  36. };
  37. public static void main(String[] args) {
  38. // ConnectElasticsearch.connect(SEARCH_ALL);
  39. // ConnectElasticsearch.connect(SEARCH_BY_CONDITION);
  40. // ConnectElasticsearch.connect(SEARCH_BY_PAGING);
  41. // ConnectElasticsearch.connect(SEARCH_WITH_ORDER);
  42. // ConnectElasticsearch.connect(SEARCH_BY_BOOL_CONDITION);
  43. // ConnectElasticsearch.connect(SEARCH_BY_RANGE);
  44. ConnectElasticsearch.connect(SEARCH_BY_FUZZY_CONDITION);
  45. }
  46. }

高亮查询

  1. import com.lun.elasticsearch.hello.ConnectElasticsearch;
  2. import com.lun.elasticsearch.hello.ElasticsearchTask;
  3. import org.elasticsearch.action.search.SearchRequest;
  4. import org.elasticsearch.action.search.SearchResponse;
  5. import org.elasticsearch.client.RequestOptions;
  6. import org.elasticsearch.common.unit.Fuzziness;
  7. import org.elasticsearch.index.query.BoolQueryBuilder;
  8. import org.elasticsearch.index.query.QueryBuilders;
  9. import org.elasticsearch.index.query.RangeQueryBuilder;
  10. import org.elasticsearch.index.query.TermsQueryBuilder;
  11. import org.elasticsearch.search.SearchHit;
  12. import org.elasticsearch.search.SearchHits;
  13. import org.elasticsearch.search.builder.SearchSourceBuilder;
  14. import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
  15. import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
  16. import org.elasticsearch.search.sort.SortOrder;
  17. import java.util.Map;
  18. public class QueryDoc {
  19. public static final ElasticsearchTask SEARCH_WITH_HIGHLIGHT = client -> {
  20. // 高亮查询
  21. SearchRequest request = new SearchRequest().indices("user");
  22. //2.创建查询请求体构建器
  23. SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
  24. //构建查询方式:高亮查询
  25. TermsQueryBuilder termsQueryBuilder =
  26. QueryBuilders.termsQuery("name","zhangsan");
  27. //设置查询方式
  28. sourceBuilder.query(termsQueryBuilder);
  29. //构建高亮字段
  30. HighlightBuilder highlightBuilder = new HighlightBuilder();
  31. highlightBuilder.preTags("<font color='red'>");//设置标签前缀
  32. highlightBuilder.postTags("</font>");//设置标签后缀
  33. highlightBuilder.field("name");//设置高亮字段
  34. //设置高亮构建对象
  35. sourceBuilder.highlighter(highlightBuilder);
  36. //设置请求体
  37. request.source(sourceBuilder);
  38. //3.客户端发送请求,获取响应对象
  39. SearchResponse response = client.search(request, RequestOptions.DEFAULT);
  40. //4.打印响应结果
  41. SearchHits hits = response.getHits();
  42. System.out.println("took::"+response.getTook());
  43. System.out.println("time_out::"+response.isTimedOut());
  44. System.out.println("total::"+hits.getTotalHits());
  45. System.out.println("max_score::"+hits.getMaxScore());
  46. System.out.println("hits::::>>");
  47. for (SearchHit hit : hits) {
  48. String sourceAsString = hit.getSourceAsString();
  49. System.out.println(sourceAsString);
  50. //打印高亮结果
  51. Map<String, HighlightField> highlightFields = hit.getHighlightFields();
  52. System.out.println(highlightFields);
  53. }
  54. System.out.println("<<::::");
  55. };
  56. public static void main(String[] args) {
  57. ConnectElasticsearch.connect(SEARCH_WITH_HIGHLIGHT);
  58. }
  59. }

入门-JavaAPI-文档-高级查询-最大值查询 & 分组查询

最大值查询

  1. import com.lun.elasticsearch.hello.ConnectElasticsearch;
  2. import com.lun.elasticsearch.hello.ElasticsearchTask;
  3. import org.elasticsearch.action.search.SearchRequest;
  4. import org.elasticsearch.action.search.SearchResponse;
  5. import org.elasticsearch.client.RequestOptions;
  6. import org.elasticsearch.common.unit.Fuzziness;
  7. import org.elasticsearch.index.query.BoolQueryBuilder;
  8. import org.elasticsearch.index.query.QueryBuilders;
  9. import org.elasticsearch.index.query.RangeQueryBuilder;
  10. import org.elasticsearch.index.query.TermsQueryBuilder;
  11. import org.elasticsearch.search.SearchHit;
  12. import org.elasticsearch.search.SearchHits;
  13. import org.elasticsearch.search.aggregations.AggregationBuilders;
  14. import org.elasticsearch.search.builder.SearchSourceBuilder;
  15. import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
  16. import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
  17. import org.elasticsearch.search.sort.SortOrder;
  18. import java.util.Map;
  19. public class QueryDoc {
  20. public static final ElasticsearchTask SEARCH_WITH_MAX = client -> {
  21. // 高亮查询
  22. SearchRequest request = new SearchRequest().indices("user");
  23. SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
  24. sourceBuilder.aggregation(AggregationBuilders.max("maxAge").field("age"));
  25. //设置请求体
  26. request.source(sourceBuilder);
  27. //3.客户端发送请求,获取响应对象
  28. SearchResponse response = client.search(request, RequestOptions.DEFAULT);
  29. //4.打印响应结果
  30. SearchHits hits = response.getHits();
  31. System.out.println(response);
  32. };
  33. public static void main(String[] args) {
  34. ConnectElasticsearch.connect(SEARCH_WITH_MAX);
  35. }
  36. }

分组查询

  1. import com.lun.elasticsearch.hello.ConnectElasticsearch;
  2. import com.lun.elasticsearch.hello.ElasticsearchTask;
  3. import org.elasticsearch.action.search.SearchRequest;
  4. import org.elasticsearch.action.search.SearchResponse;
  5. import org.elasticsearch.client.RequestOptions;
  6. import org.elasticsearch.common.unit.Fuzziness;
  7. import org.elasticsearch.index.query.BoolQueryBuilder;
  8. import org.elasticsearch.index.query.QueryBuilders;
  9. import org.elasticsearch.index.query.RangeQueryBuilder;
  10. import org.elasticsearch.index.query.TermsQueryBuilder;
  11. import org.elasticsearch.search.SearchHit;
  12. import org.elasticsearch.search.SearchHits;
  13. import org.elasticsearch.search.aggregations.AggregationBuilders;
  14. import org.elasticsearch.search.builder.SearchSourceBuilder;
  15. import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
  16. import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
  17. import org.elasticsearch.search.sort.SortOrder;
  18. import java.util.Map;
  19. public class QueryDoc {
  20. public static final ElasticsearchTask SEARCH_WITH_GROUP = client -> {
  21. SearchRequest request = new SearchRequest().indices("user");
  22. SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
  23. sourceBuilder.aggregation(AggregationBuilders.terms("age_groupby").field("age"));
  24. //设置请求体
  25. request.source(sourceBuilder);
  26. //3.客户端发送请求,获取响应对象
  27. SearchResponse response = client.search(request, RequestOptions.DEFAULT);
  28. //4.打印响应结果
  29. SearchHits hits = response.getHits();
  30. System.out.println(response);
  31. };
  32. public static void main(String[] args) {
  33. ConnectElasticsearch.connect(SEARCH_WITH_GROUP);
  34. }
  35. }