【Elasticsearch】入门篇

Elasticsearch 入门

前言

简介

Elasticsearch 是一个分布式、RESTful 风格的搜索和数据分析引擎,能够解决不断涌现出的各种用例。作为 Elastic Stck 的核心,它集中存储您的数据,帮助您发现意料之中以及意料之外的情况。

The Elastic Stack,包括 Elasticsearch、Kibana、Beats 和 Logstash(也称为ELK Stack)。

能够安全可靠地获取任何来源、任何格式的数据,然后实时地对数据进行搜索、分析和可视化。

Elaticsearch,简称为 ES,ES 是一个开源的高扩展的分布式全文搜索引擎,是整个 Elastic Sack 技术栈的核心。它可以近乎实时的存储、检索数据;本身扩展性很好,可以扩展到上百台服务器,处理 PB 级别的数据。

全文搜索引擎

Google,百度类的网站搜索,它们都是根据网页中的关键字生成索引,我们在搜索的时候输入关键字,它们会将该关键字即索引匹配到的所有网页返回;还有常见的项目中应用日志的搜索等等。对于这些非结构化的数据文本,关系型数据库搜索不是能很好的支持。

一般传统数据库,全文检索都实现的很鸡肋,因为一般也没人用数据库存文本字段。进行全文检索需要扫描整个表,如果数据量大的话即使对 SQL 的语法优化,也收效甚微。建立了索引,但是维护起来也很麻烦,对于 insert 和 update 操作都会重新构建索引。

基于以上原因可以分析得出,在一些生产环境中,使用常规的搜索方式,性能是非常差的:

  • 搜索的数据对象是大量的非结构化的文本数据。
  • 文件记录量达到数十万或数百万个甚至更多。
  • 支持大量基于交互式文本的查询。
  • 需求非常灵活的全文搜索查询。
  • 对高度相关的搜索结果的有特殊需求,但是没有可用的关系数据库可以满足。
  • 对不同记录类型、非文本数据操作或安全事务处理的需求相对较少的情况。

为了解决结构化数据搜索和非结构化数据搜索性能问题,我们就需要专业,健壮,强大的全

文搜索引擎

这里说到的全文搜索引擎指的是目前广泛应用的主流搜索引擎。

它的工作原理是计算机索引程序通过扫描文章中的每一个词,对每一个词建立一个索引,指明该词在文章中出现的次数和位置,当用户查询时,检索程序就根据事先建立的索引进行查找,并将查找的结果反馈给用户的检索方式。

这个过程类似于通过字典中的检索字表查字的过程。

环境准备

Windows 版

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

  • 解压后,进入 bin 文件目录,点击 elasticsearch.bat 文件启动 ES 服务。
目录 含义
bin 可执行脚本目录
config 配置目录
jdk 内置 JDK 目录
lib 类库
logs 日志目录
modules 模块目录
plugins 插件目录

注意:

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

打开浏览器,输入地址:http://localhost:9200,测试返回结果,返回结果如下:

  • 正常有返回结果即可
json 复制代码
{
  "name": "CHENMENG",
  "cluster_name": "elasticsearch",
  "cluster_uuid": "kzJynYXKQge03U7WpEu8fg",
  "version": {
    "number": "7.8.0",
    "build_flavor": "default",
    "build_type": "zip",
    "build_hash": "757314695644ea9a1dc2fecd26d1a43856725e65",
    "build_date": "2020-06-14T19:35:50.234439Z",
    "build_snapshot": false,
    "lucene_version": "8.5.1",
    "minimum_wire_compatibility_version": "6.8.0",
    "minimum_index_compatibility_version": "6.0.0-beta1"
  },
  "tagline": "You Know, for Search"
}

倒排索引

正排索引(传统)

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

倒排索引

keyword id
name 1001,1002
zhang 1001

Elasticsearch vs MySQL

Elasticsearch 是面向文档型数据库,一条数据在这里就是一个文档。

为了方便大家理解,我们将 Elasticsearch 里存储文档数据和关系型数据库 MySQL 存储数据的概念进行一个类比:

