DAY 26
0
Elastic Stack on Cloud

## 分析問題

1. 用 stock_id (股票代號)對所有的收盤資料進行 Agrregation
2. 在每個 stock_id bucket 中再根據不同的月份進行一次 Aggregation
3. 在 month_k bucket 中找出當月份的開/高/低/收/量。
在這個問題中，我們會用到很多不同的 Aggregation，就一步步來實現吧！

## terms aggregation

``````GET /stock-history-prices-daily/_search
{
"size":0,
"aggs" : {
"stock_id" : {
"terms": {
"field": "stock_id"
}
}
}
}
``````

## nested aggregation

Aggregation 是可以 Nested 的！第二步，我要把每個 stock_id bucket 中的相同月份，再進行一次 aggregation。

``````GET /stock-history-prices-daily/_search
{
"size":0,
"aggs" : {
"stock_id" : {
"terms": {
"field": "stock_id"
},
"aggs" : {
"month_k": {
"date_histogram": {
"field": "date",
"calendar_interval": "month"
}
}
}
}
}
}
``````

## max, min aggregation

``````GET /stock-history-prices-daily/_search
{
"size":0,
"aggs" : {
"stock_id" : {
"terms": {
...
},
"aggs" : {
"month_k": {
...
},
"aggs": {
"high": {
"max": {
"field": "high"
}
},
"low": {
"min": {
"field": "low"
}
}
}
}
}
}
}
}
``````

## top_hits aggregation

``````GET /stock-history-prices-daily/_search
{
"size":0,
"aggs" : {
"stock_id" : {
...
},
"aggs" : {
"month_k": {
...
},
"aggs": {
"high": {
...
},
"low": {
...
},
"open": {
"top_hits": {
"size": 1,
"sort": [
{
"date": {
"order": "asc"
}
}
]
}
},
"close": {
"top_hits": {
"size": 1,
"sort":
{
"date": {
"order": "desc"
}
}
}
}
...
}
``````

Elastic 戰台股30