kdb+ 条件插入:仅在列值不存在时插入

kdb+ conditional insert: only insert when column value doesn't exist

仅当 table 中不存在该行的列时,将行插入 table 的最佳方法是什么。

例如:

q)table:([] col1:(); col2:(); col3:());
q)`table insert (1;2;3);
q)conditionalInsert:{if[first where table.col1=x(0)~0N;`table insert x]};

现在执行以下操作时:

q)conditionalInsert[(1;2;3)];
q)conditionalInsert[(7;8;9)];

结果产生:

q)table
col1 col2 col3
--------------
1    2    3
7    8    9

这可能更容易完成。我的问题:easiest/best 方法是什么?

明确一点:该列可能是非键控列。

或者换句话说:Table 是键控或非键控且目标列不是键(或复合键列的一部分)

使用键控 table?

q)table  
col1| col2 col3  
----| ---------  
1   | 2    3  
q)`table insert (1;2;4)  
'insert  
q)`table insert (2;2;4)  
,1  
q)table  
col1| col2 col3  
----| ---------  
1   | 2    3  
2   | 2    4  

您始终可以使用受保护的评估来消除错误。

q).[insert;(`table;(1;2;4));{`already_there}]  
`already_there  
q).[insert;(`table;(3;2;4));{`already_there}]  
,2  
q)table  
col1| col2 col3  
----| ---------  
1   | 2    3  
2   | 2    4  
3   | 2    4  

第一件事是在目标列上具有适当的属性(排序、分组),这将使函数更快。

现在我能想到的场景有2种:

a) Table 是键控的,目标列是键控列: 在这种情况下,正常插入将像条件插入一样工作。

b) Table 是键控或非键控且目标列不是键(或复合键列的一部分):

         q)conditionalInsert: {if[not x[0] in table.col1;`table insert x]} 

最好使用 'exec' 代替 'table.col1',因为点符号不适用于键控 table:

         q)conditionalInsert: {if[not x[0] in exec col1 from table;`table insert x]}