如何使用Kusto scan算子生成ColumnA匹配的连续数据对?
使用Kusto scan算子生成ColumnA匹配的连续数据对
问题描述
现有数据表threecolumns,包含Ts(时间跨度)、ColumnA、ColumnB字段,需要生成同一ColumnA下的连续数据对:按时间顺序两两组合,剩余单个数据不输出。期望结果中,每条配对的起始数据标记为isPair=true,并关联下一条数据的ColumnA和ColumnB值。
示例数据表:
let threecolumns = datatable( Ts: timespan, ColumnA: string, ColumnB: string) [ 0m, "aaa","023", 1m, "aaa","134", 2m, "aaa", "256", 3m, "aaa", "356", 4m, "aaa", "467", 5m, "bbb", "578", 6m, "bbb", "687", 8m, "ccc", "788", 11m, "ddd", "899", 12m, "ddd", "988"];
期望输出:
| Ts | ColumnA | ColumnB | isPair | A_1 | B_1 |
|---|---|---|---|---|---|
| 0m | aaa | 023 | true | aaa | 134 |
| 2m | aaa | 256 | true | aaa | 356 |
| 5m | bbb | 578 | true | bbb | 687 |
| 11m | ddd | 899 | true | ddd | 988 |
错误代码分析
原代码存在以下问题:
- 分区内按
Ts desc排序,导致配对方向颠倒,生成了从后往前的反向配对 - scan算子的状态逻辑未正确追踪已配对记录,导致重复标记配对
- 额外引入的
A_2、B_2字段及冗余scan步骤,干扰了配对逻辑
修正后的代码
let threecolumns = datatable( Ts: timespan, ColumnA: string, ColumnB: string) [ 0m, "aaa","023", 1m, "aaa","134", 2m, "aaa", "256", 3m, "aaa", "356", 4m, "aaa", "467", 5m, "bbb", "578", 6m, "bbb", "687", 8m, "ccc", "788", 11m, "ddd", "899", 12m, "ddd", "988"]; threecolumns | partition hint.strategy=native by ColumnA ( order by Ts asc // 按时间升序排列,保证配对顺序正确 | scan declare(is_paired: bool = false, next_A: string, next_B: string) with ( // 识别未配对且存在下一条同组数据的记录,标记为配对并记录下一条数据 step start: is_paired == false and next(ColumnA) == ColumnA => is_paired = true, next_A = next(ColumnA), next_B = next(ColumnB); // 跳过已配对的后续记录,避免重复输出 step paired: start.is_paired == true => is_paired = true; // 处理无后续数据的单个记录,标记为未配对 step default: is_paired = false; ) ) | where is_paired == true and next_A != "" // 筛选有效配对的起始记录 | project Ts, ColumnA, ColumnB, isPair = is_paired, A_1 = next_A, B_1 = next_B | order by Ts asc // 按时间排序输出最终结果
代码说明
- 分区与排序:按
ColumnA分区后,每个分区内按Ts升序排列,确保数据按时间顺序处理。 - scan状态追踪:
start步骤:锁定可配对的起始记录,标记配对状态并存储下一条数据信息。paired步骤:跳过已配对的后续记录,避免重复输出。default步骤:处理无后续数据的单个记录,标记为未配对以排除输出。
- 结果筛选:仅保留标记为配对且存在下一条数据的记录,整理为期望的输出字段。
内容的提问来源于stack exchange,提问作者h.das
相关产品推荐
相关产品推荐

