Skip to content

Python Querying API.

The following documentation defines a Python API to be used when querying the kdb Insights and kdb Insights Enterprise Offerings.

Classes:

  • Opts – Service Gateway request options.
  • Query – Python API for querying kdb Insights and kdb Insights Enterprise.
  • Scope – Target scope for a query.

Functions:

  • is_sql_not_enabled – Whether the query failed because SQL is not enabled in the targeted environment.

Opts

Bases: TypedDict

Service Gateway request options.

See the request header for details. Keys starting with app are passed through to the application.

Attributes:

Query

Bases: ApiClient

Python API for querying kdb Insights and kdb Insights Enterprise.

See Connection Parameters for shared constructor arguments.

Attributes:

Functions:

fetch_custom_apis

fetch_custom_apis()

Query the database for custom APIs and attach them as additional attributes.

get_data

get_data(table, start_time=lambda: datetime.now(tz=timezone.utc) - timedelta(minutes=15), end_time=lambda: datetime.now(tz=timezone.utc), *, input_timezone=None, output_timezone=None, filter=None, group_by=None, aggregations=None, fill=None, temporality=None, slice=None, sort_columns=None, labels=None, scope=None, limit=None, output_timezone_columns=None, opts=None, use_qe=False, **kwargs)

Run a getData.

API call on kdb Insights Enterprise.

Parameters:

  • table (str) – The name of the table from which to retrieve data
  • start_time (str | datetime | None) – The earliest time data is to be queried from, by default this is 15 minutes prior to the time that the get_data call is made.
  • end_time (str | datetime | None) – The latest time data is to be queried from, by default this is the time that the get_data function is called.
  • input_timezone (Optional[str]) – The timezones of start_time and end_time, default is UTC if not specified.
  • output_timezone (Optional[str]) – The timezone of output timestamp columns, default is UTC if not specified.
  • filter (Optional[List[list]]) – A list of triadic Python lists defining filter conditions in the format [['function', 'column name', 'parameter'], ... ]
  • group_by (Optional[str]) – A list of Python str items defining the columns to group aggregations by
  • aggregations (Optional[List[list]]) – A list of Python str items or a list of lists of str items defining. The columns to be returned from the table across DAPs if defined as a list of str. If provided as a list of triadic Python lists as follows [['assignName', 'agg', 'column'], ...] then assignName defines the name to be assigned to the return of the aggregation, agg defines the aggregation function to be used and column defines the column on which that aggregation is applied.
  • fill (Optional[str]) – This defines how to handle the presence of null values. This should be supplied as a single str item with value forward to define the use of the last non-null value in a column or zero to replace all null values with the 0 value of that column.
  • temporality (Optional[str]) – This determines the way that the start_time and end_time arguments are interpreted. The two support input types are 'slice' and 'snapshot'.
  • slice (Optional[str]) – This should be defined as a Python list of 'times' which denote the time range to grab between each date in the start_time and end_time range when a temporality of 'slice' is used.
  • sort_columns (Optional[List[str]]) – This should be a Python list of str type objects denoting the columns which are to be sorted on.
  • labels (Optional[Dict[str, str]]) – labels defined in the assembly file of the DAPs can be used to only select data from DAPs in assemblies matching that label.
  • scope (Optional[Scope]) – Target a specific assembly, tier or DAP, sent as scope. See Scope.
  • limit (Optional[int]) – The maximum number of rows to return, sent as limit.
  • output_timezone_columns (Optional[List[str]]) – The timestamp columns to convert to output_timezone, sent as outputTZCols.
  • opts (Optional[Opts]) – Additional request options, sent as opts. See Opts.
  • use_qe (bool) – Indicate whether to use the QE or PROD environment.
  • *kwargs* – Other possible arguments, such as the raw outputTZCols.

Returns:

  • Table – A pykx.Table or pykx.KeyedTable returned from a query to kdb Insights Enterprise

Examples:

Connect to a running instance of kdb Insights and query using get_data with default values

import kxi.query
conn = kxi.query.Query()
conn.get_data('my_table')

Query the instance providing arguments to various get_data calls.

