我是 jq 新手,正在尝试从 json 响应中获取一些字段。值得注意的字段是“角色”小节下的“关键”字段。以下是响应格式的示例:
{
"took": 755,
"timed_out": false,
"_shards": {
"total": 3,
"successful": 3,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 10000,
"relation": "gte"
},
"max_score": null,
"hits": []
},
"aggregations": {
"user_data": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [
{
"key": "user1",
"doc_count": 872721,
"response_status": {
"buckets": {
"success": {
"from": 200,
"to": 300,
"doc_count": 872709,
"roles": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [
{
"key": "example-role",
"doc_count": 872709
}
]
}
},
"failure": {
"from": 400,
"to": 500,
"doc_count": 0,
"roles": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": []
}
}
}
}
},
{
"key": "user2",
"doc_count": 2286,
"response_status": {
"buckets": {
"success": {
"from": 200,
"to": 300,
"doc_count": 2285,
"roles": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 2285,
"buckets": [
{
"key": "example-role",
"doc_count": 2285
}
]
}
},
"failure": {
"from": 400,
"to": 500,
"doc_count": 1,
"roles": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 1,
"buckets": [
{
"key": "example-role",
"doc_count": 1
}
]
}
}
}
}
},
{
"key": "user4",
"doc_count": 872721,
"response_status": {
"buckets": {
"success": {
"from": 200,
"to": 300,
"doc_count": 872709,
"roles": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": []
}
},
"failure": {
"from": 400,
"to": 500,
"doc_count": 0,
"roles": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": []
}
}
}
}
},
{
"key": "user4",
"doc_count": 1,
"response_status": {
"buckets": {
"success": {
"from": 200,
"to": 300,
"doc_count": 0,
"roles": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": []
}
},
"failure": {
"from": 400,
"to": 500,
"doc_count": 1,
"roles": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [
{
"key": "example-role",
"doc_count": 1
}
]
}
}
}
}
}
]
}
}
}
为了解释最终目标,我正在按用户和用户角色收集有关 http 成功/失败的汇总数据。并非所有用户都有角色,但我仍然需要这些用户的数据,这就是查询以这种方式构造的原因。
我的问题是如何获取用户的角色,或者如果他们没有角色则为 null。上面的示例中有 3 种明显的情况:具有角色的用户(要么成功但没有失败,反之亦然)、具有角色的用户以及没有角色的用户。我设法编写了这个 jq 命令来过滤哪些用户有/没有角色:
.aggregations|.user_data|.buckets[]|.response_status|.buckets|map(.roles|.buckets|map(has("key")))|flatten|any
对于此数据返回以下内容:
true
true
false
true
我如何从这里返回角色本身(如果为 true)或 null(如果为 false),以便在这个示例中我将返回:
"example-role"
"example-role"
null
"example-role"
提前致谢。