es的安装可以看我另一篇博客 点我传送
文章内容较长,建议左侧下滑看目录,跳转想看的地方
Elasticsearch具备以下特点:
- 分布式,无需人工搭建集群(solr就需要人为配置,使用Zookeeper作为注册中心)
- Restful风格,一切API都遵循Rest原则,容易上手
- 近实时搜索,数据更新在Elasticsearch中几乎是完全同步的
基本概念
索引(indices)-------------------------Databases 数据库
类型(type)-----------------------------Table 数据表
文档(Document)---------------------Row 行
字段(Field)----------------------------Columns 列
概念 | 说明 |
---|---|
索引库(indices) | indices是index的复数,代表许多的索引 |
类型(type) | 类型是模拟mysql中的table概念,一个索引库下可以有不同类型的索引,比如商品索引,订单索引,其数据格式不同。不过这会导致索引库混乱,因此在7.x移除了 |
文档(document) | 存入索引库原始的数据。比如每一条信息,就是一个文档 |
字段(field) | 文档中的属性 |
映射配置(mappings) | 字段的数据类型、属性、是否索引、是否存储等特性 |
要注意的是:Elasticsearch本身就是分布式的,因此即便只有一个节点,Elasticsearch默认也会对数据进行分片和副本操作,当向集群添加新数据时,数据也会在新加入的节点中进行平衡。
索引
创建索引
settings:索引库的设置
- number_of_shards:分片数量
- number_of_replicas:副本数量
查看索引设置:GET 索引库名
删除索引:DELETE 索引库名
查看所有索引:/cat/indices?v
映射
语法:
PUT /索引库名/_mapping/类型名称
{
"properties": {
"字段名": {
"type": "类型",
"index": true,
"store": true,
"analyzer": "分词器"
}
}
}
类型名称:就是前面将的type的概念,类似于数据库中的不同表
字段名:任意填写 ,可以指定许多属性,例如:
- type:类型
- text:⽤于全⽂索引,搜索时会自动使用分词器进⾏分词再匹配,不可参与聚合
- keyword:不分词,搜索时需要匹配完整的值
- 整型: byte,short,integer,long
- 浮点型: float, half_float, scaled_float,double
- date:固定格式的字符串(如:“2020-04-18”、“2020/04/18 09:00:00”) 时间戳(如:1631896870000)
- boolean:值为true、false
- binary:二进制,会把值当做经过 base64 编码的字符串,默认不存储,且不可搜索
- index:是否索引,默认为true
- true:字段会被索引,则可以用来进行搜索。默认值就是true
- false:字段不会被索引,不能用来搜索
- store:是否存储,默认为false
是否将数据进行额外存储。Elasticsearch中,即便store设置为false,也可以搜索到结果。
原因是Elasticsearch在创建文档索引时,会将文档中的原始数据备份,保存到一个叫做_source的属性中。而且可以通过过滤_source来选择哪些要显示,哪些不显示。而如果设置store为true,就会在_source以外额外存储一份数据 - analyzer:分词器
Elasticsearch非常智能,如果给索引库设置任何mapping映射,它也可以根据输入的数据来判断类型,动态添加数据映射。
新增数据
语法:
POST /索引库名/类型名
{
"key":"value"
}
以上新增数据的_id是自动生成的,若想自定义id,如下:
POST /索引库名/类型/id值
{
...
}
修改数据
语法:
POST /索引库名/类型名/id值
{
"key":"value"
}
- id对应文档存在,修改
- id对应文档不存在,新增
删除数据
语法:
DELETE /索引库名/类型名/id值
基本查询
语法:
GET /索引库名/_search
{
"query":{
"查询类型":{
"查询条件":"查询条件值"
}
}
}
查询类型:match_all
, match
,term
, range
等等
-
match_all(查询所有)
GET /索引库/_search { "query":{ "match_all": {} } }
查询结果:
{ "took": 0, "timed_out": false, "_shards": { "total": 5, "successful": 5, "skipped": 0, "failed": 0 }, "hits": { "total": 6, "max_score": 1, "hits": [ { "_index": "threats", "_type": "threats", "_id": "AXZqaegBjxrftZLkfcMC", "_score": 1, "_source": { "grade": "info", "timeval": 1608007101, "cid": 6 } } ] } }
- took:查询花费时间,单位是毫秒
- time_out:是否超时
- _shards:分片信息
- hits:搜索结果总览对象
- total:搜索到的总条数
- max_score:所有结果中文档得分的最高分
- hits:搜索结果的文档对象数组,每个元素是一条搜索到的文档信息
- _index:索引库
- _type:文档类型
- _id:文档id
- _score:文档得分
- _source:文档的源数据
-
match(匹配查询)
match
类型查询,会把查询条件进行分词,然后进行查询,多个词条之间是or的关系GET /索引库/_search { "query":{ "match": { "name":"张三李四" } } }
若name按照 张三、李四 这样分词,会搜索出包含张三、包含李四、包含张三李四的数据
某些情况下,需要更精确查找,希望这个关系变成
and
,可以这样做:GET /索引库/_search { "query":{ "match":{ "title":{"query":"张三李四","operator":"and"} } } }
这样就只会搜索出张三李四的数据
某些情况下,希望这个关系变成在
or
和and
之间,可以这样做:GET /索引库/_search { "query":{ "match":{ "name":{"query":"张三李四王五","minimum_should_match":"75%"} } } }
若name按照 张三、李四、王五 分成三个词,但是查询希望一次能匹配到至少两个词 ,这时候只用operator满足不了了,name分成3个词,把minimum_should_match设置成75%,3*75%≈2,于是就会搜索至少能满足两个词的数据
-
multi_match(多字段查询)
与match
类似,不同的是它可以在多个字段中查询GET /索引库/_search { "query":{ "multi_match": { "query": "张三", "fields": [ "title", "name" ] } } }
-
term(词条匹配)
用于精确值 匹配,这些精确值可能是数字、时间、布尔或者那些未分词的字符串GET /索引库/_search { "query":{ "term":{ "name":"张三" } } }
-
terms(多词条精确匹配)
GET /索引库/_search { "query":{ "terms":{ "name":["张三","李四"] } } }
搜索条件
-
结果过滤
- 1.指定需要显示的字段
GET /索引库/_search { "_source": ["name","age"], "query":{ "term":{ "age":23 } } }
- 2.指定includes和excludes
GET /索引库/_search { "_source": { "includes":["name","age"] }, "query":{ "term":{ "age":23 } } } GET /索引库/_search { "_source": { "excludes":["age"] }, "query":{ "term":{ "age":23 } } }
- includes:指定想要显示的字段
- excludes:指定不想要显示的字段
- 1.指定需要显示的字段
-
boost
搜索条件的权重,如下,title含java的会优先比含python的先搜索出来{ "query":{ "bool":{ "should":[ { "match": { "title": { "query": "java", "boost": 5 } } },{ "match": { "title": { "query": "python" "boost": 4 } } } ] } } }
-
bool(布尔组合)
bool
把各种其它查询通过must
(与)、must_not
(非)、should
(或)的方式进行组合GET /索引库/_search { "query":{ "bool":{ "must": { "match": { "name": "张三" }}, "must_not": { "match": { "age": "23" }}, "should": { "match": { "sex": "男" }} } } }
-
range(范围查询)
GET /索引库/_search { "query":{ "range": { "age": { "gte": 23 "lt": 35 } } } }
操作符 说明 gt 大于 gte 大于等于 lt 小于 lte 小于等于 -
fuzzy(模糊查询)
fuzzy
查询是term
查询的模糊等价。它允许用户搜索词条与实际词条的拼写出现偏差,但是偏差的编辑距离不得超过2:GET /索引库/_search { "query": { "fuzzy": { "title": "appla" } } } # 上面的查询,能查询到apple手机 # 可以通过`fuzziness`来指定允许的编辑距离: GET /索引库/_search { "query": { "fuzzy": { "title": { "value":"appla", "fuzziness":1 } } } }
-
filter(过滤)
所有的查询都会影响到文档的评分及排名。如果需要在查询结果中进行过滤,并且不希望过滤条件影响评分,那么就不要把过滤条件作为查询条件来用。而是使用filter
方式:GET /索引库/_search { "query":{ "bool":{ "must":{ "match": { "name": "张三" }}, "filter":{ "range":{"age":{"gt":23,"lt":35}} } } } }
注:
filter
中还可以再次进行bool
组合条件过滤。如果一次查询只有过滤,没有查询条件,不希望进行评分,可以使用
constant_score
取代只有 filter 语句的 bool 查询。在性能上是完全相同的,但对于提高查询简洁性和清晰度有很大帮助。GET /索引库/_search { "query":{ "constant_score": { "filter": { "range":{"age":{"gt":23,"lt":35}} } } }
-
排序
GET /索引库/_search { "query":{ "bool":{ "must":{ "match": { "name": "张三" }}, "filter":{ "range":{"age":{"gt":23,"lt":35}} } } }, "sort": [ { "age": { "order": "asc" }}, { "_score": { "order": "desc" }} ] }
聚合aggregations
Elasticsearch中的聚合,包含多种类型,最常用的两种,一个叫桶
,一个叫度量
-
bucket(桶)
桶的作用,是按照某种方式对数据进行分组,每一组数据在ES中称为一个桶
Elasticsearch中提供的划分桶的方式有很多:- Date Histogram Aggregation:根据日期阶梯分组,例如给定阶梯为周,会自动每周分为一组
- Histogram Aggregation:根据数值阶梯分组,与日期类似
- Terms Aggregation:根据词条内容分组,词条内容完全匹配的为一组
- Range Aggregation:数值和日期的范围分组,指定开始和结束,然后按段分组
- ……
bucket aggregations 只负责对数据进行分组,并不进行计算,因此往往bucket中往往会嵌套另一种聚合:metrics aggregations即度量
-
metrics(度量)
分组完成以后,一般会对组中的数据进行聚合运算,例如求平均值、最大、最小、求和等,这些在ES中称为度量
比较常用的一些度量聚合方式:- Avg Aggregation:求平均值
- Max Aggregation:求最大值
- Min Aggregation:求最小值
- Percentiles Aggregation:求百分比
- Stats Aggregation:同时返回avg、max、min、sum、count等
- Sum Aggregation:求和
- Top hits Aggregation:求前几
- Value Count Aggregation:求总数
- ……
-
桶和度量的例子
创建索引:PUT /cars { "settings": { "number_of_shards": 1, "number_of_replicas": 0 }, "mappings": { "transactions": { "properties": { "color": { "type": "keyword" }, "make": { "type": "keyword" } } } } }
注:在ES中,需要进行聚合、排序、过滤的字段其处理方式比较特殊,因此不能被分词。这里我将color和make这两个文字类型的字段设置为keyword类型,这个类型不会被分词,将来就可以参与聚合
导入数据:
POST /cars/transactions/_bulk { "index": {}} { "price" : 10000, "color" : "red", "make" : "honda", "sold" : "2020-10-28" } { "index": {}} { "price" : 20000, "color" : "red", "make" : "honda", "sold" : "2020-11-05" } { "index": {}} { "price" : 30000, "color" : "green", "make" : "ford", "sold" : "2020-05-18" } { "index": {}} { "price" : 15000, "color" : "blue", "make" : "toyota", "sold" : "2020-07-02" } { "index": {}} { "price" : 12000, "color" : "green", "make" : "toyota", "sold" : "2020-08-19" } { "index": {}} { "price" : 20000, "color" : "red", "make" : "honda", "sold" : "2020-11-05" } { "index": {}} { "price" : 80000, "color" : "red", "make" : "bmw", "sold" : "2020-01-01" } { "index": {}} { "price" : 25000, "color" : "blue", "make" : "ford", "sold" : "2020-02-12" }
聚合为桶:
首先,按照 汽车的颜色color来
划分桶
:GET /cars/_search { "size" : 0, "aggs" : { "popular_colors" : { "terms" : { "field" : "color" } } } }
- size: 查询条数,这里设置为0,搜索到的数据,只关心聚合结果,提高效率
- aggs:声明这是一个聚合查询,是aggregations的缩写
- popular_colors:给这次聚合起一个名字,任意。
- terms:划分桶的方式,这里是根据词条划分
- field:划分桶的字段
- terms:划分桶的方式,这里是根据词条划分
- popular_colors:给这次聚合起一个名字,任意。
结果:
{ "took": 1, "timed_out": false, "_shards": { "total": 1, "successful": 1, "skipped": 0, "failed": 0 }, "hits": { "total": 8, "max_score": 0, "hits": [] }, "aggregations": { "popular_colors": { "doc_count_error_upper_bound": 0, "sum_other_doc_count": 0, "buckets": [ { "key": "red", "doc_count": 4 }, { "key": "blue", "doc_count": 2 }, { "key": "green", "doc_count": 2 } ] } } }
- hits:查询结果为空,因为我们设置了size为0
- aggregations:聚合的结果
- popular_colors:我们定义的聚合名称
- buckets:查找到的桶,每个不同的color字段值都会形成一个桶
- key:这个桶对应的color字段的值
- doc_count:这个桶中的文档数量
桶内度量
求每种颜色价格平均值的度量:GET /cars/_search { "size" : 0, "aggs" : { "popular_colors" : { "terms" : { "field" : "color" }, "aggs":{ "avg_price": { "avg": { "field": "price" } } } } } }
结果:
... "aggregations": { "popular_colors": { "doc_count_error_upper_bound": 0, "sum_other_doc_count": 0, "buckets": [ { "key": "red", "doc_count": 4, "avg_price": { "value": 32500 } }, { "key": "blue", "doc_count": 2, "avg_price": { "value": 20000 } }, { "key": "green", "doc_count": 2, "avg_price": { "value": 21000 } } ] } } ...
桶内嵌套桶
统计每种颜色的汽车中,分别属于哪个制造商:GET /cars/_search { "size" : 0, "aggs" : { "popular_colors" : { "terms" : { "field" : "color" }, "aggs":{ "avg_price": { "avg": { "field": "price" } }, "maker":{ "terms":{ "field":"make" } } } } } }
结果:
... {"aggregations": { "popular_colors": { "doc_count_error_upper_bound": 0, "sum_other_doc_count": 0, "buckets": [ { "key": "red", "doc_count": 4, "maker": { "doc_count_error_upper_bound": 0, "sum_other_doc_count": 0, "buckets": [ { "key": "honda", "doc_count": 3 }, { "key": "bmw", "doc_count": 1 } ] }, "avg_price": { "value": 32500 } }, { "key": "blue", "doc_count": 2, "maker": { "doc_count_error_upper_bound": 0, "sum_other_doc_count": 0, "buckets": [ { "key": "ford", "doc_count": 1 }, { "key": "toyota", "doc_count": 1 } ] }, "avg_price": { "value": 20000 } }, { "key": "green", "doc_count": 2, "maker": { "doc_count_error_upper_bound": 0, "sum_other_doc_count": 0, "buckets": [ { "key": "ford", "doc_count": 1 }, { "key": "toyota", "doc_count": 1 } ] }, "avg_price": { "value": 21000 } } ] } } } ...
-
阶梯分桶Histogram
histogram是把数值类型的字段,按照一定的阶梯大小进行分组。需要指定一个阶梯值(interval)来划分阶梯大小。
对汽车的价格进行分组,指定间隔interval为5000:GET /cars/_search { "size":0, "aggs":{ "price":{ "histogram": { "field": "price", "interval": 5000 } } } }
结果:
... "aggregations": { "price": { "buckets": [ { "key": 10000, "doc_count": 2 }, { "key": 15000, "doc_count": 1 }, { "key": 20000, "doc_count": 2 }, { "key": 25000, "doc_count": 1 }, { "key": 30000, "doc_count": 1 }, { "key": 35000, "doc_count": 0 }, { "key": 40000, "doc_count": 0 }, { "key": 45000, "doc_count": 0 }, { "key": 50000, "doc_count": 0 }, { "key": 55000, "doc_count": 0 }, { "key": 60000, "doc_count": 0 }, { "key": 65000, "doc_count": 0 }, { "key": 70000, "doc_count": 0 }, { "key": 75000, "doc_count": 0 }, { "key": 80000, "doc_count": 1 } ] } }
中间有大量的文档数量为0 的桶,看起来很丑。
可以增加一个参数min_doc_count为1,来约束最少文档数量为1,这样文档数量为0的桶会被过滤:
GET /cars/_search { "size":0, "aggs":{ "price":{ "histogram": { "field": "price", "interval": 5000, "min_doc_count": 1 } } } }
结果:
... "aggregations": { "price": { "buckets": [ { "key": 10000, "doc_count": 2 }, { "key": 15000, "doc_count": 1 }, { "key": 20000, "doc_count": 2 }, { "key": 25000, "doc_count": 1 }, { "key": 30000, "doc_count": 1 }, { "key": 80000, "doc_count": 1 } ] } }
ik分词器
将ik分词器的压缩包放在elasticsearch下的plugins下,解压重启elasticsearch即可
Kibana
是一个基于Node.js的Elasticsearch索引库数据统计工具,可以利用Elasticsearch的聚合功能,生成各种图表,如柱形图,线状图,饼图等。提供了操作Elasticsearch索引数据的控制台,并且提供了一定的API提示
若连接远程elasticsearch,进入安装目录下的config目录,修改kibana.yml文件:
# 改成远程elasticsearch的IP和端口
elasticsearch.url: "http://192.168.0.150:9200"