Querying¶
kxi.query.Query provides an authenticated connection to kdb Insights Enterprise for running SQL queries, getData API calls, UDAs and metadata inspection.
Creating a connection¶
Pass credentials explicitly or rely on environment variables:
import kxi.query
# From environment variables (INSIGHTS_URL, INSIGHTS_CLIENT_ID, INSIGHTS_CLIENT_SECRET)
conn = kxi.query.Query()
# Explicit credentials
conn = kxi.query.Query(
host="https://my-insights.kx.com",
client_id="my-client-id",
client_secret="my-client-secret",
)
# Return JSON instead of pykx objects
conn = kxi.query.Query(data_format="application/json")
Connection parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
host |
str |
$INSIGHTS_URL |
Base URL of the kdb Insights Enterprise instance |
client_id |
str |
$INSIGHTS_CLIENT_ID |
Keycloak client ID |
client_secret |
str |
$INSIGHTS_CLIENT_SECRET |
Keycloak client secret |
realm |
str |
$INSIGHTS_REALM or insights |
Keycloak realm |
data_format |
str |
application/octet-stream |
Response format; use application/json without pykx |
timeout |
int |
20 |
Token request timeout in seconds |
Request options¶
Query methods share a common set of request options. Each method's reference lists the ones it accepts.
| Option | Type | Description |
|---|---|---|
scope |
Scope |
Target a specific assembly, tier or dap, with optional affinity (soft or hard). tier, dap and affinity require assembly; tier and dap cannot be combined. |
labels |
dict[str, str] |
Only use DAPs in assemblies matching these labels. |
opts |
Opts |
Additional request options, such as version. |
use_qe |
bool |
Route to the Query Environment gateway instead of production. |
A scope key an API does not support (for example scope.tier on sql) emits a
UserWarning and is still sent, so existing calls keep working.
sql¶
Run a SQL query against the kdb Insights query environment.
# Basic SELECT
result = conn.sql("SELECT * FROM my_table LIMIT 100")
# With a WHERE clause
result = conn.sql("SELECT sym, price FROM trades WHERE side = 'BID'")
# Aggregation
result = conn.sql("SELECT sym, AVG(price) AS avg_price FROM trades GROUP BY sym")
Returns a pykx.Table:
result = conn.sql("SELECT * FROM my_table LIMIT 5")
# pykx.Table(pykx.q('...'))
df = result.pd() # convert to pandas DataFrame
Returns a dict with a payload key containing a list of row dicts:
conn = kxi.query.Query(data_format="application/json")
result = conn.sql("SELECT * FROM my_table LIMIT 5")
rows = result["payload"]
SQL2¶
Pass version=2 to use SQL2. It uses the same endpoint as plain SQL; version is sent as
opts.version and merged with any opts you pass. The server validates the value: 3 is rejected
as an unknown SQL version, and 1 was rejected by the gateway this was tested against.
result = conn.sql("SELECT * FROM my_table", version=2)
SQL2 differs from the old SQL: virtual columns come first in SELECT *, trailing zeros are not
retained, and unspecified output column names follow kdb+ rather than PostgreSQL defaults. When
version is not set the server decides: it uses SQL2 and falls back to the old SQL when SQL2
cannot handle a query, depending on KXI_ALLOWED_SBX_APIS.
Note
sql queries the Query Environment by default (use_qe=True), unlike qsql and UDAs, which
default to production. Pass use_qe=False on deployments without Query Environments.
qsql¶
Run a qSQL query.
# Distributed across tiers: no scope is sent
# (some gateway versions still require scope.assembly and scope.tier)
result = conn.qsql("select from my_table")
# Target an assembly and tier
result = conn.qsql("select from my_table", scope={"assembly": "my-pkg", "tier": "rdb"})
# Target one DAP
result = conn.qsql("select from my_table", scope={"assembly": "my-pkg", "dap": "my-dap"})
# Combine the results from each DAP with an aggregation function
result = conn.qsql("select from my_table", agg=".my.agg")
| Parameter | Type | Description |
|---|---|---|
query |
str |
The qSQL query |
scope |
dict |
Target an assembly, tier or dap. See Request options. When omitted the query is distributed across tiers |
agg |
str |
Aggregation function that combines the results from each DAP (keyword-only) |
opts |
dict |
Additional request options (keyword-only) |
use_qe |
bool |
Query the Query Environment instead of production. Default: False |
Deprecated: assembly and target
The assembly and target arguments are deprecated and raise a DeprecationWarning. They
are sent as scope.assembly and scope.tier. Use scope instead. Passing them together with
scope raises a TypeError, as does target without assembly.
qsql¶
Run a qSQL query.
# Distributed across tiers: no scope is sent
# (some gateway versions still require scope.assembly and scope.tier)
result = conn.qsql("select from my_table")
# Target an assembly and tier
result = conn.qsql("select from my_table", scope={"assembly": "my-pkg", "tier": "rdb"})
# Target one DAP
result = conn.qsql("select from my_table", scope={"assembly": "my-pkg", "dap": "my-dap"})
# Combine the results from each DAP with an aggregation function
result = conn.qsql("select from my_table", agg=".my.agg")
| Parameter | Type | Description |
|---|---|---|
query |
str |
The qSQL query |
scope |
dict |
Target an assembly, tier or dap. See Request options. When omitted the query is distributed across tiers |
agg |
str |
Aggregation function that combines the results from each DAP (keyword-only) |
opts |
dict |
Additional request options (keyword-only) |
use_qe |
bool |
Query the Query Environment instead of production. Default: False |
Deprecated: assembly and target
The assembly and target arguments are deprecated and raise a DeprecationWarning. They
are sent as scope.assembly and scope.tier. Use scope instead. Passing them together with
scope raises a TypeError, as does target without assembly.
get_data¶
get_data provides structured access to kdb+ timeseries tables in kdb Insights with built-in support for time ranges, filters, grouping, and aggregations.
Basic usage¶
result = conn.get_data("my_table")
Time range¶
result = conn.get_data(
"my_table",
start_time="2024.01.01D09:00:00.000000000",
end_time="2024.01.01D17:00:00.000000000",
)
Filtering¶
Filters are triadic lists: [function, column, value].
result = conn.get_data(
"my_table",
filter=[
["=", "sym", "AAPL"],
["within", "price", [100.0, 200.0]],
],
)
Grouping and aggregations¶
result = conn.get_data(
"my_table",
group_by=["sym"],
aggregations=[
["avg_price", "avg", "price"],
["total_qty", "sum", "qty"],
],
)
All parameters¶
| Parameter | Type | Description |
|---|---|---|
table |
str |
Table name to query |
start_time |
str |
Inclusive start time (q timestamp format) |
end_time |
str |
Exclusive end time (q timestamp format) |
input_timezone |
str |
Timezone for start/end times. Default: UTC |
output_timezone |
str |
Timezone for returned timestamps. Default: UTC |
filter |
list |
Filter conditions as [['fn', 'col', value], ...] |
group_by |
list[str] |
Columns to group aggregations by |
aggregations |
list |
Columns to return, or [['name', 'agg', 'col'], ...] |
fill |
str |
Null handling: forward or zero |
temporality |
str |
Time interpretation: slice or snapshot |
slice |
list[str] |
Intra-day time range used with temporality='slice' |
sort_columns |
list[str] |
Columns to sort results by |
labels |
dict[str, str] |
Assembly label filters for DAP selection |
scope |
dict |
Target an assembly, tier or dap. See Request options |
limit |
int |
Maximum number of rows to return |
output_timezone_columns |
list[str] |
Timestamp columns to convert to output_timezone. Sent as outputTZCols |
opts |
dict |
Additional request options |
use_qe |
bool |
Query the Query Environment instead of production. Default: False |
Any other keyword argument is passed through unchanged, so the raw wire name
outputTZCols= also works.
preview¶
Fetch a small sample of a table using minimal time and resources, to review its contents or check compatibility with a schema.
result = conn.preview("my_table", limit=10)
| Parameter | Type | Description |
|---|---|---|
table |
str |
Table name |
start_time |
str |
Inclusive start time. Default: 15 minutes ago |
end_time |
str |
Exclusive end time. Default: now |
limit |
int |
Maximum number of rows to return |
opts |
dict |
Additional request options (keyword-only) |
use_qe |
bool |
Query the Query Environment instead of production. Default: False (keyword-only) |
get_meta¶
Retrieve metadata about assemblies, schemas, and available APIs on the deployment.
meta = conn.get_meta()
assemblies = meta["assembly"] # deployed assemblies
schemas = meta["schema"] # table schemas with column types
apis = meta["api"] # available API endpoints
daps = meta["dap"] # data access process instances
Versions¶
get_meta() returns the legacy (v1) response. Pass version=3 for
getMeta v3. v3 is not a
superset of v1:
- there is no
aggsection; apientries are flattened:params,return,description,misc,udaandpackageare top-level columns instead of being nested undermetadata, and there is nocustomflag;assemblyentries gainlabels.
meta = conn.get_meta(version=3)
udas = [api for api, is_uda in zip(meta["api"]["api"], meta["api"]["uda"]) if is_uda]
version is keyword-only and is sent as opts.version.
Parameters¶
| Parameter | Type | Description |
|---|---|---|
version |
int |
getMeta version. Default: 1 |
start_time |
str |
Start of the time range to report on |
end_time |
str |
End of the time range to report on |
labels |
dict[str, str] |
Assembly label filters for DAP selection |
advanced |
bool |
Request the extended metadata, where supported |
opts |
dict |
Additional request options. opts["version"] overrides version |
use_qe |
bool |
Query the Query Environment instead of production. Default: False |
ping¶
Check that a target process can be reached. Returns a list of booleans.
conn.ping()
conn.ping(labels={"region": "emea"})
| Parameter | Type | Description |
|---|---|---|
labels |
dict[str, str] |
Only ping DAPs in assemblies matching these labels |
opts |
dict |
Additional request options (keyword-only) |
use_qe |
bool |
Ping the Query Environment instead of production. Default: False (keyword-only) |
Error handling¶
Query errors raise typed exceptions from kxi.exceptions:
from kxi.exceptions import ClientQueryError, UnauthorizedError
try:
result = conn.sql("SELECT * FROM non_existent_table")
except ClientQueryError as e:
print(f"Query error: {e.info.get('ai')}")
except UnauthorizedError:
print("Authentication failed — check client credentials")