You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现Kx q语言仅插入新记录的upsert变种upsertmod

实现Kdb+的upsertmod函数

先看原始的键表操作示例:

q)show x:`a`b xkey ([] a:2#`p; b:`x`y; c:1 2);
a b| c
---| -
p x| 1
p y| 2

q)show y:update c:(3;4) from x;
a b| c
---| -
p x| 3
p y| 4

q)x upsert y
a b| c
---| -
p x| 3
p y| 4

默认的upsert行为:当操作对象是键表时,匹配键的新记录会覆盖原记录;若不是键表则插入新记录。

现在需要实现upsertmod函数,要求仅插入键不存在于原表的新记录,匹配键的记录不做更新,期望效果如下:

q)x upsertmod y // 期望输出
a b| c
---| -
p x| 1
p y| 2

实现方案

核心逻辑是先筛选出待插入表u中,键未出现在目标表t键集合里的记录,再用upsert执行插入操作。函数定义如下:

upsertmod:{[t;u] t upsert u where not u.key in t.key}

验证效果:

// 原有键记录不更新
q)x upsertmod y
a b| c
---| -
p x| 1
p y| 2

// 插入全新键的记录正常生效
q)z:([a:`p;b:`z] c:5)
q)x upsertmod z
a b| c
---| -
p x| 1
p y| 2
p z| 5

内容的提问来源于stack exchange,提问作者marital_weeping

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 18:42:18