Elasticsearch MySQL 说明
Cluster 多个数据库实例 整个 Elasticsearch 集群(多个节点)
Index ✅ 更像 Table 一个索引相当于一个"表"
Type(已废弃 表(Table) 旧版本中的 Type 类似于 MySQL 中的表,但 7.x+ 已废弃
Document 行(Row) 存储的每一条数据
Field 列(Column) 每个文档中的属性
Mapping 表结构(Schema) 定义字段类型和结构
Shard 分片机制 类似分库分表中的分片概念
Replica 主从复制 高可用副本机制

DSL 语法

HTTP 操作

http 调试工具准备,例如:postman、apifox、apipost...

curl 也可

1、索引(表)

官方文档:Index APIs | Elasticsearch Guide | Elastic

创建 PUT

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

  • 但在使用上,Elasticsearch 的 Index 更强大、更灵活,比如它是分布式的,可以自带分片、复制、副本等能力,MySQL 表通常没有这些。

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

  • 请求后,服务器返回响应:
json 复制代码
{
    "acknowledged": true,
    "shards_acknowledged": true,
    "index": "shopping"
}
json 复制代码
{
    "error": {
        "root_cause": [
            {
                "type": "resource_already_exists_exception",
                "reason": "index [shopping/Z3ALzZdnQzGEJNoNSEGlvw] already exists",
                "index_uuid": "Z3ALzZdnQzGEJNoNSEGlvw",
                "index": "shopping"
            }
        ],
        "type": "resource_already_exists_exception",
        "reason": "index [shopping/Z3ALzZdnQzGEJNoNSEGlvw] already exists",
        "index_uuid": "Z3ALzZdnQzGEJNoNSEGlvw",
        "index": "shopping"
    },
    "status": 400
}
查询 GET

查看所有索引

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

  • 这里请求路径中的 _cat 表示查看的意思,indices 表示索引,

  • 所以整体含义就是查看当前 ES 服务器中的所有索引,就好像 MySQL 中的 show tables 的感觉,

  • 服务器响应结果如下:

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

响应结果说明:

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

查看单个索引

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

  • url 中 shopping 代表 索引名称

返回结果如下:

json 复制代码
{
    "shopping": {
        "aliases": {},
        "mappings": {},
        "settings": {
            "index": {
                "creation_date": "1744101764908",
                "number_of_shards": "1",
                "number_of_replicas": "1",
                "uuid": "Z3ALzZdnQzGEJNoNSEGlvw",
                "version": {
                    "created": "7080099"
                },
                "provided_name": "shopping"
            }
        }
    }
}
删除 DELETE

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

返回结果如下:

json 复制代码
{
    "acknowledged": true
}

2、文档(行)

这里的文档可以类比为关系型数据库中的表数据,添加的数据格式为 JSON 格式。

创建 POST

向 ES 服务器发 POST 请求:http://127.0.0.1:9200/shopping/_doc,请求体 JSON 内容为:

json 复制代码
{
    "title": "小米手机",
    "category": "小米",
    "images": "http://www.gulixueyuan.com/xm.jpg",
    "price": 3999.00
}

返回结果如下:

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

⚠️注意:

  • 上面的数据创建后,由于没有指定数据唯一性标识(ID),默认情况下, ES 服务器会随机生成一个。

如果想要自定义唯一性标识,需要在创建时指定:http://127.0.0.1:9200/shopping/_doc/1,请求体 JSON 内容为:

json 复制代码
{
    "title": "小米手机",
    "category": "小米",
    "images": "http://www.gulixueyuan.com/xm.jpg",
    "price": 3999.00
}

返回结果如下:

json 复制代码
{
    "_index": "shopping",
    "_type": "_doc",
    "_id": "1",
    "_version": 1,  // 自定义唯一标识
    "result": "created",
    "_shards": {
        "total": 2,
        "successful": 1,
        "failed": 0
    },
    "_seq_no": 1,
    "_primary_term": 1
}
主键查询 GET

返回结果如下:

json 复制代码
{
    "_index": "shopping",
    "_type": "_doc",
    "_id": "1",
    "_version": 1,
    "_seq_no": 1,
    "_primary_term": 1,
    "found": true,
    "_source": {
        "title": "小米手机",
        "category": "小米",
        "images": "http://www.gulixueyuan.com/xm.jpg",
        "price": 3999.00
    }
}

查找不存在的内容

返回结果如下:

json 复制代码
{
    "_index": "shopping",
    "_type": "_doc",
    "_id": "1001",
    "found": false
}
查询索引下所有数据 GET

返回结果如下:

json 复制代码
{
    "took": 384,
    "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": "_doc",
                "_id": "aemnFJYBLUeT2LeerGCL",
                "_score": 1.0,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.gulixueyuan.com/xm.jpg",
                    "price": 3999.00
                }
            },
            {
                "_index": "shopping",
                "_type": "_doc",
                "_id": "1",
                "_score": 1.0,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.gulixueyuan.com/xm.jpg",
                    "price": 3999.00
                }
            }
        ]
    }
}
修改 POST

