Kdb+查询api函数单参数调用报错问题及修改需求咨询
extraCols Let's break down what's causing the type error and how to fix it step by step.
Why the Type Error Happens
When you pass a single column using enlist(Species)as theextraColsvalue,Params[`extraCols]` becomes a single-element list of symbols (`,`Species`). When you create the dictionary `Params[`extraCols]!Params[`extraCols]`, this results in a dictionary where the key is a list type (`,`Species`) instead of a single symbol.
Your defaultCols dictionary uses individual symbols as keys (\ID\Name\Client`), and kdb+ throws a type error because it can't merge dictionaries with mismatched key types (symbol vs. list).
In contrast, when passing multiple columns like \Species\Length, Params[extraCols] is a list of symbols, so the generated dictionary has symbols as keys (matching defaultCols' key type) — which is why that case works without issues.
Modified API Function
To fix this, we need to ensure extraCols is always converted to a proper symbol vector (either a single symbol atom or a list of symbols) before building the dictionary. The \$` operator handles this conversion automatically for both single and multiple columns:
api:{[Params] if [Params~();Params:()!()]; defaultCols:`ID`Name`Client!(`ID`Name`Client); if[`extraCols in key Params; // Convert to symbol vector (handles single/multiple column inputs) extraCols:`$Params[`extraCols]; defaultCols:defaultCols,extraCols!extraCols]; : ?[table1;();0b;defaultCols]; }
Testing the Fixed Function
- First, define your table as originally specified:
table1:([]ID:`1`2`3;Name:`A`B`C;Client:`P`Q`S;ClientType:`QW`DS`WW;NameType:`jj`ll`oo;Basket:`QD`IO`LK;Sepal:5.1 4.5 23.5;Length:2 34 6;Species:`setosa`setosa`setosa)
- Test with single column parameter:
api[(enlist[`extraCols]!enlist(`Species))]
This now returns your desired result:
ID Name Client Species ----------------------- 1 A P setosa 2 B Q setosa 3 C S setosa
- Test with multiple columns (still works as expected):
api[(enlist[`extraCols]!enlist(`Species`Length))]
Returns:
ID Name Client Species Length ------------------------------ 1 A P setosa 2 2 B Q setosa 34 3 C S setosa 6
内容的提问来源于stack exchange,提问作者James

