世界上并没有完美的程序,但是我们并不因此而沮丧,因为写程序就是一个不断追求完美的过程。
问:avg有什么特点?
答:
问:avg如何使用?
答:
# 删除
DELETE /avg_test
# 映射
PUT /avg_test
{
"mappings": {
"properties": {
"name": {"type": "keyword"},
"filter_type": {"type": "keyword"},
"num": {"type": "integer"}
}
}
}
# 索引
POST /avg_test/_bulk?routing=1&refresh
{"index": {"_id": 1}}
{"name": "hello", "filter_type": "t1", "num": 3}
{"index": {"_id": 2}}
{"name": "me", "filter_type": "t2", "num": 5}
{"index": {"_id": 3}}
{"name": "me", "filter_type": "t1", "num": 18}
{"index": {"_id": 4}}
{"name": "hello", "filter_type": "t1", "num": 20}
{"index": {"_id": 5}}
{"name": "good", "filter_type": "t1", "num": 28}
{"index": {"_id": 6}}
{"name": "me", "filter_type": "t2", "num": 50}
{"index": {"_id": 7}}
{"name": "good", "filter_type": "t1", "num": 58}
{"index": {"_id": 8}}
{"name": "hello", "filter_type": "t1", "num": 88}
# 搜索
GET /avg_test/_search?size=0
{
"aggs": {
"avg_aggs": {
"avg": {
"field": "num"
}
}
}
}
# 结果
{
"took" : 1,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 8,
"relation" : "eq"
},
"max_score" : null,
"hits" : [ ]
},
"aggregations" : {
"avg_aggs" : {
"value" : 33.75
}
}
}
# 搜索
GET /avg_test/_search?size=0
{
"aggs": {
"avg_aggs": {
"avg": {
"script": {
"source": "doc.num.value"
}
}
}
}
}
# 结果
{
"took" : 22,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 8,
"relation" : "eq"
},
"max_score" : null,
"hits" : [ ]
},
"aggregations" : {
"avg_aggs" : {
"value" : 33.75
}
}
}
# 搜索
GET /avg_test/_search?size=0
{
"aggs": {
"avg_aggs": {
"avg": {
"field": "num",
"script": {
"lang": "painless",
"source": "_value * params.mul",
"params": {
"mul": 10
}
}
}
}
}
}
# 结果
{
"took" : 1,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 8,
"relation" : "eq"
},
"max_score" : null,
"hits" : [ ]
},
"aggregations" : {
"avg_aggs" : {
"value" : 337.5
}
}
}
DELETE /avg_histo_test
PUT /avg_histo_test
{
"mappings": {
"properties": {
"my_histo": {"type": "histogram"}
}
}
}
POST /avg_histo_test/_doc/1
{
"name": "no1",
"my_histo": {
"values": [1, 2, 3, 4],
"counts": [1, 2, 3, 4]
}
}
GET /avg_histo_test/_mapping
POST /avg_histo_test/_doc/2
{
"name": "no2",
"my_histo": {
"values": [7, 8, 9, 10],
"counts": [7, 8, 9, 10]
}
}
# 搜索 - value * count / 总count 的平均值
GET /avg_histo_test/_search?size=0
{
"aggs": {
"avg_aggs": {
"avg": {
"field": "my_histo"
}
}
}
}
# 结果
{
"took" : 1,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 2,
"relation" : "eq"
},
"max_score" : null,
"hits" : [ ]
},
"aggregations" : {
"avg_aggs" : {
"value" : 7.363636363636363
}
}
}