全量修改

和新增文档一样 ,输入相同的 URL 地址请求,如果请求体变化,会将原有的数据内容覆盖

请求体 JSON 内容为:

json 复制代码
{
    "title": "华为手机",
    "category": "华为",
    "images": "http://www.gulixueyuan.com/hw.jpg",
    "price": 4999.00
}

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

json 复制代码
{
    "_index": "shopping",
    "_type": "_doc",
    "_id": "1",
    "_version": 2,
    "result": "updated", // updated 表示数据被更新
    "_shards": {
        "total": 2,
        "successful": 1,
        "failed": 0
    },
    "_seq_no": 4,
    "_primary_term": 1
}

再次进行主键查询,结果如下:

json 复制代码
{
    "_index": "shopping",
    "_type": "_doc",
    "_id": "1",
    "_version": 2,
    "_seq_no": 4,
    "_primary_term": 1,
    "found": true,
    "_source": {
        "title": "华为手机",
        "category": "华为",
        "images": "http://www.gulixueyuan.com/hw.jpg",
        "price": 4999.00
    }
}

可以看到,修改成功。

局部修改

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

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

请求体 JSON 内容为:

json 复制代码
{
    "doc": {
        "title": "小米手机",
        "category": "小米"
    }
}
删除 DELETE

删除一个文档不会立即从磁盘上移除,它只是被标记成已删除(逻辑删除)。

向 ES 服务器发 DELETE 请求:http://127.0.0.1:9200/shopping/_doc/1

返回结果:

json 复制代码
{
    "_index": "shopping",
    "_type": "_doc",
    "_id": "1", // 对应删除标识
    "_version": 4,
    "result": "deleted", // 表示删除成功
    "_shards": {
        "total": 2,
        "successful": 1,
        "failed": 0
    },
    "_seq_no": 6,
    "_primary_term": 2
}

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

json 复制代码
{
    "_index": "shopping",
    "_type": "_doc",
    "_id": "1",
    "found": false
}

3、映射操作(表结构)

先创建一个索引:

创建映射 PUT
json 复制代码
{
    "properties": {
        "name": {
            "type": "text",
            "index": true
        },
        "sex": {
            "type": "keyword", // 关键词类型,查询的时候不会分词
            "index": true
        },
        "tel": {
            "type": "keyword",
            "index": false // 字段不会被索引,不能用来搜索

        }
    }
}

映射数据说明

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

4、复杂查询

确保索引下有数据

json 复制代码
{
    "took": 661,
    "timed_out": false,
    "_shards": {
        "total": 1,
        "successful": 1,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 3,
            "relation": "eq"
        },
        "max_score": 1.0,
        "hits": [
            {
                "_index": "shopping",
                "_type": "_doc",
                "_id": "psZeGZYBs2T-OKTlWq1C",
                "_score": 1.0,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.gulixueyuan.com/xm.jpg",
                    "price": 3999.00
                }
            },
            {
                "_index": "shopping",
                "_type": "_doc",
                "_id": "p8ZeGZYBs2T-OKTloK3v",
                "_score": 1.0,
                "_source": {
                    "title": "红米手机",
                    "category": "红米",
                    "images": "http://www.gulixueyuan.com/xm.jpg",
                    "price": 1999.00
                }
            },
            {
                "_index": "shopping",
                "_type": "_doc",
                "_id": "qMZfGZYBs2T-OKTlDK1W",
                "_score": 1.0,
                "_source": {
                    "title": "华为手机",
                    "category": "华为",
                    "images": "http://www.gulixueyuan.com/xm.jpg",
                    "price": 5999.00
                }
            }
        ]
    }
}
URL 带参查询

