DEV Community

Fernando Paladini
Fernando Paladini

Posted on

Query KairosDB from Python and Load Results into a Spark DataFrame

Time-series data is useful only when it can move from storage into the tools that analyze it. KairosDB exposes a REST query endpoint, while Apache Spark gives you DataFrames for filtering and aggregation. The small open-source pySpark-connector-kairosdb project connects those two pieces with a minimal Python API.

This tutorial shows the smallest useful path: build a KairosDB query, send it through the connector, and understand how its Dataframe adapter turns the response into Spark-readable JSON. It also treats the project as it exists today. The repository describes itself as an alpha module, has no release tag, declares version 0.1.0, and leaves important dependencies to the user.

TL;DR

sconnk.Connection posts a JSON query to /api/v1/datapoints/query and returns the decoded response. sconnk.Dataframe then reduces KairosDB results into newline-delimited JSON and asks Spark SQL to read data.json. The client path is easy to verify locally with a mock HTTP endpoint. The DataFrame path needs a real PySpark installation and a KairosDB response with the shape the adapter expects.

Prerequisites

You need:

  • Python 3
  • a reachable KairosDB server, normally on port 8080
  • requests for the connector's HTTP client
  • PySpark if you use the Dataframe adapter
  • a checkout of pySpark-connector-kairosdb

The project is MIT licensed. Its setup.py reports version 0.1.0, uses distutils.core, and has an empty install_requires list. That means installing the package does not express the runtime requirements for requests or PySpark. Install and pin those dependencies in your own environment rather than assuming the package will provide them.

1. Install the connector and dependencies

From a fresh checkout, create an isolated environment and install the missing runtime pieces explicitly:

python -m venv .venv
source .venv/bin/activate
python -m pip install --upgrade pip
python -m pip install requests pyspark
python -m pip install .
Enter fullscreen mode Exit fullscreen mode

On Windows PowerShell, activate the environment with .venv\\Scripts\\Activate.ps1. If your current Python distribution cannot build or install this 2015-era package, keep the checkout on PYTHONPATH and install its runtime dependencies separately. That is a compatibility workaround, not a change to the project.

The package imports Dataframe from sconnk.__init__, so importing sconnk requires PySpark even when you only want the HTTP client. This is an important boundary: a client-only script can load sconnk/connection.py directly, but normal package imports need the full Spark dependency.

2. Build a KairosDB query

KairosDB's query API accepts a JSON object containing a time range and metrics. The repository README uses a relative range and metric limits. Here is a smaller query for one metric:

query_data = {
    "start_relative": {"value": "5", "unit": "years"},
    "metrics": [
        {"name": "cpu.load", "limit": 100}
    ],
}
Enter fullscreen mode Exit fullscreen mode

The exact metric name must exist in your KairosDB installation. The connector does not validate the query against a schema. It serializes the object with json.dumps, sends it to api/v1/datapoints/query, and parses the response body as JSON.

KairosDB documents port 8080 for its REST protocol and identifies /api/v1/datapoints as the REST ingestion endpoint. The connector's query implementation uses the corresponding /api/v1/datapoints/query path. Keep the server URL free of a second path segment because the connector appends the endpoint itself.

3. Query KairosDB through Connection

The minimal client workflow is:

from sconnk import Connection

query_data = {
    "start_relative": {"value": "5", "unit": "years"},
    "metrics": [{"name": "cpu.load", "limit": 100}],
}

conn = Connection("http://localhost:8080/")
response = conn.query(query_data)

print(response.keys())
print(response["queries"])
Enter fullscreen mode Exit fullscreen mode

The return value is a Python dictionary created from the server's JSON response. There is no status-code check, timeout argument, retry policy, authentication option, or error translation in the connector. A production wrapper should add those concerns around this small client instead of treating a successful requests.post call as proof that the query succeeded.

I verified this path with a local HTTP test server that asserted the connector posted to /api/v1/datapoints/query, checked the metric name, and returned {"queries": []}. The connector decoded that response as {'queries': []}. This verifies the request construction and JSON handling, not KairosDB itself.

4. Convert the response with Dataframe

