How to create a cursor in kdb?

蹲街弑〆低调 提交于 2019-12-08 02:52:11

问题


I want to iterate over all the rows in a time series, partitioned kdb database and perform some calculation at each step. In SQL this could be done with a cursor. Is there something similar in kdb?

Some background: the database consist of several million time series records and I need to maintain a state for a number of objects as I progress through the rows. There are a few 'if' statements I need to run at each step. I thought to integrate my calculation in a query, but because of the number of tests I have to perform I think a cursor or something like a row callback would be more appropriate. What's the most efficient solution to run custom code while "replaying" the database?


回答1:


Tables in q behave much like lists of dictionaries. So if t is a table, t[0] would be a dictionary mapping column names to the first row of values, t[1] would be the second row, and so on. So in effect your cursor is just an index and progressing the cursor is just incrementing the index.

q)t:([]c1:1 2 3;c2:`a`b`c);
q)show t[0];
c1| 1
c2| `a
q)show t[1];
c1| 2
c2| `b

On the other hand, probably the more idiomatic way to apply an operation to a list element-wise is with the each operator:

q)f:{show x};
q)f each t;
c1| 1
c2| `a
c1| 2
c2| `b
c1| 3
c2| `c


来源:https://stackoverflow.com/questions/16803232/how-to-create-a-cursor-in-kdb

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!