查找 category 为小米的文档

向 ES 服务器发 GET 请求:http://127.0.0.1:9200/shopping/_search?q=category:小米,返回结果如下:

  • 可以看出来,会自动进行分词查询 ,即会查出 category 包含 的所有数据
json 复制代码
{
    "took": 9,
    "timed_out": false,
    "_shards": {
        "total": 1,
        "successful": 1,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 2,
            "relation": "eq"
        },
        "max_score": 2.5700645,
        "hits": [
            {
                "_index": "shopping",
                "_type": "_doc",
                "_id": "psZeGZYBs2T-OKTlWq1C",
                "_score": 2.5700645,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.gulixueyuan.com/xm.jpg",
                    "price": 3999.00
                }
            },
            {
                "_index": "shopping",
                "_type": "_doc",
                "_id": "p8ZeGZYBs2T-OKTloK3v",
                "_score": 1.0296195,
                "_source": {
                    "title": "红米手机",
                    "category": "红米",
                    "images": "http://www.gulixueyuan.com/xm.jpg",
                    "price": 1999.00
                }
            }
        ]
    }
}
请求体带参查询

URL 带参数形式查询,这很容易让不善者心怀恶意,或者参数值出现中文会出现乱码情况。

为了避免这些情况,我们可用使用带 JSON 请求体请求进行查询。

接下带 JSON 请求体,还是查找 category 为小米的文档

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

json 复制代码
{
    "query": {
        "match": {
            "category": "小米"
        }
    }
}

返回结果如下:

json 复制代码
{
    "took": 790,
    "timed_out": false,
    "_shards": {
        "total": 1,
        "successful": 1,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 2,
            "relation": "eq"
        },
        "max_score": 2.5700645,
        "hits": [
            {
                "_index": "shopping",
                "_type": "_doc",
                "_id": "psZeGZYBs2T-OKTlWq1C",
                "_score": 2.5700645,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.gulixueyuan.com/xm.jpg",
                    "price": 3999.00
                }
            },
            {
                "_index": "shopping",
                "_type": "_doc",
                "_id": "p8ZeGZYBs2T-OKTloK3v",
                "_score": 1.0296195,
                "_source": {
                    "title": "红米手机",
                    "category": "红米",
                    "images": "http://www.gulixueyuan.com/xm.jpg",
                    "price": 1999.00
                }
            }
        ]
    }
}
查询所有文档(请求体)

查找所有文档内容,也可以这样,

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

  • 不带也是同样的效果
json 复制代码
{
    "query": {
        "match_all": {}
    }
}
查询指定字段

如果你想查询指定字段

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

  • 比如,只查询 title 字段
json 复制代码
{
    "query": {
        "match_all": {}
    },
    "_source": [
        "title"
    ]
}

返回结果如下:

json 复制代码
{
    "took": 53,
    "timed_out": false,
    "_shards": {
        "total": 1,
        "successful": 1,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 3,
            "relation": "eq"
        },
        "max_score": 1.0,
        "hits": [
            {
                "_index": "shopping",
                "_type": "_doc",
                "_id": "psZeGZYBs2T-OKTlWq1C",
                "_score": 1.0,
                "_source": {
                    "title": "小米手机"
                }
            },
            {
                "_index": "shopping",
                "_type": "_doc",
                "_id": "p8ZeGZYBs2T-OKTloK3v",
                "_score": 1.0,
                "_source": {
                    "title": "红米手机"
                }
            },
            {
                "_index": "shopping",
                "_type": "_doc",
                "_id": "qMZfGZYBs2T-OKTlDK1W",
                "_score": 1.0,
                "_source": {
                    "title": "华为手机"
                }
            }
        ]
    }
}
分页查询
  • from:当前页的起始索引,默认从 0 开始。from = (pageNum - 1) * size
  • size:每页显示多少条

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

json 复制代码
{
    "query": {
        "match_all": {}
    },
    "from": 0,
    "size": 2
}

返回结果如下:

