KQL如何解析日志提取Relations_s字段的工作项ID与关联名称
Azure DevOps工作项关联字段KQL解析方案
Relations_s字段存储的是非标准格式的JSON字符串:多个独立对象数组用, 拼接,没有外层数组包裹,直接调用parse_json会解析失败,先做格式修正后再提取字段即可,以下是两类需求的可直接运行的代码。
长表输出结果
每一行对应一条工作项关联关系,包含当前工作项ID、关联类型名称、关联工作项ID三个核心字段,兼容所有关联类型(Parent/Child/Related/Duplicate等),无需提前硬编码类型。
azure_devops_work_item_events_CL | summarize any(WorkItemType_s, TeamProject_s, Title_s, AssignedTo_s, State_s, Reason_s) by WorkItemId_d, Relations_s // 修正JSON格式:替换块分隔符,外层包裹数组括号 | extend fixed_relation = parse_json(strcat("[", replace(@'\]\s*,\s*\[', ',', Relations_s), "]")) // 拆分单条关联记录为独立行 | mv-expand single_relation = fixed_relation // 提取| extend Name = tostring(single_relation[0].attributes.name), Item = tolong(split(single_relation[0].url, "/")[-1]) // 过滤空值无效记录 | where isnotempty(Name) and isnotempty(Item) | project WorkItemId_d, Name, Item, WorkItemType_s, TeamProject_s, Title_s, AssignedTo_s, State_s, Reason_s | order by WorkItemId_d desc
宽表输出结果
固定生成Parent、Child列分别存储父、子工作项ID,基于长表逻辑做透视即可实现:
azure_devops_work_item_events_CL | summarize any(WorkItemType_s, TeamProject_s, Title_s, AssignedTo_s, State_s, Reason_s) by WorkItemId_d, Relations_s | extend fixed_relation = parse_json(strcat("[", replace(@'\]\s*,\s*\[', ',', Relations_s), "]")) | mv-expand single_relation = fixed_relation | extend Name = tostring(single_relation[0].attributes.name), Item = tolong(split(single_relation[0].url, "/")[-1]) | where isnotempty(Name) and isnotempty(Item) // 按关联类型透视生成宽列 | evaluate pivot(Name, make_set(Item, 1)) | project-rename Parent = Parent, Child = Child | order by WorkItemId_d desc
注意事项
- 正则替换里加了
\s*兼容字段里不同数量的空格格式,避免因为空格差异导致解析失败 - 正常工作项逻辑下单个工作项仅会有1个Parent,代码里
make_set(Item,1)默认取第一个有效ID;如果需要展示所有多关联的ID,替换为make_list(Item)即可,输出为ID数组格式 - 如果存在其他关联类型,pivot步骤会自动生成对应名称的列,无需手动修改代码
内容的提问来源于stack exchange,提问作者Hudson Carpenter
相关产品推荐
相关产品推荐

