1.1基本概念
Elasticsearch也是基于Lucene的全文檢索庫,本質也是存儲數據,很多概念與MySQL類似的。
對比關系:
索引(indices)--------------------------------Databases 數據庫
? 類型(type)-----------------------------Table 數據表
? 文檔(Document)----------------Row 行
? 字段(Field)-------------------Columns 列
詳細說明:
概念 | 說明 |
---|---|
索引庫(indices) | indices是index的復數,代表許多的索引, |
類型(type) | 類型是模擬mysql中的table概念,一個索引庫下可以有不同類型的索引,比如商品索引,訂單索引,其數據格式不同。不過這會導致索引庫混亂,因此未來版本中會移除這個概念 |
文檔(document) | 存入索引庫原始的數據。比如每一條商品信息,就是一個文檔 |
字段(field) | 文檔中的屬性 |
映射配置(mappings) | 字段的數據類型、屬性、是否索引、是否存儲等特性 |
- 索引集(Indices,index的復數):邏輯上的完整索引
- 分片(shard):數據拆分后的各個部分
- 副本(replica):每個分片的復制
要注意的是:Elasticsearch本身就是分布式的,因此即便你只有一個節點,Elasticsearch默認也會對你的數據進行分片和副本操作,當你向集群添加新數據時,數據也會在新加入的節點中進行平衡。
1.2.創建索引
1.2.1.語法
Elasticsearch采用Rest風格API,因此其API就是一次http請求,你可以用任何工具發起http請求
創建索引的請求格式:
請求方式:PUT
請求路徑:/索引庫名
-
請求參數:json格式:
{ "settings": { "number_of_shards": 3, "number_of_replicas": 2 } }
- settings:索引庫的設置
- number_of_shards:分片數量
- number_of_replicas:副本數量
- settings:索引庫的設置
1.2.2.測試
我們用kibana來試試
可以看到索引創建成功了。
1.2.3.使用posman創建
也可以創建成功,但是沒有使用kibana來的方便
1.3.查看索引設置
語法
Get請求可以幫我們查看索引信息,格式:
GET /索引庫名
或者,我們可以使用*來查詢所有索引庫配置
1.4.刪除索引
刪除索引使用DELETE請求
語法
DELETE /索引庫名
2.5.映射配置
索引有了,接下來肯定是添加數據。但是,在添加數據之前必須定義映射。
什么是映射?
? 映射是定義文檔的過程,文檔包含哪些字段,這些字段是否保存,是否索引,是否分詞等
只有配置清楚,Elasticsearch才會幫我們進行索引庫的創建
2.5.1.創建映射字段
語法
請求方式依然是PUT
PUT /索引庫名/_mapping/類型名稱
{
"properties": {
"字段名": {
"type": "類型",
"index": true,
"store": true,
"analyzer": "分詞器"
}
}
}
- 類型名稱:就是前面將的type的概念,類似于數據庫中的不同表
字段名:任意填寫 ,可以指定許多屬性,例如: - type:類型,可以是text、long、short、date、integer、object等
- index:是否索引,默認為true
- store:是否存儲,默認為false
- analyzer:分詞器,這里的
ik_max_word
即使用ik分詞器
示例
發起請求:
PUT testindex/_mapping/goods
{
"properties": {
"title": {
"type": "text",
"analyzer": "ik_max_word"
},
"images": {
"type": "keyword",
"index": "false"
},
"price": {
"type": "float"
}
}
}
響應結果:
{
"acknowledged": true
}
1.5.2.查看映射關系
語法:
GET /索引庫名/_mapping
示例:
GET /testindex/_mapping
響應:
{
"testindex": {
"mappings": {
"goods": {
"properties": {
"images": {
"type": "keyword",
"index": false
},
"price": {
"type": "float"
},
"title": {
"type": "text",
"analyzer": "ik_max_word"
}
}
}
}
}
}
1.5.3.字段屬性詳解
1.5.3.1.type
Elasticsearch中支持的數據類型非常豐富:
我們說幾個關鍵的:
-
String類型,又分兩種:
- text:可分詞,不可參與聚合
- keyword:不可分詞,數據會作為完整字段進行匹配,可以參與聚合
-
Numerical:數值類型,分兩類
- 基本數據類型:long、interger、short、byte、double、float、half_float
- 浮點數的高精度類型:scaled_float
- 需要指定一個精度因子,比如10或100。elasticsearch會把真實值乘以這個因子后存儲,取出時再還原。
-
Date:日期類型
elasticsearch可以對日期格式化為字符串存儲,但是建議我們存儲為毫秒值,存儲為long,節省空間。
1.5.3.2.index
index影響字段的索引情況。
- true:字段會被索引,則可以用來進行搜索。默認值就是true
- false:字段不會被索引,不能用來搜索
index的默認值就是true,也就是說你不進行任何配置,所有字段都會被索引。
但是有些字段是我們不希望被索引的,比如商品的圖片信息,就需要手動設置index為false。
1.5.3.3.store
是否將數據進行額外存儲。
在學習lucene和solr時,我們知道如果一個字段的store設置為false,那么在文檔列表中就不會有這個字段的值,用戶的搜索結果中不會顯示出來。
但是在Elasticsearch中,即便store設置為false,也可以搜索到結果。
原因是Elasticsearch在創建文檔索引時,會將文檔中的原始數據備份,保存到一個叫做_source
的屬性中。而且我們可以通過過濾_source
來選擇哪些要顯示,哪些不顯示。
而如果設置store為true,就會在_source
以外額外存儲一份數據,多余,因此一般我們都會將store設置為false,事實上,store的默認值就是false。
1.6.新增數據
1.6.1.隨機生成id
通過POST請求,可以向一個已經存在的索引庫中添加數據。
語法:
POST /索引庫名/類型名
{
"key":"value"
}
示例:
POST /testindex/goods/
{
"title":"小米手機",
"images":"1,jpg",
"price":111.00
}
響應:
{
"_index": "testindex",
"_type": "goods",
"_id": "AWsS5Neq-k3yg4WVTNnG",
"_version": 1,
"result": "created",
"_shards": {
"total": 2,
"successful": 1,
"failed": 0
},
"created": true
}
通過kibana查看數據:
get _search
{
"query":{
"match_all":{}
}
}
{
"_index": "testindex",
"_type": "goods",
"_id": "AWsS5Neq-k3yg4WVTNnG",
"_version": 1,
"_score": 1,
"_source": {
"title": "小米手機",
"images": "1.jpg",
"price": 111
}
}
-
_source
:源文檔信息,所有的數據都在里面。 -
_id
:這條文檔的唯一標示,與文檔自己的id字段沒有關聯
1.6.2.自定義id
如果我們想要自己新增的時候指定id,可以這么做:
POST /索引庫名/類型/id值
{
...
}
示例:
POST /testindex/goods/2
{
"title":"大米手機",
"images":"2.jpg",
"price":222
}
得到的數據:
{
"_index": "testindex",
"_type": "goods",
"_id": "2",
"_score": 1,
"_source": {
"title": "大米手機",
"images": "2,jpg",
"price": 222
}
}
2.6.3.智能判斷
在學習Solr時我們發現,我們在新增數據時,只能使用提前配置好映射屬性的字段,否則就會報錯。
不過在Elasticsearch中并沒有這樣的規定。
事實上Elasticsearch非常智能,你不需要給索引庫設置任何mapping映射,它也可以根據你輸入的數據來判斷類型,動態添加數據映射。
測試一下:
POST /testindex/goods/3
{
"title":"超米手機",
"images":"3.jpg",
"price":333,
"stock": 200
}
我們額外添加了stock庫存字段。
來看結果:
{
"_index": "testindex",
"_type": "goods",
"_id": "3",
"_version": 1,
"_score": 1,
"_source": {
"title": "超米手機",
"images": "3.jpg",
"price": 333,
"stock": 200
}
}
在看下索引庫的映射關系:
{
"testindex": {
"mappings": {
"goods": {
"properties": {
"images": {
"type": "keyword",
"index": false
},
"price": {
"type": "float"
},
"stock": {
"type": "long"
},
"title": {
"type": "text",
"analyzer": "ik_max_word"
}
}
}
}
}
}
stock和saleable都被成功映射了。
1.7.修改數據
把剛才新增的請求方式改為PUT,就是修改了。不過修改必須指定id,
- id對應文檔存在,則修改
- id對應文檔不存在,則新增
比如,我們把id為3的數據進行修改:
PUT /testindex/goods/3
{
"title":"超大米手機",
"images":"3.jpg",
"price":333,
"stock": 100
}
結果:
{
"took": 17,
"timed_out": false,
"_shards": {
"total": 9,
"successful": 9,
"skipped": 0,
"failed": 0
},
"hits": {
"total": 1,
"max_score": 1,
"hits": [
{
"_index": "testindex",
"_type": "goods",
"_id": "3",
"_score": 1,
"_source": {
"title": "超大米手機",
"images": "3.jpg",
"price": 333,
"stock": 100
}
}
]
}
}
2.8.刪除數據
刪除使用DELETE請求,同樣,需要根據id進行刪除:
語法
DELETE /索引庫名/類型名/id值
3.查詢
我們從4塊來講查詢:
- 基本查詢
-
_source
過濾 - 結果過濾
- 高級查詢
- 排序
3.1.基本查詢:
基本語法
GET /索引庫名/_search
{
"query":{
"查詢類型":{
"查詢條件":"查詢條件值"
}
}
}
這里的query代表一個查詢對象,里面可以有不同的查詢屬性
- 查詢類型:
- 例如:
match_all
,match
,term
,range
等等
- 例如:
- 查詢條件:查詢條件會根據類型的不同,寫法也有差異,后面詳細講解
3.1.1 查詢所有(match_all)
示例:
GET /testindex/_search
{
"query":{
"match_all": {}
}
}
-
query
:代表查詢對象 -
match_all
:代表查詢所有
結果:
{
"took": 2,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 1,
"max_score": 1,
"hits": [
{
"_index": "testindex",
"_type": "goods",
"_id": "AWsS5Neq-k3yg4WVTNnG",
"_score": 1,
"_source": {
"title": "小米手機",
"images": "1,jpg",
"price": 111
}
}
]
}
}
- took:查詢花費時間,單位是毫秒
- time_out:是否超時
- _shards:分片信息
- hits:搜索結果總覽對象
- total:搜索到的總條數
- max_score:所有結果中文檔得分的最高分
- hits:搜索結果的文檔對象數組,每個元素是一條搜索到的文檔信息
- _index:索引庫
- _type:文檔類型
- _id:文檔id
- _score:文檔得分
- _source:文檔的源數據
3.1.2 匹配查詢(match)
- or關系
match
類型查詢,會把查詢條件進行分詞,然后進行查詢,多個詞條之間是or的關系
GET /testindex/_search
{
"query":{
"match":{
"title":"小米手機"
}
}
}
結果:
{
"took": 26,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 2,
"max_score": 0.51623213,
"hits": [
{
"_index": "testindex",
"_type": "goods",
"_id": "AWsS5Neq-k3yg4WVTNnG",
"_score": 0.51623213,
"_source": {
"title": "小米手機",
"images": "1,jpg",
"price": 111
}
},
{
"_index": "testindex",
"_type": "goods",
"_id": "3",
"_score": 0.25811607,
"_source": {
"title": "小米電視",
"images": "4.jp",
"price": 444
}
}
]
}
}
在上面的案例中,不僅會查詢到小米手機,而且與小米相關的都會查詢到,多個詞之間是or
的關系。(小米手機分為小米和手機兩個詞,由于是or關系,所以只要有小米或者手機兩個關鍵字中的一個就會被查詢到)
- and關系
某些情況下,我們需要更精確查找,我們希望這個關系變成and
,可以這樣做:
GET /testindex/_search
{
"query":{
"match": {
"title": {
"query": "小米手機",
"operator": "and"
}
}
}
}
結果:
{
"took": 26,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 1,
"max_score": 0.51623213,
"hits": [
{
"_index": "testindex",
"_type": "goods",
"_id": "AWsS5Neq-k3yg4WVTNnG",
"_score": 0.51623213,
"_source": {
"title": "小米手機",
"images": "1,jpg",
"price": 111
}
}
]
}
}
本例中,只有同時包含小米
和手機
的詞條才會被搜索到。
- or和and之間?
在 or
與 and
間二選一有點過于非黑即白。 如果用戶給定的條件分詞后有 5 個查詢詞項,想查找只包含其中 4 個詞的文檔,該如何處理?將 operator 操作符參數設置成 and
只會將此文檔排除。
有時候這正是我們期望的,但在全文搜索的大多數應用場景下,我們既想包含那些可能相關的文檔,同時又排除那些不太相關的。換句話說,我們想要處于中間某種結果。
match
查詢支持 minimum_should_match
最小匹配參數, 這讓我們可以指定必須匹配的詞項數用來表示一個文檔是否相關。我們可以將其設置為某個具體數字,更常用的做法是將其設置為一個百分數
,因為我們無法控制用戶搜索時輸入的單詞數量:
GET /testindex/_search
{
"query":{
"match":{
"title":{
"query":"小米無敵手機",
"minimum_should_match": "75%"
}
}
}
}
本例中,搜索語句可以分為3個詞,如果使用and關系,需要同時滿足3個詞才會被搜索到。這里我們采用最小品牌數:75%,那么也就是說只要匹配到總詞條數量的75%即可,這里3*75% 約等于2。所以只要包含2個詞條就算滿足條件了。
3.1.3 多字段查詢(multi_match)
multi_match
與match
類似,不同的是它可以在多個字段中查詢
GET /testindex/_search
{
"query":{
"multi_match": {
"query": "小米",
"fields": [ "title", "image" ]
}
}
}
會在title和image兩個字段中取查詢
3.1.4 詞條匹配(term)
term
查詢被用于精確值 匹配,這些精確值可能是數字、時間、布爾或者那些未分詞的字符串
GET /testindex/_search
{
"query":{
"term":{
"price":111
}
}
}
結果:
{
"took": 15,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 1,
"max_score": 1,
"hits": [
{
"_index": "testindex",
"_type": "goods",
"_id": "AWsS5Neq-k3yg4WVTNnG",
"_score": 1,
"_source": {
"title": "小米手機",
"images": "1,jpg",
"price": 111
}
}
]
}
}
3.1.5 多詞條精確匹配(terms)
terms
查詢和 term 查詢一樣,但它允許你指定多值進行匹配。如果這個字段包含了指定值中的任何一個值,那么這個文檔滿足條件:
GET /testindex/_search
{
"query":{
"terms":{
"price":[111,222]
}
}
}
3.2.結果過濾
默認情況下,elasticsearch在搜索的結果中,會把文檔中保存在_source
的所有字段都返回。
如果我們只想獲取其中的部分字段,我們可以添加_source
的過濾
3.2.1.直接指定字段
示例:
GET /testindex/_search
{
"_source": ["title","price"],
"query": {
"term": {
"price": 111
}
}
}
返回的結果:
{
"took": 28,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 1,
"max_score": 1,
"hits": [
{
"_index": "testindex",
"_type": "goods",
"_id": "AWsS5Neq-k3yg4WVTNnG",
"_score": 1,
"_source": {
"price": 111,
"title": "小米手機"
}
}
]
}
}
這樣_source字段中只有title和price兩個字段了
3.2.2.指定includes和excludes
我們也可以通過:
- includes:來指定想要顯示的字段
- excludes:來指定不想要顯示的字段
二者都是可選的。
示例:
GET /testindex/_search
{
"_source": {
"includes":["title","price"]
},
"query": {
"term": {
"price": 111
}
}
}
與下面的結果將是一樣的:
GET /testindex/_search
{
"_source": {
"excludes": ["images"]
},
"query": {
"term": {
"price": 2699
}
}
}
3.3 高級查詢
3.3.1 布爾組合(bool)
bool
把各種其它查詢通過must
(與)、must_not
(非)、should
(或)的方式進行組合
GET /testindex/_search
{
"query":{
"bool":{
"must": { "match": { "title": "小米" }},
"must_not": { "match": { "title": "電視" }},
"should": { "match": { "title": "手機" }}
}
}
}
結果:
{
"took": 18,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 1,
"max_score": 0.51623213,
"hits": [
{
"_index": "testindex",
"_type": "goods",
"_id": "AWsS5Neq-k3yg4WVTNnG",
"_score": 0.51623213,
"_source": {
"title": "小米手機",
"images": "1,jpg",
"price": 111
}
}
]
}
}
range
查詢允許以下字符:
操作符 | 說明 |
---|---|
gt | 大于 |
gte | 大于等于 |
lt | 小于 |
lte | 小于等于 |
3.3.3 模糊查詢(fuzzy)
我們新增一個商品:
POST /testindex/goods/4
{
"title":"apple手機",
"images":"apple.jpg",
"price":6899.00
}
fuzzy
查詢是 term
查詢的模糊等價。它允許用戶搜索詞條與實際詞條的拼寫出現偏差,但是偏差的編輯距離不得超過2:
GET /testindex/_search
{
"query": {
"fuzzy": {
"title": "appla"
}
}
}
上面的查詢,也能查詢到apple手機
我們可以通過fuzziness
來指定允許的編輯距離:
GET /testindex/_search
{
"query": {
"fuzzy": {
"title": {
"value":"appla",
"fuzziness":1
}
}
}
}
3.4 過濾(filter)
條件查詢中進行過濾
所有的查詢都會影響到文檔的評分及排名。如果我們需要在查詢結果中進行過濾,并且不希望過濾條件影響評分,那么就不要把過濾條件作為查詢條件來用。而是使用filter
方式:
GET /testindex/_search
{
"query":{
"bool":{
"must":{ "match": { "title": "小米手機" }},
"filter":{
"range":{"price":{"gt":2000.00,"lt":3800.00}}
}
}
}
}
注意:filter
中還可以再次進行bool
組合條件過濾。
無查詢條件,直接過濾
如果一次查詢只有過濾,沒有查詢條件,不希望進行評分,我們可以使用constant_score
取代只有 filter 語句的 bool 查詢。在性能上是完全相同的,但對于提高查詢簡潔性和清晰度有很大幫助。
GET /heima/_search
{
"query":{
"constant_score": {
"filter": {
"range":{"price":{"gt":2000.00,"lt":3000.00}}
}
}
}
3.5 排序
3.4.1 單字段排序
sort
可以讓我們按照不同的字段進行排序,并且通過order
指定排序的方式
GET /testindex/_search
{
"query": {
"match": {
"title": "小米手機"
}
},
"sort": [
{
"price": {
"order": "desc"
}
}
]
}
3.4.2 多字段排序
假定我們想要結合使用 price和 _score(得分) 進行查詢,并且匹配的結果首先按照價格排序,然后按照相關性得分排序:
GET /goods/_search
{
"query":{
"bool":{
"must":{ "match": { "title": "小米手機" }},
"filter":{
"range":{"price":{"gt":200000,"lt":300000}}
}
}
},
"sort": [
{ "price": { "order": "desc" }},
{ "_score": { "order": "desc" }}
]
}
4. 聚合aggregations
聚合可以讓我們極其方便的實現對數據的統計、分析。例如:
- 什么品牌的手機最受歡迎?
- 這些手機的平均價格、最高價格、最低價格?
- 這些手機每月的銷售情況如何?
實現這些統計功能的比數據庫的sql要方便的多,而且查詢速度非常快,可以實現實時搜索效果。
4.1 基本概念
Elasticsearch中的聚合,包含多種類型,最常用的兩種,一個叫桶
,一個叫度量
:
桶(bucket)
桶的作用,是按照某種方式對數據進行分組,每一組數據在ES中稱為一個桶
,例如我們根據國籍對人劃分,可以得到中國桶
、英國桶
,日本桶
……或者我們按照年齡段對人進行劃分:010,1020,2030,3040等。
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" : "2014-10-28" }
{ "index": {}}
{ "price" : 20000, "color" : "red", "make" : "honda", "sold" : "2014-11-05" }
{ "index": {}}
{ "price" : 30000, "color" : "green", "make" : "ford", "sold" : "2014-05-18" }
{ "index": {}}
{ "price" : 15000, "color" : "blue", "make" : "toyota", "sold" : "2014-07-02" }
{ "index": {}}
{ "price" : 12000, "color" : "green", "make" : "toyota", "sold" : "2014-08-19" }
{ "index": {}}
{ "price" : 20000, "color" : "red", "make" : "honda", "sold" : "2014-11-05" }
{ "index": {}}
{ "price" : 80000, "color" : "red", "make" : "bmw", "sold" : "2014-01-01" }
{ "index": {}}
{ "price" : 25000, "color" : "blue", "make" : "ford", "sold" : "2014-02-12" }
4.2 聚合為桶
首先,我們按照 汽車的顏色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:這個桶中的文檔數量
通過聚合的結果我們發現,目前紅色的小車比較暢銷!
4.3 桶內度量
前面的例子告訴我們每個桶里面的文檔數量,這很有用。 但通常,我們的應用需要提供更復雜的文檔度量。 例如,每種顏色汽車的平均價格是多少?
因此,我們需要告訴Elasticsearch使用哪個字段
,使用何種度量方式
進行運算,這些信息要嵌套在桶
內,度量
的運算會基于桶
內的文檔進行
現在,我們為剛剛的聚合結果添加 求價格平均值的度量:
GET /cars/_search
{
"size" : 0,
"aggs" : {
"popular_colors" : {
"terms" : {
"field" : "color"
},
"aggs":{
"avg_price": {
"avg": {
"field": "price"
}
}
}
}
}
}
- aggs:我們在上一個aggs(popular_colors)中添加新的aggs。可見
度量
也是一個聚合,度量是在桶內的聚合 - avg_price:聚合的名稱
- avg:度量的類型,這里是求平均值
- field:度量運算的字段
結果:
...
"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
}
}
]
}
}
...
可以看到每個桶中都有自己的avg_price
字段,這是度量聚合的結果
4.4 桶內嵌套桶
剛剛的案例中,我們在桶內嵌套度量運算。事實上桶不僅可以嵌套運算, 還可以再嵌套其它桶。也就是說在每個分組中,再分更多組。
比如:我們想統計每種顏色的汽車中,分別屬于哪個制造商,按照make
字段再進行分桶
GET /cars/_search
{
"size" : 0,
"aggs" : {
"popular_colors" : {
"terms" : {
"field" : "color"
},
"aggs":{
"avg_price": {
"avg": {
"field": "price"
}
},
"maker":{
"terms":{
"field":"make"
}
}
}
}
}
}
- 原來的color桶和avg計算我們不變
- maker:在嵌套的aggs下新添一個桶,叫做maker
- terms:桶的劃分類型依然是詞條
- filed:這里根據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
}
}
]
}
}
}
...
- 我們可以看到,新的聚合
maker
被嵌套在原來每一個color
的桶中。 - 每個顏色下面都根據
make
字段進行了分組 - 我們能讀取到的信息:
- 紅色車共有4輛
- 紅色車的平均售價是 $32,500 美元。
- 其中3輛是 Honda 本田制造,1輛是 BMW 寶馬制造。
4.5.劃分桶的其它方式
前面講了,劃分桶的方式有很多,例如:
- Date Histogram Aggregation:根據日期階梯分組,例如給定階梯為周,會自動每周分為一組
- Histogram Aggregation:根據數值階梯分組,與日期類似
- Terms Aggregation:根據詞條內容分組,詞條內容完全匹配的為一組
- Range Aggregation:數值和日期的范圍分組,指定開始和結束,然后按段分組
剛剛的案例中,我們采用的是Terms Aggregation,即根據詞條劃分桶。
接下來,我們再學習幾個比較實用的:
4.5.1.階梯分桶Histogram
原理:
histogram是把數值類型的字段,按照一定的階梯大小進行分組。你需要指定一個階梯值(interval)來劃分階梯大小。
舉例:
比如你有價格字段,如果你設定interval的值為200,那么階梯就會是這樣的:
0,200,400,600,...
上面列出的是每個階梯的key,也是區間的啟點。
如果一件商品的價格是450,會落入哪個階梯區間呢?計算公式如下:
bucket_key = Math.floor((value - offset) / interval) * interval + offset
value:就是當前數據的值,本例中是450
offset:起始偏移量,默認為0
interval:階梯間隔,比如200
因此你得到的key = Math.floor((450 - 0) / 200) * 200 + 0 = 400
操作一下:
比如,我們對汽車的價格進行分組,指定間隔interval為5000:
GET /cars/_search
{
"size":0,
"aggs":{
"price":{
"histogram": {
"field": "price",
"interval": 5000
}
}
}
}
結果:
{
"took": 21,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"skipped": 0,
"failed": 0
},
"hits": {
"total": 8,
"max_score": 0,
"hits": []
},
"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
}
}
}
}
結果:
{
"took": 15,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"skipped": 0,
"failed": 0
},
"hits": {
"total": 8,
"max_score": 0,
"hits": []
},
"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
}
]
}
}
}
完美,!
4.5.2.范圍分桶range
范圍分桶與階梯分桶類似,也是把數字按照階段進行分組,只不過range方式需要你自己指定每一組的起始和結束大小。