json 复制代码
{
    "took": 113,
    "timed_out": false,
    "_shards": {
        "total": 1,
        "successful": 1,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 3,
            "relation": "eq"
        },
        "max_score": 1.0,
        "hits": [
            {
                "_index": "shopping",
                "_type": "_doc",
                "_id": "psZeGZYBs2T-OKTlWq1C",
                "_score": 1.0,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.gulixueyuan.com/xm.jpg",
                    "price": 3999.00
                }
            },
            {
                "_index": "shopping",
                "_type": "_doc",
                "_id": "p8ZeGZYBs2T-OKTloK3v",
                "_score": 1.0,
                "_source": {
                    "title": "红米手机",
                    "category": "红米",
                    "images": "http://www.gulixueyuan.com/xm.jpg",
                    "price": 1999.00
                }
            }
        ]
    }
}
排序查询
json 复制代码
{
    "query": {
        "match_all": {}
    },
    "sort": {
        "price": {
            "order": "desc"
        }
    }
}

返回结果如下:

json 复制代码
{
    "took": 298,
    "timed_out": false,
    "_shards": {
        "total": 1,
        "successful": 1,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 3,
            "relation": "eq"
        },
        "max_score": null,
        "hits": [
            {
                "_index": "shopping",
                "_type": "_doc",
                "_id": "qMZfGZYBs2T-OKTlDK1W",
                "_score": null,
                "_source": {
                    "title": "华为手机",
                    "category": "华为",
                    "images": "http://www.gulixueyuan.com/xm.jpg",
                    "price": 5999.00
                },
                "sort": [
                    5999.0
                ]
            },
            {
                "_index": "shopping",
                "_type": "_doc",
                "_id": "psZeGZYBs2T-OKTlWq1C",
                "_score": null,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.gulixueyuan.com/xm.jpg",
                    "price": 3999.00
                },
                "sort": [
                    3999.0
                ]
            },
            {
                "_index": "shopping",
                "_type": "_doc",
                "_id": "p8ZeGZYBs2T-OKTloK3v",
                "_score": null,
                "_source": {
                    "title": "红米手机",
                    "category": "红米",
                    "images": "http://www.gulixueyuan.com/xm.jpg",
                    "price": 1999.00
                },
                "sort": [
                    1999.0
                ]
            }
        ]
    }
}
组合查询
  • bool 把各种其它查询通过 must(必须)、must not(必须不)、should(应该) 的方式进行组合

must 与查询

json 复制代码
{
    "query": {
        "bool": {
            "must": [
                {
                    "match": {
                        "category": "小米"
                    }
                },
                {
                    "match": {
                        "price": 3999.00
                    }
                }
            ]
        }
    }
}

返回结果如下:

json 复制代码
{
    "took": 119,
    "timed_out": false,
    "_shards": {
        "total": 1,
        "successful": 1,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 1,
            "relation": "eq"
        },
        "max_score": 2.89712,
        "hits": [
            {
                "_index": "shopping",
                "_type": "_doc",
                "_id": "psZeGZYBs2T-OKTlWq1C",
                "_score": 2.89712,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.gulixueyuan.com/xm.jpg",
                    "price": 3999.00
                }
            }
        ]
    }
}

should 或查询

json 复制代码
{
    "query": {
        "bool": {
            "should": [
                {
                    "match": {
                        "category": "小米"
                    }
                },
                {
                    "match": {
                        "category": "华为"
                    }
                }
            ]
        }
    }
}

返回结果如下:

  • 字段不是关键词类型,会分词查询
json 复制代码
{
    "took": 13,
    "timed_out": false,
    "_shards": {
        "total": 1,
        "successful": 1,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 3,
            "relation": "eq"
        },
        "max_score": 1.89712,
        "hits": [
            {
                "_index": "shopping",
                "_type": "_doc",
                "_id": "psZeGZYBs2T-OKTlWq1C",
                "_score": 1.89712,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.gulixueyuan.com/xm.jpg",
                    "price": 3999.00
                }
            },
            {
                "_index": "shopping",
                "_type": "_doc",
                "_id": "qMZfGZYBs2T-OKTlDK1W",
                "_score": 1.3862942,
                "_source": {
                    "title": "华为手机",
                    "category": "华为",
                    "images": "http://www.gulixueyuan.com/xm.jpg",
                    "price": 5999.00
                }
            },
            {
                "_index": "shopping",
                "_type": "_doc",
                "_id": "p8ZeGZYBs2T-OKTloK3v",
                "_score": 0.6931471,
                "_source": {
                    "title": "红米手机",
                    "category": "红米",
                    "images": "http://www.gulixueyuan.com/xm.jpg",
                    "price": 1999.00
                }
            }
        ]
    }
}
范围查询

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

