如何用KQL实现两表基于包含关系的非精确关联查询?
KQL实现跨表包含关系关联方案
要实现非精确匹配的跨表关联(即找出表A中被表B字符串包含的记录),可以通过mv-expand展开动态数组,结合join与contains/has运算符实现,以下是针对你需求的具体方案:
核心思路
- 展开动态数组:用
mv-expand将两个表中存储的dynamic类型数组拆分为单行字符串,方便后续匹配。 - 跨表包含匹配:通过
join关联两个表,在关联条件中使用contains(子串匹配)或has(整词匹配)判断包含关系,如需忽略大小写可结合tolower()统一转换。
针对你提供的示例代码实现
let bad_software = datatable(d: dynamic) [ dynamic(["Windows 10 its cool"]), dynamic(["Windows 11 its cool"]), dynamic(["linux its the best"]) ]; let mysoftware = datatable(d: dynamic) [ dynamic(["Windows"]), dynamic(["Windows 11"]), dynamic(["Some words"]) ]; // 展开数组为单行字符串并重命名字段 let bad_sw_expanded = bad_software | mv-expand d to typeof(string) | rename bad_item = d; let my_sw_expanded = mysoftware | mv-expand d to typeof(string) | rename my_item = d; // 关联并筛选包含关系的记录 my_sw_expanded | join kind=inner bad_sw_expanded on $right.bad_item contains $left.my_item // 忽略大小写的写法:on tolower($right.bad_item) contains tolower($left.my_item) | project my_item, bad_item
执行后会输出:
my_item | bad_item -----------|--------------------- Windows | Windows 10 its cool Windows | Windows 11 its cool Windows 11 | Windows 11 its cool
其他场景示例
漏洞软件与系统表关联
let vulnerable_software = datatable(software: string) [ "Windows 10 Kerberos failure", "linux systemd failure" ]; let os_list = datatable(os: string) [ "windows", "linux", "mac" ]; os_list | join kind=inner vulnerable_software on tolower(vulnerable_software.software) contains tolower(os_list.os) | project os, software
输出:
os | software --------|--------------------------- windows | Windows 10 Kerberos failure linux | linux systemd failure
姓名与描述关联
let table1 = datatable(desc: string) [ "rod is handsome", "rod is nice", "alice is pretty" ]; let table2 = datatable(name: string) [ "rod", "alice", "Ben" ]; table2 | join kind=inner table1 on tolower(table1.desc) contains tolower(table2.name) | project name, desc
输出:
name | desc ------|------------------ rod | rod is handsome rod | rod is nice alice | alice is pretty
关键说明
contains:匹配任意子串,适用于部分字符包含的场景;has:匹配完整单词(以空格/标点分隔),需根据需求选择。join kind=inner:仅保留两边都匹配的记录,若需保留表A所有记录(匹配不上的显示null),可改用kind=leftouter。tolower():统一转换为小写,避免大小写导致的匹配失败。
内容的提问来源于stack exchange,提问作者newbie-python
相关产品推荐
相关产品推荐

