【问题标题】:Parameterize select query in unary kdb function在一元 kdb 函数中参数化选择查询
【发布时间】:2019-03-17 19:02:17
【问题描述】:

我希望能够从远程存储在磁盘上的非常大的键控表中批量选择行。作为测试我的功能的玩具示例,我设置了以下表格 tnt...

t:([sym:110?`A`aa`Abc`B`bb`Bac];px:110?10f;id:1+til 110)
nt:0#t

我从表中只选择以字符“A”开头的记录,计算字符数,将计数除以我想为每个函数调用获取的行数 (10),然后向上取整到最接近的整数...

aRec:select from t where sym like "A*"
counter:count aRec
divy:counter%10
divyUP:ceiling divy

接下来我将idx 变量设置为0,并将if statement 作为参数化函数。这将检查 idx 是否等于 divyUP。如果不是,那么它应该选择 aRec 的前 10 行,将它们插入到 nt 表中,将函数参数 x 递增 10,并将 idx 变量递增 1。一旦 @ 987654333@ 变量和divyUP 相等应该退出函数...

idx:0
batches:{[x]if[not idx=divyUP;batch::select[x 10]from aRec;`nt upsert batch;x+:10;idx+::1]}

但是,当我调用该函数时,它会返回 type 错误...

q)batches 0
'type
[1]  batches:{[x]if[not idx=divyUP;batch::select[x 10]from aRec;`nt upsert batch;x+:10;idx+::1]}
                                                 ^

我也尝试过将它与sublist 一起使用,尽管我得到了相同的结果...

batches:{[x]if[not idx=divyUP;batch::x 10 sublist aRec;`nt upsert batch;x+:10;idx+::1]}

q)batches 0
'type
[1]  batches:{[x]if[not idx=divyUP;batch::x 10 sublist aRec;`nt upsert batch;x+:10;idx+::1]}
                                          ^

但是在函数之外发出上述任何一个命令都返回预期的结果...

q)select[0 10] from aRec
sym| px        id
---| ------------
A  | 4.236121  1
A  | 5.932252  3
Abc| 5.473628  5
A  | 0.7014928 7
Abc| 3.503483  8
A  | 8.254616  9
Abc| 4.328712  10
A  | 5.435053  19
A  | 1.014108  22
A  | 1.492811  25

q)0 10 sublist aRec
sym| px        id
---| ------------
A  | 4.236121  1
A  | 5.932252  3
Abc| 5.473628  5
A  | 0.7014928 7
Abc| 3.503483  8
A  | 8.254616  9
Abc| 4.328712  10
A  | 5.435053  19
A  | 1.014108  22
A  | 1.492811  25

【问题讨论】:

    标签: kdb


    【解决方案1】:

    问题在于,在您的示例中, select[] 和 sublist 需要一个列表作为输入,但您的输入不是一个列表。原因是当项目中有一个变量(它将形成一个列表)时,它不再被视为一个简单的列表,这意味着空白(空格)不能用于分隔值。在这种情况下,需要使用分号。

    q) x:2
    q) (1;x) / (1 2)
    

    选择命令:将输入更改为 (x;10) 以使其工作。

    q) t:([]id:1 2 3; v: 3 4 5)
    q) {select[(x;2)] from t} 1
    
    `id  `v
    ---------
     2    4
     3    5
    

    另一种选择是使用 'i'(index) 列:

    q) {select from t where i within x + 0 2} 1
    

    子列表命令:将子列表函数的左输入转换为列表(x;10)。

     q) {(x;2) sublist t}1
    

    【讨论】:

      【解决方案2】:

      您不能使用带有变量输入的 select[] 表单,而是可以使用https://code.kx.com/q4m3/9_Queries_q-sql/#912-functional-forms 中显示的功能选择,您可以在其中输入您想要的行作为第 5 个参数

      希望这会有所帮助!

      【讨论】:

      • select[] 适用于变量。输入应该是一个列表。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-27
      • 2013-09-17
      相关资源
      最近更新 更多