- 需求:
业务 需要知道考勤打卡记录最早进 与 最早出 一天记录原始信息,现通过 top_hits来实现 - 如下:
GET /att_index/_search
{
"query": {
"bool": {
"filter": [
{
"range": {
"record_time": {
"gte": "2022-03-07T00:00:00",
"lte": "2022-03-08T00:00:00"
}
}
},
{
"match":{
"idcardno.keyword":"5*******"
}
}
]
}
}
,"size":0,
"aggs": {
"groupBy_idcardno": {
"terms": { --对人员身份证进行分桶
"field": "idcardno.keyword",
"size": 50
},
"aggs": {
"groupBy_recordtime":{
"date_histogram": { --对人员打卡日期,以天为单位进行分桶
"field": "record_time",
"calendar_interval": "day",
"format": "yyyy-MM-dd" ,
"min_doc_count" : 0
},
"aggs": {
"idcard_recordTime_top_last": {--通过top_hits排序获取最晚出的记录
"top_hits": {
"sort": [
{
"record_time": {
"order": "desc"
}
}
],
"size": 1
}
},
"idcard_recordTime_earliest": {--通过top_hits排序获取最早进的记录
"top_hits": {
"sort": [
{
"record_time": {
"order": "asc"
}
}
],
"size": 1
}
}
}
}
}
}
}
}
- 结果
{
"took" : 69,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 281,
"relation" : "eq"
},
"max_score" : null,
"hits" : [ ]
},
"aggregations" : {
"record_date_partiton" : {
"doc_count_error_upper_bound" : 0,
"sum_other_doc_count" : 0,
"buckets" : [
{
"key" : "532122*******1613",
"doc_count" : 281,
"groupBy_recordtime" : {
"buckets" : [
{
"key_as_string" : "2022-03-07",
"key" : 1646611200000,
"doc_count" : 281,
"idcard_recordTime_earliest" : {
"hits" : {
"total" : {
"value" : 281,
"relation" : "eq"
},
"max_score" : null,
"hits" : [
{
"_index" : "atte",
"_type" : "_doc",
"_id" : "PFywaH8BGUfFSK8ILMmm",
"_score" : null,
"_source" : {
.....
"record_time" : "2022-03-07T06:04:17",
......
"idcardno" : "5*********",
"direct" : 1,
},
"sort" : [
1646633057000
]
}
]
}
},
"idcard_recordTime_top_last" : {
"hits" : {
"total" : {
"value" : 281,
"relation" : "eq"
},
"max_score" : null,
"hits" : [
{
"_index" : "att",
"_type" : "_doc",
"_id" : "qIOSZ38BPDXhbVpyFFgY",
"_score" : null,
"_source" : {
.......
"record_time" : "2022-03-07T17:35:49",
........
"idcardno" : "5**********",
......
"direct" : 1,
},
"sort" : [
1646674549000
]
}
]
}
}
}
]
}
}
]
}
}
}