The repository's second abstraction accepts the dictionary returned by Connection.query:

from sconnk import Connection, Dataframe

query_data = {
    "start_relative": {"value": "5", "unit": "years"},
    "metrics": [{"name": "cpu.load", "limit": 100}],
}

json_data = Connection("http://localhost:8080/").query(query_data)
df = Dataframe(json_data).df

df.printSchema()
df.show()
Enter fullscreen mode Exit fullscreen mode

Internally, Dataframe expects every item in json_data["queries"] to contain a non-empty results list. It selects the first result, keeps its name and values, writes one JSON object per line to a file named data.json, creates a local SparkContext, creates a SQLContext, and reads that file as a DataFrame.

That behavior explains both the convenience and the risk. The adapter gives you a quick bridge into Spark SQL, but it writes a fixed filename in the current working directory and creates its own Spark context. Two simultaneous calls can overwrite the same file, and an application that already owns a Spark session cannot configure this adapter's context through the public API.

Once the DataFrame exists, use ordinary Spark operations. Spark's official SQL guide shows the same pattern of creating a session, reading JSON, inspecting the schema, selecting columns, filtering, and grouping. The connector's output is not a native KairosDB source, so operations happen after the local JSON conversion.

Why the adapter works

KairosDB returns nested query results. The adapter flattens only one level:

KairosDB response
  queries
    results[0]
      name
      values

newline-delimited data.json
  {"name": "cpu.load", "values": [...]}

Spark DataFrame
  inferred columns: name, values
Enter fullscreen mode Exit fullscreen mode

This is a deliberately small design. The connector does not attempt to model every KairosDB field, normalize timestamps, expand tags, or preserve multiple result series. If your query returns several result objects or needs tag-aware analysis, inspect the raw response first and consider writing a custom transformation.

Failure modes to check first

The package fails during import

Install PySpark, even for a client-only use, or load the connection module directly. The unconditional import in sconnk/dataframe.py is the cause.

The query returns an empty result

Check the metric name, time range, tags, and KairosDB URL. The connector does not validate any of them. An empty queries response is valid JSON but cannot produce a useful DataFrame.

Dataframe raises an index error

The adapter assumes results[0] exists for every query. Inspect the raw response before constructing the adapter and handle empty result sets in your application.

data.json contains stale or mixed rows

The filename is fixed and the file is opened with write mode. Run one conversion at a time, use an isolated working directory, or replace the adapter with code that writes to a unique temporary file.

Security boundaries and limitations

The connector sends HTTP requests to the configured hostname and has no authentication, TLS enforcement, certificate configuration, timeout, retry, or redaction layer. Do not point it at a sensitive KairosDB deployment until you have added the controls your environment requires. Avoid logging responses if metric values or tags contain sensitive information.

The repository is an archived-in-place style experiment, not a maintained compatibility promise. The README calls it alpha, the code targets old Spark APIs, and the implementation has no tests or dependency pins. Treat it as a reference adapter and validate it against your Python, PySpark, and KairosDB versions before adopting it.

FAQ

Does this package install PySpark automatically?

No. setup.py declares no runtime dependencies. Install requests and PySpark explicitly.

Can I use it without a KairosDB server?

You can verify the HTTP request path with a mock server, as shown above. A meaningful DataFrame still requires a KairosDB response with populated query results.

Does it preserve every KairosDB field?

No. The adapter keeps the first result's name and values. Tags, metadata, and additional result objects are not modeled by Dataframe.

Takeaway

pySpark-connector-kairosdb is useful as a compact example of a REST-to-Spark bridge: construct a KairosDB query, retrieve JSON, reduce the response, and read it with Spark SQL. Its small size also makes the tradeoffs visible. Add dependency management, response validation, safe temporary files, connection ownership, and security controls before treating the pattern as production code.

What would you change first in this adapter: dependency metadata, response normalization, or a SparkSession-based API?

AI assistance disclosure: AI assistance was used to organize and edit this tutorial. The repository code, current README, setup metadata, license, KairosDB documentation, Spark documentation, and the local HTTP smoke test were checked against the claims above.

Top comments (0)