kdb+

Using parse to create functional queries


I am having issues translating parse output to functional select. Am I right in thinking that you need to convert each , to enlist

Full problem:

q)dict:exec i by uid from select uid from tb where sym=syms

One:

q)hd:exec date by uid from select date,ht by uid from tb where uid in raze key dict
q)parse"exec date by uid from select date,ht by uid from tb where uid in raze key dict"
?
(?;`tb;,,(in;`uid;(,/;(!:;`dict)));(,`uid)!,`uid;`date`ht!`date`ht)
()
,`uid
,`date

Two:

q)ht:key asc(value exec ht by uid from tb where uid in uids)!(value dict)
q)parse"exec ht by uid from tb where uid in uids"
?
`tb
,,(in;`uid;`uids)
,`uid
,`ht
q)

My attempts:

One (not working):

q)?[(?;`tb;enlist enlist (in;`uid;(,/;(!:;`dict)));(enlist `uid)!enlist `uid;`date`ht!`date`ht);();enlist `uid;enlist `date]
'type
  [0]  ?[(?;`tb;enlist enlist (in;`uid;(,/;(!:;`dict)));(enlist `uid)!enlist `uid;`date`ht!`date`ht);();(enlist`date)!enlist`date]

Two (working):

q) ?[`tb;enlist(in;`uid;`uids);`uid;(enlist`ht)!enlist`ht]

Solution

  • Sample data is always helpful to answer question if you can provide some

    q)dict:(1 2;3 4)!2#()
    dict
    1 2|
    3 4|
    q)tb:([] date:.z.d+til 4;ht:til 4;uid:1 2 3 6)
    q)tb
    date       ht uid
    -----------------
    2025.02.27 0  1
    2025.02.28 1  2
    2025.03.01 2  3
    2025.03.02 3  6
    q)?[?[tb;enlist (in;`uid;raze key dict);(enlist `uid)!enlist `uid;`date`ht!`date`ht];();`uid;`date]
    1| 2025.02.27
    2| 2025.02.28
    3| 2025.03.01
    

    Note:

    1. The inner query gets wrapped in ?[...] for it to execute first.
    2. Rather than using the parse tree version of code like raze key dict it's cleaner to just execute it as is.

    Rather than nesting the queries, breaking them out will be more readable:

    q)t1:?[tb;enlist (in;`uid;raze key dict);(enlist `uid)!enlist `uid;`date`ht!`date`ht]
    q)t1
    t1
    uid| date       ht
    ---| -------------
    1  | 2025.02.27 0
    2  | 2025.02.28 1
    3  | 2025.03.01 2
    q)?[t1;();`uid;`date]
    1| 2025.02.27
    2| 2025.02.28
    3| 2025.03.01