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:
- version (
NotRequired[int]) – Integer SQL dialect version (SQL and getMeta only);2selects SQL2. A string is rejected. See SQL2. - timeout (
NotRequired[int]) – Server-side timeout in milliseconds. Defaults to the server'sKXI_SG_TIMEOUT. The client has its own request timeout (20 s by default). - logCorr (
NotRequired[str]) – Log correlator, to trace the request in the logs. - auditID (
NotRequired[str]) – Audit ID, to trace the request in the logs. - sendPartials (
NotRequired[bool]) – Return DAP partial results if an aggregation fails, for debugging UDAs. - rowFilterDebug (
NotRequired[bool]) – Return row filter debugging information. - aggregator (
NotRequired[str]) – Aggregator to use (getData). - cast (
NotRequired[bool]) – Cast the result columns (getData). - aggFn (
NotRequired[str]) – Deprecated.
Query¶
Bases: ApiClient
Python API for querying kdb Insights and kdb Insights Enterprise.
See Connection Parameters for shared constructor arguments.
Attributes:
- udas (
'UdaNamespace') – A namespace of UDAs (User-Defined Analytics) available on the connected instance. See: UDA (User-Defined Analytic) object model for kdb Insights for details.
Functions:
- fetch_custom_apis – Query the database for custom APIs and attach them as additional attributes.
- get_data – Run a getData.
- get_meta – Run a getMeta.
- get_table_schemas – Get table schemas in the format of {"table": {"col": pykxtype}}.
- ping – Run a ping.
- preview – Run a preview.
- qsql – Run a qSQL.
- refresh_udas – Re-fetch UDAs from getMeta and return the updated namespace.
- sql – Run an SQL.
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 Pythonstritems defining the columns to group aggregations by - aggregations (
Optional[List[list]]) – A list of Pythonstritems or a list of lists ofstritems defining. The columns to be returned from the table across DAPs if defined as a list ofstr. If provided as a list of triadic Python lists as follows[['assignName', 'agg', 'column'], ...]thenassignNamedefines the name to be assigned to the return of the aggregation,aggdefines the aggregation function to be used andcolumndefines 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 singlestritem with valueforwardto define the use of the last non-null value in a column orzeroto replace all null values with the 0 value of that column. - temporality (
Optional[str]) – This determines the way that thestart_timeandend_timearguments 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 thestart_timeandend_timerange when a temporality of'slice'is used. - sort_columns (
Optional[List[str]]) – This should be a Python list ofstrtype 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 asscope. See Scope. - limit (
Optional[int]) – The maximum number of rows to return, sent aslimit. - output_timezone_columns (
Optional[List[str]]) – The timestamp columns to convert tooutput_timezone, sent asoutputTZCols. - opts (
Optional[Opts]) – Additional request options, sent asopts. 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– Apykx.Tableorpykx.KeyedTablereturned 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 asopts.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 overversion. - use_qe (
bool) – Indicate whether to use the QE or PROD environment.
Returns:
Dictionary– Apykx.Dictionarycontaining 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 asopts. See Opts. - use_qe (
bool) – Indicate whether to use the QE or PROD environment.
Returns:
BooleanVector– A list of booleans.
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 asopts. 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, usescope={"assembly": ...}. The Assembly name to query, must support query environment. - target (
str | None) – Deprecated, usescope={"tier": ...}. The DAP instance to query. Requiresassembly. - use_qe (
bool) – Indicate whether to use the QE or PROD environment. - scope (
Scope | None) – Target a specific assembly, tier or DAP, sent asscope. The accepted keys areassembly,tier,dapandaffinity, see Scope. When omitted, no scope is sent and the query is distributed across tiers. Some gateway versions still requirescope.assemblyandscope.tierand reject a qSQL request without them. To query one DAP, givescope.assemblyandscope.dap. - agg (
str | None) – The aggregation function used to combine the results from each DAP. - opts (
Opts | None) – Additional request options, sent asopts. See Opts.
Returns:
K– Apykx.Kreturned from a query to kdb Insights Enterprise
Raises:
TypeError–assemblyortargetis combined withscope, ortargetis given withoutassembly.
Warns:
DeprecationWarning–assemblyortargetis used. The qSQL API deprecatesargs.assemblyandargs.targetin favour ofargs.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 refreshedUdaNamespace.
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. Unlikeqsqland UDAs,sqldefaults to the QE. Query Environments are off by default since 1.13; passuse_qe=Falseon those deployments. - scope (
Optional[Scope]) – Target scope for the query. See Scope.tieranddapare 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 asopts.version;opts["version"]takes precedence.2selects SQL2, which differs from the old SQL in column order forSELECT *, trailing zeros, and default output column names. When unset, the server decides. - *kwargs* – Additional parameters.
Returns:
Table– Apykx.Tableorpykx.KeyedTablereturned from a query to kdb Insights Enterprise
Raises:
QueryEnvironmentUnavailableError–use_qeis True and the QE gateway is not reachable, e.g. because Query Environments are not enabled.
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'sKXI_SCOPE_AFFINITYdefault).
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). |