conn.get_data('my_table', group_by = ['sensorID', 'qual'])
conn.get_data('my_table', filter = [['within', 'qual', [0, 2]]])
conn.get_data('my_table', start_time='2000.05.26',end_time='2000.05.27')

get_meta

get_meta(*, version=1, start_time=None, end_time=None, labels=None, advanced=None, opts=None, use_qe=False)

Run a getMeta.

API call on kdb Insights Enterprise.

The default version=1 response is unchanged. version=3 is the preferred getMeta v3 and is not a superset of v1: it has no agg section, its api entries are flattened (params, return, description, misc, uda and package are top-level columns rather than nested under metadata, and there is no custom flag), and its assembly entries gain labels.

Parameters:

  • version (int) – The getMeta version, sent as opts.version.
  • start_time (str | datetime | None) – Only report data in the time range starting here.
  • end_time (str | datetime | None) – Only report data in the time range ending here.
  • labels (Optional[Dict[str, str]]) – labels defined in the assembly file of the DAPs can be used to only select data from DAPs in assemblies matching that label.
  • advanced (Optional[bool]) – Request the extended metadata, where the API supports it.
  • opts (Optional[Opts]) – Additional request options. opts["version"] takes precedence over version.
  • use_qe (bool) – Indicate whether to use the QE or PROD environment.

Returns:

  • Dictionary – A pykx.Dictionary containing metadata information about the various processes and schemas which describe a database.

Examples:

Connect to a running instance of kdb Insights and retrieve metadata information about the database, schemas and assemblies

import kxi.query
conn = kxi.query.Query()
conn.get_meta()
conn.get_meta(version=3, labels={"region": "emea"})

get_table_schemas

get_table_schemas(assembly=None)

Get table schemas in the format of {"table": {"col": pykxtype}}.

Parameters:

  • assembly (str | None) – Optional assembly name to filter for.

Returns:

Example
query.get_table_schemas()
{
    "tableName": {
        "col1": kxi.util.QType(-12, pykx.TimestampAtom, "timestamp", "p")
    }
}

ping

ping(labels=None, *, opts=None, use_qe=False)

Run a ping.

This API is intended to run on a data access process and returns true if it reaches a target

Parameters:

  • labels (Optional[dict]) – labels defined in the assembly file of the DAPs can be used to only select data from DAPs in assemblies matching that label.
  • opts (Optional[Opts]) – Additional request options, sent as opts. See Opts.
  • use_qe (bool) – Indicate whether to use the QE or PROD environment.

Returns:

preview

preview(table, start_time=None, end_time=None, limit=None, *, opts=None, use_qe=False)

Run a preview.

The preview API is a lightweight data retrieval API which is able to fetch small samples of a table using minimal time and resources, for you to review or to use in testing software compatibility with a schema.

Parameters:

  • table (str) – The name of the table from which to retrieve data
  • start_time (str | datetime | None) – The earliest time data is to be queried from, by default this is 15 minutes prior to the time that the get_data call is made.
  • end_time (str | datetime | None) – The latest time data is to be queried from, by default this is the time that the get_data function is called.
  • limit (int | None) – The maximum number of rows to return.
  • opts (Opts | None) – Additional request options, sent as opts. See Opts.
  • use_qe (bool) – Indicate whether to use the QE or PROD environment.

qsql

qsql(query, assembly=None, target=None, use_qe=False, *, scope=None, agg=None, opts=None)

Run a qSQL.

API call on kdb Insights Enterprise.

Parameters:

  • query (str) – The qSQL query to run.
  • assembly (str | None) – Deprecated, use scope={"assembly": ...}. The Assembly name to query, must support query environment.
  • target (str | None) – Deprecated, use scope={"tier": ...}. The DAP instance to query. Requires assembly.
  • use_qe (bool) – Indicate whether to use the QE or PROD environment.
  • scope (Scope | None) – Target a specific assembly, tier or DAP, sent as scope. The accepted keys are assembly, tier, dap and affinity, see Scope. When omitted, no scope is sent and the query is distributed across tiers. Some gateway versions still require scope.assembly and scope.tier and reject a qSQL request without them. To query one DAP, give scope.assembly and scope.dap.
  • agg (str | None) – The aggregation function used to combine the results from each DAP.
  • opts (Opts | None) – Additional request options, sent as opts. See Opts.

