#查看测试索引结构 test_index
GET test_index/_mapping
#创建测试索引结构
PUT test_index
{
"mappings": {
"doc": {
"properties": {
"age": {
"type": "integer"
},
"birthday": {
"type": "date"
},
"job": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"name": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
}
}
}
}
}
#插入测试数据
POST test_index/doc/6
{
"name": "老马",
"age": "58",
"birthday": "1958-06-01",
"job":"famer"
}
POST test_index/doc/2
{
"name":"小红",
"age":"18",
"birthday":"2021-06-01",
"job":"student"
}
POST test_index/doc/1
{
"name":"小明",
"age":"18",
"birthday":"2021-06-01",
"job":"student"
}
POST test_index/doc/7
{
"name":"小李",
"age":"26",
"birthday":"1999-06-01",
"job":"student"
}
#查看所有数据
GET test_index/_search
{
"query": {
"match_all": {
}
},
"sort": [
{
"_id": {
"order": "asc"
}
}
]
}
#按工作分类,统计每个工种的人数,并找出年龄最大的三个人,注意:分桶和分桶排序最好不要使用_id和keword,这样会占用内存且不会自动释放。
POST test_index/doc/_search
{
"size": 0,
"aggs": {
"jobs": {
"terms": {
"field": "job.keyword",
"order": {
"_count": "desc"
}
},
"aggs": {
"ages": {
"top_hits": {
"size": 3,
"sort": [
{
"age.keyword": {
"order": "desc"
}
}
]
}
}
}
}
}
}
#聚合 按照年龄范围聚合分桶,注意:range只能针对数字或者日期
POST test_index/doc/_search
{
"size": 0,
"aggs": {
"age_range": {
"range": {
"field": "age",
"ranges": [
{"to": "20","key": "青年"},
{
"from": "20",
"to": "30","key":
"中年"
},
{"from": "30","key": "老年"}
]
},
"aggs": {
"jobs": {
"terms": {
"field": "job.keyword",
"size": 3
}
}
}
}
}
}
#聚合计算聚 年龄合区间分桶 分析
POST test_index/doc/_search
{
"size": 0,
"aggs": {
"age_count": {
"histogram": {
"field": "age",
"interval": 10
}
}
}
}
#分桶 查看状态计算
POST test_index/doc/_search
{
"size": 0,
"aggs": {
"job_count": {
"terms": {
"field": "job.keyword",
"size": 10
},
"aggs": {
"age_status": {
"stats": {
"field": "age"
}
}
}
}
}
}