Powered by AppSignal & Oban Pro

Time-series with Arcadic

timeseries.livemd

Time-series with Arcadic

Use this tutorial to store sensor readings, query them with PromQL, and manage downsampling and continuous aggregates. The notebook uses a throwaway time-series database.

Setup

Start ArcadeDB over HTTP. See Compatibility for the time-series server requirement:

docker run -d --name arcadic-timeseries \
  -p 2480:2480 \
  -e JAVA_OPTS="-Darcadedb.server.rootPassword=playwithdata" \
  arcadedata/arcadedb:26.11.1

HTTP on port 2480 serves both time-series requests and PromQL reads.

Every connection value can be overridden with an environment variable set before you launch Livebook (ARCADIC_HTTP_URL, ARCADIC_PASSWORD); otherwise the defaults match the docker run above.

Re-running cells. The aggregate and downsampling cells clean up their own changes. Define the type drops any previous sensor type before creating it. Re-running a write cell appends points and increases row counts. Use Cleanup before starting again.

Install

Mix.install([
  {:arcadic, "~> 3.1"},
  {:kino, "~> 0.14"}
])

Connect

We create a throwaway arcadic_timeseries database to play in (only if it does not already exist, so this cell is safe to re-run).

http_url = System.get_env("ARCADIC_HTTP_URL", "http://localhost:2480")
password = System.get_env("ARCADIC_PASSWORD", "playwithdata")
database = "arcadic_timeseries"

admin = Arcadic.connect(http_url, database, auth: {"root", password})
{:ok, true} = Arcadic.Server.ready?(admin)

unless match?({:ok, true}, Arcadic.Server.database_exists?(admin, database)) do
  Arcadic.Server.create_database!(admin, database)
end

conn = Arcadic.connect(http_url, database, auth: {"root", password})

Define the type

Arcadic.TimeSeries.create_type!/4 emits CREATE TIMESERIES TYPE, a sensor type tagged by sensor_id/location, carrying temperature/humidity fields, millisecond precision, and a 90-day retention window.

# No IF NOT EXISTS on 26.7.2 -- the discarded drop makes this cell safe to re-run
# in isolation (dropping a not-yet-existing type errors too; `_ =` discards either way).
_ = Arcadic.TimeSeries.drop_type(conn, "sensor")

:ok =
  Arcadic.TimeSeries.create_type!(conn, "sensor", "ts",
    fields: [temperature: "DOUBLE", humidity: "DOUBLE"],
    tags: [sensor_id: "STRING", location: "STRING"],
    precision: :millisecond,
    retention: {90, :days}
  )

Writing points

Arcadic.TimeSeries.write/3 builds InfluxDB line protocol from point maps. Pass precision: :ms for the epoch-millisecond timestamps below. The default wire precision is nanoseconds, which places a millisecond timestamp in January 1970. See Time-series precision and delivery for the units.

now_ms = System.system_time(:millisecond)

:ok =
  Arcadic.TimeSeries.write(
    conn,
    [
      %{
        type: "sensor",
        tags: %{"sensor_id" => "s1", "location" => "lab-a"},
        fields: %{"temperature" => 21.5, "humidity" => 45.0},
        timestamp: now_ms - 60_000
      },
      %{
        type: "sensor",
        tags: %{"sensor_id" => "s1", "location" => "lab-a"},
        fields: %{"temperature" => 22.0, "humidity" => 44.0},
        timestamp: now_ms
      }
    ],
    precision: :ms
  )

Arcadic.TimeSeries.write_lines/3 is the raw passthrough, useful for relaying an already-built batch (e.g. forwarding a Telegraf line) without going through the point-map builder.

:ok =
  Arcadic.TimeSeries.write_lines(
    conn,
    "sensor,sensor_id=s2,location=lab-b temperature=19.0,humidity=50.0 #{now_ms}",
    precision: :ms
  )

Check existing rows before retrying an unconfirmed write. See Time-series precision and delivery for rules on replay, batch validation, and time units.

Querying

A raw window query returns the server's columnar shape, columns/rows/count, for every point regardless of tag.

{:ok, %{columns: columns, rows: rows, count: count}} =
  Arcadic.TimeSeries.query(conn, "sensor", from: now_ms - 3_600_000, to: now_ms + 3_600_000)

{columns, count}

A point must match every entry in the :tags map.

{:ok, %{count: s1_count}} =
  Arcadic.TimeSeries.query(conn, "sensor",
    from: now_ms - 3_600_000,
    to: now_ms + 3_600_000,
    tags: %{"sensor_id" => "s1", "location" => "lab-a"}
  )

s1_count

Use :aggregation with :bucket_interval to reduce each bucket. This query calculates an hourly average temperature for s1.

{:ok, %{aggregations: aggregations, buckets: buckets}} =
  Arcadic.TimeSeries.query(conn, "sensor",
    from: now_ms - 3_600_000,
    to: now_ms + 3_600_000,
    tags: %{"sensor_id" => "s1"},
    aggregation: [%{field: "temperature", type: :avg}],
    bucket_interval: {1, :hours}
  )