操作符 说明
gt 大于 >
gte 大于等于 >=
lt 小于 <
lte 小于等于 <=
json 复制代码
{
    "query": {
        "bool": {
            "should": [
                {
                    "match": {
                        "category": "小米"
                    }
                },
                {
                    "match": {
                        "category": "华为"
                    }
                }
            ],
            "filter": {
                "range": {
                    "price": {
                        "gt": 4000
                    }
                }
            }
        }
    }
}

返回结果如下:

json 复制代码
{
    "took": 40,
    "timed_out": false,
    "_shards": {
        "total": 1,
        "successful": 1,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 1,
            "relation": "eq"
        },
        "max_score": 1.3862942,
        "hits": [
            {
                "_index": "shopping",
                "_type": "_doc",
                "_id": "qMZfGZYBs2T-OKTlDK1W",
                "_score": 1.3862942,
                "_source": {
                    "title": "华为手机",
                    "category": "华为",
                    "images": "http://www.gulixueyuan.com/xm.jpg",
                    "price": 5999.00
                }
            }
        ]
    }
}
完全匹配

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

json 复制代码
{
    "query": {
        "match_phrase": {
            "category": "小米"
        }
    }
}

返回结果如下:

  • 不会进行分词查询
json 复制代码
{
    "took": 65,
    "timed_out": false,
    "_shards": {
        "total": 1,
        "successful": 1,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 1,
            "relation": "eq"
        },
        "max_score": 1.89712,
        "hits": [
            {
                "_index": "shopping",
                "_type": "_doc",
                "_id": "psZeGZYBs2T-OKTlWq1C",
                "_score": 1.89712,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.gulixueyuan.com/xm.jpg",
                    "price": 3999.00
                }
            }
        ]
    }
}
高亮查询

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

json 复制代码
{
    "query": {
        "match_phrase": {
            "category": "米"
        }
    },
    "highlight": {
        "fields": {
            "category": {} // 高亮这字段
        }
    }
}

返回结果如下:

json 复制代码
{
    "took": 403,
    "timed_out": false,
    "_shards": {
        "total": 1,
        "successful": 1,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 2,
            "relation": "eq"
        },
        "max_score": 0.6931471,
        "hits": [
            {
                "_index": "shopping",
                "_type": "_doc",
                "_id": "psZeGZYBs2T-OKTlWq1C",
                "_score": 0.6931471,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.gulixueyuan.com/xm.jpg",
                    "price": 3999.00
                },
                "highlight": {
                    "category": [
                        "小<em>米</em>"
                    ]
                }
            },
            {
                "_index": "shopping",
                "_type": "_doc",
                "_id": "p8ZeGZYBs2T-OKTloK3v",
                "_score": 0.6931471,
                "_source": {
                    "title": "红米手机",
                    "category": "红米",
                    "images": "http://www.gulixueyuan.com/xm.jpg",
                    "price": 1999.00
                },
                "highlight": {
                    "category": [
                        "红<em>米</em>"
                    ]
                }
            }
        ]
    }
}
聚合查询

分组查询示例

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

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

json 复制代码
{
    "aggs": { //聚合操作
        "price_group": { //名称,随意起名
            "terms": { //分组
                "field": "price" //分组字段
            }
        }
    }
}

返回结果如下:

