Getting Started

Getting Started with kdb+/q

An introduction to the kdb+ database and the q programming language.

What is kdb+/q?

kdb+ is a high-performance, column-oriented time-series database developed by KX. It is widely used in financial services for storing and analysing large volumes of time-series data such as market tick data.

q is the programming language built into kdb+. It is a concise, vector-oriented language built on k, which descends from APL. Operations apply to whole lists at once, so many tasks that need an explicit loop in other languages are a single expression in q.

The q Console

Start q by running q from your terminal. After a short banner you will see the prompt:

q)

Everything in q returns a value. Type an expression and press Enter:

q)1+1
2
q)2*3 4 5
6 8 10

Basic Data Types

/ Long (the default integer type)
x: 42

/ Float
f: 3.14

/ Boolean
b: 1b        / true
c: 0b        / false

/ Character
ch: "a"

/ Symbol
s: `AAPL

/ String (list of chars)
str: "hello world"

Lists

Lists are the core data structure. They are typed or mixed:

/ Typed list of longs
nums: 1 2 3 4 5

/ Typed list of floats
prices: 100.5 101.2 99.8

/ Typed list of symbols
syms: `AAPL`GOOG`MSFT

/ Access by index (0-based)
nums[0]     / 1
nums[2]     / 3

/ Slicing
nums[1 3]   / 2 4

/ Length
count nums  / 5

/ Arithmetic on lists (vector operations)
nums * 2    / 2 4 6 8 10
nums + 10   / 11 12 13 14 15

Defining Functions

Functions in q are lambdas enclosed in curly braces:

/ Single-argument function (implicit x)
double: {x * 2}
double[5]    / 10

/ Multi-argument function
add: {[a;b] a + b}
add[3;4]     / 7

/ Functions are first-class values
apply: {[f;val] f val}
apply[double; 7]   / 14

Applying Functions Over Lists

q calls the operators that apply a function repeatedly iterators. The each keyword applies a function to every item of a list:

double each 1 2 3 4 5    / 2 4 6 8 10

/ Equivalent, using the Each iterator ' directly
double'[1 2 3 4 5]       / 2 4 6 8 10

Write ' straight after the function with no space, and apply the result with brackets as shown. double ' 1 2 3, with a space, fails to parse.

The Over iterator / folds (reduces) a list to a single value:

(+/) 1 2 3 4 5    / 15  (the same as sum)
(*/) 1 2 3 4 5    / 120 (the same as prd)

The Scan iterator \ is like Over, but returns every intermediate result:

(+\) 1 2 3 4 5    / 1 3 6 10 15  (running sum, the same as sums)

Next Steps

With the basics covered, explore:

  • Dictionaries — key-value mappings that underpin tables
  • Tables — the column-oriented data structure at the heart of kdb+
  • qSQL — the SQL-like query language for tables