4

I am trying to implement a multi line query from a python client using qpython.

I would like to perform the following query:

a = """
/declare a function that pivots a table on index
piv:{[t;k;p;v]f:{[v;P]`${raze "_" sv x} each string raze P,'/:v};v:(),v; k:(),k; p:(),p;G:group flip k!(t:.Q.v t)k;F:group flip p!t p;key[G]!flip(C:f[v]P:flip value flip key F)!raze{[i;j;k;x;y]a:count[x]#x 0N;a[y]:x y;b:count[x]#0b;b[y]:1b;c:a i;c[k]:first'[a[j]@'where'[b j]];c}[I[;0];I J;J:where 1<>count'[I:value G]]/:\:[t v;value F]};

/get aggregated trades table 
tt:0!select last_price:last price, last_qty: last qty, low_qty: min qty by exch,sym,side,1 xbar time.second from trades

/apply pivot function on aggregated trade table
piv[`tt;`second;`exch`sym`side;`last_price`last_qty`low_qty]
"""

And the following qpython client simply calls the remote kdb+/q server in order to retrieve a response to the above query

with qconnection.QConnection(host='localhost', port=5001, pandas = True) as q:
    q.query(qconnection.MessageType.SYNC, a)
    msg = q.receive(data_only=False, raw=False)
    print(msg)

however it raises the following _read_error:

qpython.qtype.QException: b'tt'

However the same queries executed on the remote server q shell run correctly? I think this might have something to do with dereferencing of the variables during deserialization, however I am not sure if this is due to the incorrect implementation of above client or malformed logic within the query.

What would be the canonical manner of implementing a multi line query such as the one above be?

James
  • 1,260
  • 13
  • 25

1 Answers1

3

Probably due to the lack of a semicolon at the end of the second line declaring the variable tt meaning those lines will be treated as one expression.

As q evaluates from right to left it will run the last line which calls piv which in turn calls t:.Q.v t with input tt before it has been declared.

Try changing the second line to include a semicolon

tt:0!select last_price:last price, last_qty: last qty, low_qty: min qty by exch,sym,side,1 xbar time.second from trades;

Mark Kelly
  • 1,780
  • 7
  • 16