【发布时间】:2021-02-05 07:45:05
【问题描述】:
我想按sysCode 和最大date 分组,即获取每个sysCode 的最新文档,然后在employeeId 上聚合并键入字段。
下面的查询没有返回我想要的结果,对于GER,它返回employeeId=1,对于IND,它返回我不想要的employeeId=3。
示例 json 文档
{
"sysCode": "GER",
"employeeId": 1,
"date": "2014-06-14",
"categories": {
"pb": [
{
"metric": "OVERDUE",
"type": "LATE"
}
]
}
}
{
"sysCode": "GER",
"employeeId": 2,
"date": "2014-06-15",
"categories": {
"pb": [
{
"metric": "OVERDUE",
"type": "LATE"
}
]
}
}
{
"sysCode": "IND",
"employeeId": 3,
"date": "2014-06-16",
"categories": {
"pb": [
{
"metric": "OVERDUE",
"type": "LATE"
}
]
}
}
{
"sysCode": "IND",
"employeeId": 3,
"date": "2014-06-16",
"categories": {
"pb": [
{
"metric": "OVERDUE",
"type": "MISSED"
}
]
}
}
聚合查询
{
"aggs": {
"result_by_sys_code": {
"terms": {
"field": "sysCode"
},
"aggs": {
"max_as_of_date": {
"max": {
"field": "date"
}
},
"employees": {
"terms": {
"field": "employeeId"
},
"aggs": {
"nested": {
"nested": {
"path": "categories.pb"
},
"aggs": {
"metrics": {
"terms": {
"field": "categories.pb.type.keyword"
}
}
}
}
}
}
}
}
}
}
映射
{
"mappings": {
"properties": {
"date": {
"type": "date"
},
"categories": {
"properties": {
"pb": {
"type": "nested",
"properties": {
"metric": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"type": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
}
}
}
}
},
"controlCode": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
}
}
}
}
【问题讨论】:
-
你能在这里添加你的映射吗
-
添加了字段映射
-
由于您的日期格式为
yyyy-mm-dd,如果多个文档具有相同的日期,您打算怎么做(恕我直言,这种情况经常发生)?
标签: elasticsearch elasticsearch-aggregation