Returns:

  • K – A pykx.K returned from a query to kdb Insights Enterprise

Raises:

  • TypeError – assembly or target is combined with scope, or target is given without assembly.

Warns:

  • DeprecationWarning – assembly or target is used. The qSQL API deprecates args.assembly and args.target in favour of args.scope.

Examples:

Connect to a running instance of kdb Insights and query using qsql

import kxi.query
conn = kxi.query.Query()
conn.qsql('my_table', scope={"assembly": "assembly-qe", "tier": "rdb"})

refresh_udas

refresh_udas()

Re-fetch UDAs from getMeta and return the updated namespace.

Call this if the deployment has changed since the last access.

Returns:

  • 'UdaNamespace' – The refreshed UdaNamespace.
Example
conn.refresh_udas()
conn.udas.example.daAPI(table="trade", column="price")

sql

sql(query, use_qe=True, scope=None, opts=None, *, version=None, **kwargs)

Run an SQL.

API call on kdb Insights Enterprise.

Parameters:

  • query (str) – The SQL query which is to be run against the query environment
  • use_qe (bool) – Whether to query the QE (default) or PROD environment. Unlike qsql and UDAs, sql defaults to the QE. Query Environments are off by default since 1.13; pass use_qe=False on those deployments.
  • scope (Optional[Scope]) – Target scope for the query. See Scope. tier and dap are not supported by the SQL API; passing either warns and the server rejects it.
  • opts (Optional[Opts]) – Additional options for the query. See Opts.
  • version (int | None) – SQL dialect version, sent as opts.version; opts["version"] takes precedence. 2 selects SQL2, which differs from the old SQL in column order for SELECT *, trailing zeros, and default output column names. When unset, the server decides.
  • *kwargs* – Additional parameters.

Returns:

  • Table – A pykx.Table or pykx.KeyedTable returned from a query to kdb Insights Enterprise

Raises:

Examples:

Connect to a running instance of kdb Insights and query using sql

import kxi.query
conn = kxi.query.Query()
conn.sql('SELECT * FROM my_table')

udas

udas: 'UdaNamespace'

Lazy UDA namespace — tab-complete across q namespaces.

Scope

Bases: TypedDict

Target scope for a query.

Attributes:

  • assembly (NotRequired[str]) – The assembly (package) to target.
  • tier (NotRequired[str]) – A data tier within the assembly. Not supported by the SQL API: with sql it triggers a warning and the server rejects the request.
  • dap (NotRequired[str]) – A specific DAP (Data Access Process) within the assembly. Not supported by the SQL API: with sql it triggers a warning and the server rejects the request.
  • affinity (NotRequired[Literal['soft', 'hard', '']]) – 'soft' (prefer the target, with fallback), 'hard' (fail if the target is unavailable) or '' (use the server's KXI_SCOPE_AFFINITY default).

is_sql_not_enabled

is_sql_not_enabled(error)

Whether the query failed because SQL is not enabled in the targeted environment.

Constants

Name Type Value Description
DEFAULT_TIMEOUT 20 Default request timeout, in seconds. None means no timeout, as in httpx.
SCOPE_DESCRIPTIONS Dict[str, str] — Short description of each Scope key.
SQL_UNSUPPORTED_SCOPE_KEYS ('tier', 'dap') The Scope keys the SQL API does not support.
OPTS_DESCRIPTIONS Dict[str, str] — Short description of each Opts key.
SQL_OPTS_KEYS ('version', 'timeout', 'logCorr', 'auditID') The Opts keys that apply to SQL queries.
UDA_OPTS_KEYS ('timeout', 'logCorr', 'auditID', 'sendPartials') The Opts keys that apply to UDA queries.
SQL_NOT_ENABLED 'SQL not enabled' What the server says when SQL is not enabled in the targeted environment (by default only in query environments, see KXI_ALLOWED_SBX_APIS).
Back to top