{aggregations, buckets}

Arcadic.TimeSeries.latest/3 returns the single newest point matching one tag filter.

{:ok, %{columns: latest_columns, latest: latest}} =
  Arcadic.TimeSeries.latest(conn, "sensor", tag: {"sensor_id", "s1"})

Enum.zip(latest_columns, latest) |> Map.new()

PromQL

Every TIMESERIES type doubles as a Prometheus metric: the metric name is the type name, and tags are labels, no separate registration step. :time/from/to are epoch-seconds here (PromQL convention), unlike query/3's epoch-milliseconds.

# +1: div/2 floors the second, and a Prometheus instant query excludes a sample AT OR
# AFTER the eval instant -- evaluating one second past the floor is what actually shows
# the millisecond-timestamped sample written above (live-probed on 26.7.2).
now_s = div(now_ms, 1000) + 1

{:ok, %{"resultType" => "vector", "result" => instant_result}} =
  Arcadic.TimeSeries.prom_query(conn, ~S(sensor{sensor_id="s1"}), time: now_s)

instant_result
{:ok, %{"resultType" => "matrix", "result" => range_result}} =
  Arcadic.TimeSeries.prom_query_range(
    conn,
    ~S(sensor{sensor_id="s1"}),
    now_s - 3600,
    now_s + 60,
    60
  )

range_result
{:ok, labels} = Arcadic.TimeSeries.prom_labels(conn)
{:ok, metric_names} = Arcadic.TimeSeries.prom_label_values(conn, "__name__")

# "sensor" -- the TIMESERIES type name, not a name we registered anywhere -- shows up
# among __name__'s values: the metric name IS the type name.
{labels, "sensor" in metric_names}

SQL over time-series

Query sensor in SQL with Arcadic.query/4. The ts.timeBucket function groups the timestamp column. Bind values with :name placeholders.

{:ok, sql_rows} =
  Arcadic.query(
    conn,
    "SELECT ts.timeBucket('1h', ts) AS hour, sensor_id, avg(temperature) AS avg_temp " <>
      "FROM sensor WHERE sensor_id = :sensor_id GROUP BY hour, sensor_id",
    %{"sensor_id" => "s1"},
    language: "sql"
  )

Kino.DataTable.new(sql_rows)

Continuous aggregates & downsampling

Arcadic.TimeSeries.create_aggregate/3 materializes a SELECT as a document type, refreshed on demand; neither it nor drop_aggregate/2 has an IF EXISTS form, so this cell creates, refreshes, reads, and drops within itself, safe to re-run.

:ok =
  Arcadic.TimeSeries.create_aggregate(
    conn,
    "hourly_sensor",
    "SELECT ts.timeBucket('1h', ts) AS hour, sensor_id, avg(temperature) AS avg_temp " <>
      "FROM sensor GROUP BY hour, sensor_id"
  )

:ok = Arcadic.TimeSeries.refresh_aggregate(conn, "hourly_sensor")

{:ok, ca_rows} = Arcadic.query(conn, "SELECT FROM hourly_sensor", %{}, language: "sql")

:ok = Arcadic.TimeSeries.drop_aggregate(conn, "hourly_sensor")

ca_rows

A downsampling policy tells ArcadeDB to compact older points at a coarser granularity; add and drop it here too, in the same cell.

:ok =
  Arcadic.TimeSeries.add_downsampling(conn, "sensor", after: {7, :days}, granularity: {1, :hours})

:ok = Arcadic.TimeSeries.drop_downsampling(conn, "sensor")

Prometheus & Grafana integration

Prometheus and Grafana can query the same database directly. Configure their endpoints on the deployment that reads the metrics.

Point a Prometheus server's remote-write/remote-read at this database's /ts prefix to have it treat ArcadeDB as its storage backend:

remote_write:
  - url: "http://<host>:2480/api/v1/ts/<db>/prom/write"
    basic_auth:
      username: root
      password: <password>
remote_read:
  - url: "http://<host>:2480/api/v1/ts/<db>/prom/read"
    basic_auth:
      username: root
      password: <password>

Point Grafana's built-in Prometheus datasource at the same prefix (its query path) to graph sensor alongside any other Prometheus-compatible source:

apiVersion: 1
datasources:
  - name: ArcadeDB Sensor
    type: prometheus
    url: http://<host>:2480/api/v1/ts/<db>/prom
    basicAuth: true
    basicAuthUser: root
    secureJsonData:
      basicAuthPassword: <password>

ArcadeDB also exposes Grafana Infinity/native endpoints server-side (/grafana/health|metadata|query) for panels that talk to it directly rather than through the Prometheus datasource. Arcadic wraps the app-facing PromQL and query/write surfaces above; wiring either machine-to-machine path into a running Prometheus or Grafana instance is deployment configuration outside the client's scope.

Cleanup

Drop the throwaway database when you are done (or before a fresh top-to-bottom run). This tears down sensor, its data, and any continuous aggregate or downsampling policy left over from a partial run.

Arcadic.Server.drop_database(admin, database)