KX Community

Find answers, ask questions, and connect with our KX Community around the world.
KX Community Guidelines

Home Forums kdb+ how to parse functional select in q Reply To: how to parse functional select in q

  • unterrainer_ale

    Member
    March 28, 2024 at 10:56 am

    Well it really depends what you actually want to do. they keyword parse (parse | Reference | kdb+ and q documentation – Kdb+ and q documentation (kx.com)) simply parses an expression into a parse tree, in this case it parses a q-sql statement into a functional select. The output you got, is what your qsql looks like in form of a functional select.

    q)parse "select time,sym,bid,ask from t"
    
    ?
    t
    ()
    0b
    time
    sym
    bid
    ask!
    time
    sym
    bid
    ask
    q)t:([] time:5?.z.p; sym:5?
    3; bid:5?10.0; ask:5?10.0)
    q)t
    time sym bid ask
    ---------------------------------------------------
    2014.11.16D17:25:17.686664320 enf 3.017723 3.927524
    2012.10.31D16:48:20.456221120 plh 7.85033 5.170911
    2016.10.06D02:12:56.529433024 nni 5.347096 5.159796
    2005.07.26D06:48:01.359027808 glc 7.111716 4.066642
    2016.10.09D03:08:41.154352640 gkp 4.11597 1.780839
    q)eval parse "select time,sym,bid,ask from t"
    
    time sym bid ask
    ---------------------------------------------------
    2014.11.16D17:25:17.686664320 enf 3.017723 3.927524
    2012.10.31D16:48:20.456221120 plh 7.85033 5.170911
    2016.10.06D02:12:56.529433024 nni 5.347096 5.159796
    2005.07.26D06:48:01.359027808 glc 7.111716 4.066642
    2016.10.09D03:08:41.154352640 gkp 4.11597 1.780839

    However, you don’t actually need to parse/transform your qsql to a functional select inside your function if you don’t really “want” (I recommend using functional selects only if you really need to, i.e. if you need to parameterise your queries)

    Here you have a function that takes a table as input and then selects from it using qsql

    q){select time,sym,bid,ask from x}[t]
    
    time sym bid ask
    ---------------------------------------------------
    2014.11.16D17:25:17.686664320 enf 3.017723 3.927524
    2012.10.31D16:48:20.456221120 plh 7.85033 5.170911
    2016.10.06D02:12:56.529433024 nni 5.347096 5.159796
    2005.07.26D06:48:01.359027808 glc 7.111716 4.066642
    2016.10.09D03:08:41.154352640 gkp 4.11597 1.780839

    A very helpful read about functional selects is the Whitepaper about parse trees.

    Parse trees and functional forms | White Paper | kdb+ and q documentation – Kdb+ and q documentation (kx.com)

    Hope this helps

    Alex