如何在kdb中创建游标? [英] How to create a cursor in kdb?

查看:78
本文介绍了如何在kdb中创建游标?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想遍历时间序列中所有行,分区的kdb数据库并在每个步骤中执行一些计算.在SQL中,可以使用游标完成此操作. kdb中有类似的东西吗?

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?

某些背景:数据库由几百万个时间序列记录组成,当我在行中前进时,我需要维护许多对象的状态.我需要在每个步骤中运行一些"if"语句.我本以为将计算结果集成到查询中,但是由于必须执行的测试数量众多,我认为使用游标或类似行回调的方法更为合适.在重播"数据库时运行自定义代码的最有效解决方案是什么?

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?

推荐答案

q中的表的行为与字典列表非常相似.因此,如果t是表,则t [0]将是将列名映射到值的第一行的字典,t [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

另一方面,可能更惯用的方式是将操作应用于列表元素的方式是 each 运算符:

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

这篇关于如何在kdb中创建游标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