Storing query results in a catalog table

This example summarizes a dataset with a query and stores the result in a catalog table. It then reads the table back in a later session, joins it with the dataset, and updates it.

The dependencies in this example are contained in rerun-sdk[all].

Connect to a dataset

This example starts a local server with a sample dataset. In practice, connect a CatalogClient to your Rerun DB instance or another Rerun DB server.

from __future__ import annotations

import tempfile
from pathlib import Path

import pyarrow as pa
from datafusion import col
from datafusion import functions as F

import rerun as rr

sample_5_path = (
    Path(__file__).parents[4] / "tests" / "assets" / "rrd" / "sample_5"
)

temp_dir = tempfile.TemporaryDirectory()
storage_dir = Path(temp_dir.name)
server = rr.server.Server(
    temporary=True, datasets={"sample_dataset": sample_5_path}
)
CATALOG_URL = server.url()
client = rr.catalog.CatalogClient(CATALOG_URL)
# On Rerun DB, connect to your deployment instead:
# client = rr.catalog.CatalogClient("rerun://api.<stack>.cloud.rerun.io")
dataset = client.get_dataset(name="sample_dataset")

Query the dataset

Build a DataFusion query that produces one summary row per dataset segment. The query remains lazy until its result is written or collected.

observations = dataset.filter_contents([
    "/observation/joint_positions",
]).reader(index="real_time")

result = observations.aggregate(
    col("rerun_segment_id"),
    [
        F.min(col("real_time")).alias("first_observation"),
        F.max(col("real_time")).alias("last_observation"),
    ],
)

Store the result

create_table creates an empty table from the query result's Arrow schema and returns its TableEntry. DataFrame.write_table then executes the lazy query and appends its rows to that table without first collecting the result into Python.

Catalog tables do not need an index for ordinary writes. This example marks rerun_segment_id as the table index only to support the upsert demonstrated later.

# A table index is optional and only needed for upserts. This query has one row
# per segment, so here we use the segment ID as each row's identity.
schema = pa.schema([
    field.with_metadata({rr.SORBET_IS_TABLE_INDEX: "true"})
    if field.name == "rerun_segment_id"
    else field
    for field in result.schema()
])

# A local server can optionally store the table in a specific directory.
# Omit the url argument when using Rerun DB.
local_table_storage_url = (storage_dir / "catalog_storage").as_uri()

summary = client.create_table(
    "observation_summary",
    schema,
    url=local_table_storage_url,
)
result.write_table("observation_summary")

The example passes url to choose where the local server stores the table. See Create a table for where a table goes without it, and on Rerun DB.

Access the table later

create_table returns a TableEntry that you can use immediately. In a later session, reconnect to the catalog and retrieve the table by name with get_table. Call reader() on the table entry to get a DataFusion dataframe that you can filter, aggregate, or join.

later_client = rr.catalog.CatalogClient(CATALOG_URL)
summary = later_client.get_table(name="observation_summary")
stored_result = summary.reader().sort(col("rerun_segment_id"))
stored_result.show()

Join with a dataset

Pass a table as join_meta to DatasetEntry.segment_table to get a dataframe of the segment table joined with the table's columns. The table must contain a rerun_segment_id column. Segments without a matching row get null values. The join is lazy and reads the table's current rows when the result is collected. It does not modify the dataset.

segments = (
    dataset
    .segment_table(join_meta=summary)
    .select("rerun_segment_id", "first_observation", "last_observation")
    .sort(col("rerun_segment_id"))
)
segments.show()

To query only the segments that match a condition on the table, pass a filtered reader() dataframe of the table to DatasetEntry.filter_segments.

Update the table

Calling collect() materializes a DataFusion query as Arrow record batches in the Python process. You can then use the table index to update existing segment summaries and append new ones:

batches = result.collect()

# Replace matching segments and append new ones.
summary.upsert(batches)

This query produces one row per segment, so the example uses rerun_segment_id as the table index, but other tables can use a different field. See Update a table for the other mutation operations and what an upsert requires.

Remove the table

Call delete() on the TableEntry to remove the table from the catalog:

summary.delete()