json 复制代码
{
    "took": 1309,
    "timed_out": false,
    "_shards": {
        "total": 1,
        "successful": 1,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 4,
            "relation": "eq"
        },
        "max_score": 1.0,
        "hits": [
            {
                "_index": "shopping",
                "_type": "_doc",
                "_id": "psZeGZYBs2T-OKTlWq1C",
                "_score": 1.0,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.gulixueyuan.com/xm.jpg",
                    "price": 3999.00
                }
            },
            {
                "_index": "shopping",
                "_type": "_doc",
                "_id": "p8ZeGZYBs2T-OKTloK3v",
                "_score": 1.0,
                "_source": {
                    "title": "红米手机",
                    "category": "红米",
                    "images": "http://www.gulixueyuan.com/xm.jpg",
                    "price": 1999.00
                }
            },
            {
                "_index": "shopping",
                "_type": "_doc",
                "_id": "qMZfGZYBs2T-OKTlDK1W",
                "_score": 1.0,
                "_source": {
                    "title": "华为手机",
                    "category": "华为",
                    "images": "http://www.gulixueyuan.com/xm.jpg",
                    "price": 5999.00
                }
            },
            {
                "_index": "shopping",
                "_type": "_doc",
                "_id": "wcbjGZYBs2T-OKTlL62H",
                "_score": 1.0,
                "_source": {
                    "title": "小米手机",
                    "category": "小米",
                    "images": "http://www.gulixueyuan.com/xm.jpg",
                    "price": 3999.00
                }
            }
        ]
    },
    "aggregations": {
        "price_group": {
            "doc_count_error_upper_bound": 0,
            "sum_other_doc_count": 0,
            "buckets": [
                {
                    "key": 3999.0,
                    "doc_count": 2
                },
                {
                    "key": 1999.0,
                    "doc_count": 1
                },
                {
                    "key": 5999.0,
                    "doc_count": 1
                }
            ]
        }
    }
}

不返回原始数据写法

上面返回结果会附带原始数据的。若不想要不附带原始数据的结果,可以加多个 size 筛选属性:

json 复制代码
{
    "aggs": {
        "price_group": {
            "terms": {
                "field": "price"
            }
        }
    },
    "size": 0
}

返回结果如下:

json 复制代码
{
    "took": 10,
    "timed_out": false,
    "_shards": {
        "total": 1,
        "successful": 1,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 4,
            "relation": "eq"
        },
        "max_score": null,
        "hits": []
    },
    "aggregations": {
        "price_group": {
            "doc_count_error_upper_bound": 0,
            "sum_other_doc_count": 0,
            "buckets": [
                {
                    "key": 3999.0,
                    "doc_count": 2
                },
                {
                    "key": 1999.0,
                    "doc_count": 1
                },
                {
                    "key": 5999.0,
                    "doc_count": 1
                }
            ]
        }
    }
}

平均值查询示例

json 复制代码
{
    "aggs": {
        "price_avg": { // 名称,随意起名
            "avg": { // 求平均
                "field": "price"
            }
        }
    },
    "size": 0
}

返回结果如下:

json 复制代码
{
    "took": 188,
    "timed_out": false,
    "_shards": {
        "total": 1,
        "successful": 1,
        "skipped": 0,
        "failed": 0
    },
    "hits": {
        "total": {
            "value": 4,
            "relation": "eq"
        },
        "max_score": null,
        "hits": []
    },
    "aggregations": {
        "price_avg": {
            "value": 3999.0
        }
    }
}

学习参考

相关推荐
凉白开33817 分钟前
Spark-Streaming核心编程
大数据·分布式·spark
lilye662 小时前
精益数据分析(17/126):精益画布与创业方向抉择
大数据·数据挖掘·数据分析
思通数科AI全行业智能NLP系统5 小时前
AI视频技术赋能幼儿园安全——教师离岗报警系统的智慧守护
大数据·人工智能·安全·目标检测·目标跟踪·自然语言处理·ocr
Gadus_7 小时前
Elasticsearch性能优化实践
大数据·elasticsearch·搜索引擎·性能优化
riveting9 小时前
SD2351核心板:重构AI视觉产业价值链的“超级节点”
大数据·linux·图像处理·人工智能·重构·智能硬件
欧先生^_^10 小时前
Spark 的一些典型应用场景及具体示例
大数据·分布式·spark
八股文领域大手子11 小时前
如何给GitHub项目提PR(踩坑记录
大数据·elasticsearch·github
爱吃龙利鱼11 小时前
elk中kibana一直处于可用和降级之间且es群集状态并没有问题的解决方法
大数据·elk·elasticsearch
腾讯云大数据11 小时前
腾讯云ES一站式RAG方案获信通院“开源大模型+软件创新应用”精选案例奖
大数据·elasticsearch·开源·云计算·腾讯云