fastrdf

Build, query, reason over and validate RDF knowledge graphs at DataFrame speed, from Python.

PyPI Python versions License: BUSL 1.1 Documentation

fastrdf is a knowledge graph engine that runs inside your Python process. It turns DataFrames, CSV, JSON, XML and RDF files into a knowledge graph, which you can query with SPARQL and GeoSPARQL, enrich with Datalog rules and reasoning, validate with SHACL and write out in any standard RDF format. You don’t need a server or a database: pip install fastrdf, create a Model, and query results come back as Polars DataFrames.

fastrdf is written in Rust and stores triples column-wise in Apache Arrow via Polars. Mapping and querying therefore run as vectorised, multi-threaded table operations, not one triple at a time.

Installation

pip install fastrdf

fastrdf is the continuation of maplib. If you come from maplib, see Migrating from maplib to fastrdf.

Prebuilt wheels are available for Linux, macOS and Windows (Python 3.12+).

Quickstart

Load a plant model, reason over it, validate it, and query it together with sensor data that stays in a database:

import duckdb
from fastrdf import Model, VirtualizedDatabase
from fastrdf.virtualization import DuckDBDatabase

m = Model()

# Load: any RDF format, from a path, a URL or s3:// / gs:// / az://
m.read("ontology.ttl")                     # ex:CentrifugalPump rdfs:subClassOf ex:Pump
m.read("plant.ttl")                        # ex:pump1 a ex:CentrifugalPump ; fastrdf:hasTimeseries ex:ts1 ...
m.read("shapes.ttl", graph="urn:shapes")   # SHACL: every ex:Pump needs an ex:ratedPower

# Infer: RDFS reasoning makes every centrifugal pump an ex:Pump
m.infer_rdfs()

# Validate with SHACL
report = m.validate(shape_graph="urn:shapes")
print(report.conforms, report.results())   # the violations, as a DataFrame

# Virtualize: readings stay in DuckDB and are fetched only when a query needs them
m.add_template("""@prefix fastrdf: <https://datatreehouse.github.io/fastrdf/vocab#> .
@prefix ex: <http://example.org/> .
ex:Speed [ xsd:string ?id, xsd:dateTime ?timestamp, xsd:double ?value ] :: {
  ottr:Triple(?id, fastrdf:hasDataPoint, ?dp) , ottr:Triple(?dp, fastrdf:hasTimestamp, ?timestamp) ,
  ottr:Triple(?dp, fastrdf:hasValue, ?value) } .""")
db = DuckDBDatabase(duckdb.connect("plant.duckdb"))
m.add_virtualization(VirtualizedDatabase(db, resource_sql_map={"speed": "SELECT id, timestamp, value FROM speed"}),
                     resources={"speed": m.get_templates()[0]})

# Query the graph, the inferred types and the time series in one SPARQL query; returns a Polars DataFrame
print(m.query("""
PREFIX ex: <http://example.org/>
PREFIX fastrdf: <https://datatreehouse.github.io/fastrdf/vocab#>
SELECT ?pump (AVG(?speed) AS ?avg_speed) WHERE {
    ?pump a ex:Pump ; fastrdf:hasTimeseries ?ts .                # ex:Pump comes from inference
    ?ts fastrdf:hasDataPoint ?dp . ?dp fastrdf:hasValue ?speed .      # the data points come from DuckDB
} GROUP BY ?pump"""))

To build a graph from DataFrames instead, use templates with m.map(...) (see Build the graph and API_USAGE.md).

Core concepts

  • Model is the knowledge graph. It holds the triples (in a default graph and any number of named graphs), the templates and the prefixes, and every operation is a method on it.

  • Templates are reusable patterns of triples, written in OTTR (as text, or built in Python with Template, Parameter, Triple and friends). Mapping a template with a DataFrame fills each parameter from the column of the same name, for all rows at once.

  • DataFrames in, DataFrames out. IRIs appear as "<...>" strings and literals as native Polars types.

  • Named graphs keep data, ontologies, shapes and inferences apart. Triples in the reserved graph fastrdf.TRANSIENT_GRAPH take part in queries, reasoning and validation, but are not written out unless you ask for them.

What you can do

For worked examples of every method, see API_USAGE.md. Each method’s docstring documents its parameters (help(Model.map)), and the documentation site has the guides and the API reference together, with search.

Build the graph

Method

What it does

m.map(template, data)

Instantiates an OTTR template once per row of a DataFrame, LazyFrame or iterable of batches, so data larger than memory can be mapped. With stream=True it returns a lazy ModelStream instead (see below).

m.map_triples(data, predicate=None)

Adds triples straight from a DataFrame with subject and object columns (and optionally predicate).

m.map_default(data, primary_key_column)

Generates a default template from the columns, with the key column as the subject of one triple per other column, adds it to the model and maps the data with it.

m.map_df(df) / m.map_json(...) / m.map_xml(...)

Maps a DataFrame, JSON or XML document to triples with a generic Façade-X mapping that mirrors its structure. JSON and XML also accept an iterable of documents, such as the lines of a JSON Lines file.

m.map_csvw(source, metadata=None)

Converts CSV and TSV files to RDF as specified by the W3C CSV on the Web recommendations, and returns the generated SPARQL Update so you can adapt it.

m.map_r2rml(mapping, database=db)

Maps relational data to RDF with a W3C R2RML mapping, given as Turtle or stored in a graph of the model (mapping_graph). The tables are queried through a Python database object, a DuckDB connection or given as DataFrames.

m.map_rml(mapping, sources=...)

Maps CSV, JSON and XML sources to RDF with an RML mapping. JSONPath and XPath iterators and references are evaluated as SPARQL over a temporary Façade-X graph of the source.

m.map_opc_ua(folder)

Maps a folder of OPC UA NodeSet2 XML files to RDF. m.opcua.add_typing_shapes() then generates SHACL shapes from their type definitions.

m.add_template(t), m.read_template(path)

Add templates from stOTTR text, a Template object or a file.

Function calls in templates

Template arguments computed with SPARQL functions, e.g. ottr:Triple((IRI (CONCAT "http://ex.org/" ?id)), ex:powerW, (* ?kw 1000)), and functions defined with def (API_USAGE.md).

m.get_templates(), m.templates_to_graph(graph)

List the model’s templates, or write them as RDF so you can query their structure with SPARQL.

fastrdf.generate_templates(m, graph)

Generates one template per class of an ontology from its rdfs:subClassOf, rdfs:domain and rdfs:range.

m.add_prefixes({...})

Registers prefixes for use in SPARQL, Datalog and OTTR.

Streaming. m.map(..., stream=True) (also map_triples, map_default, map_json and map_xml) returns a ModelStream: a lazy pipeline of .update(), .insert(), .infer() and .write() steps. .collect() then runs the pipeline batch by batch in a fresh model, so arbitrarily large inputs go to file with bounded memory.

Read and write RDF

Method

What it does

m.read(source, format=None, graph=None)

Reads Turtle, N-Triples, N-Quads, TriG, RDF/XML, JSON-LD, HDT, Jelly or CIM/XML from a path, an object storage URL, bytes or a file-like object. N-Triples, N-Quads, RDF/XML and CIM/XML are parsed in parallel by default, Turtle with parallel=True.

m.reads(string, format)

Reads triples from a string.

m.write(target, format, graph=None)

Writes Turtle (pretty-printed), N-Triples, N-Quads, TriG, RDF/XML, JSON-LD, HDT or Jelly to a path, an object storage URL or a binary file-like object. For dataset formats, graph can be a list of graphs.

m.writes(format), m.write_bytes(format)

Write to a string, or to bytes (any format, including HDT).

m.write_cim_xml(path, profile_graph)

Writes IEC 61970-552 / CGMES-compliant CIM/XML, driven by the profile ontologies.

m.cim

The CIM grid tools bound to the model: cutting out part of a grid (m.cim.cut_to_graph), serves relations, and time series of measurements and meter readings, and events such as earth faults and meter events, virtualized from a database.

m.serialize(path), Model.deserialize(path)

Save and restore a whole model in fastrdf’s own Parquet-based format, by default as one .fastrdf file, which is much faster to reload than RDF text. raw_db=True keeps DuckDB dictionaries for fast disk-mode loads.

Object storage. read, read_template, write, write_cim_xml, serialize and deserialize also take s3://, gs://, az:///abfss://, https:// and file:// URLs, with credentials from the environment or storage_options.

Query and update with SPARQL

Method

What it does

m.query(sparql)

Runs SPARQL 1.1 SELECT (returns a DataFrame), CONSTRUCT and DESCRIBE (a list of DataFrames of triples) or ASK (a bool). Options include bindings= for parameterised queries, return_format="json" or "turtle", graph= and include_graphs=, and endpoint= to send the query to a remote SPARQL endpoint.

m.insert(construct)

Runs a CONSTRUCT and adds the resulting triples, returning only the new ones. Use query first to inspect the triples, then insert the same string to commit them.

m.update(sparql_update)

Runs SPARQL 1.1 Update (INSERT/DELETE … WHERE, CLEAR, DROP, LOAD, …).

m.query_external(sparql, endpoint)

Queries another SPARQL endpoint and returns a DataFrame.

m.set_federation(allowed_endpoints=[...])

Enables SPARQL 1.1 Federated Query (SERVICE) and LOAD for the listed endpoints, using bind joins so remote endpoints only return matching rows.

m.add_udf(iri, func, output_type), m.list_udfs()

Register a Polars function that SPARQL can call, and list the registered ones.

m.set_query_cache(...), get_query_cache(), query_cache_stats(), clear_query_cache()

Cache query results, invalidating each one only when a write touches the graphs and predicates the query reads.

Beyond standard SPARQL 1.1, fastrdf supports:

  • length-constrained paths (ex:p{2,4});

  • the magic predicates fastrdf:path (hop counts and path enumeration), fastrdf:shortestPath (shortest routes with costs and nodes to avoid), and fastrdf:component, fastrdf:bridge and fastrdf:articulationPoint (islands, single points of failure and what-ifs, over stored or derived edges);

  • arithmetic on durations, dates and times;

  • full-text search with fastrdf:fts;

  • GeoSPARQL. Enable it with IndexingOptions(geo=True); m.read(..., format="cim/xml", geo=True) also turns CIM position points into geometries. WKT, WKB and GeoJSON geometry literals are then indexed spatially, and the GeoSPARQL functions work across coordinate reference systems: simple features, Egenhofer and RCC8 relations, distances and areas with units of measure, and constructions such as buffers and intersections. Spatial filters and spatial joins use the index.

Ctrl-C stops a running query, and syntax errors show the offending source with a hint.

Reason and validate

Method

What it does

m.infer_rdfs()

Applies RDFS entailment (subclass, subproperty, domain and range) and puts the inferred triples in the transient graph.

m.infer(rules)

Runs Datalog rules to a fixpoint.

m.infer(profile=...)

Materializes a built-in reasoning profile with the Datalog engine: "owl-rl" (OWL 2 RL), "rdfs-plus" or "rdfs" (all RDFS entailment rules). Puts the inferred triples in the transient graph and returns a ReasoningResult with the count and the consistency violations.

m.validate(shape_graph=...)

Validates the graph with SHACL Core and SHACL-SPARQL, evaluating shapes in parallel, and runs SHACL rules (sh:rule). Returns a ValidationReport with .conforms, .results() and .details() as DataFrames, and can also write the report as RDF.

Virtualize time series

Leave large time series in the databases that hold them, and query them in SPARQL together with the graph.

Method

What it does

m.add_virtualization(db, resources)

Adds a virtualized database, with a template per resource. You can add several databases and query them together. Filters, grouping and ordering are pushed down to the database.

fastrdf.virtualization.*

Connectors for DuckDB, Snowflake, BigQuery, Databricks, TimescaleDB, InfluxDB 1.8/2/3, Microsoft Fabric (Lakehouse and Warehouse), Azure Data Explorer / Kusto, plus fastrdf.opcua.OPCUAHistoryDatabase for OPC UA Historical Access.

m.map_cdf(client)

Maps a Cognite Data Fusion data model to RDF and virtualizes its time series.

m.map_osipi(url, ...), m.map_pi_points(url, ...)

Read an OSIsoft/AVEVA PI Asset Framework model or the PI Points of a PI Data Archive, and virtualize their recorded values.

m.map_insights_hub(host, tenant, ...)

Reads a Siemens Insights Hub asset model and virtualizes its time series.

fastrdf.ip21.map_ip21(m, url, data_source)

Adds the tags of an AspenTech InfoPlus.21 historian and virtualizes their values.

fastrdf.config

Stores a model’s virtualizations, indexes, query cache settings and saved questions as triples in its own config graph, and applies them with apply_config(m). Secrets are read from environment variables.

Serve and explore

Method

What it does

m.serve(port=...)

Serves the live model over the SPARQL 1.1 Protocol and Arrow Flight in the background. Includes optional updates, auth, CORS, a query log and static web apps, and returns a Server.

m.explore()

Opens the Model portal, a browser UI for browsing, searching and querying the model, and returns an ExploreServer with .url.

Manage the model

Method

What it does

Model(storage=..., storage_folder=...)

Chooses "memory" (the default) or, with, "hybrid" (dictionaries on disk) or "disk" (triple tables on disk as Parquet too) for graphs larger than RAM.

m.size(graph)

Count the triples of a graph.

m.add_graph(other, ...), fastrdf.add_triples(...)

Copy a graph from another model into this one.

m.detach_graph(graph), m.truncate_graph(graph)

Split a named graph off into its own model, or empty it.

m.isomorphic(other, ...), m.blank_node_mapping(other, ...)

Tell whether two graphs or datasets are the same up to blank node labels, and get the renaming of blank nodes that shows it.

m.create_index(IndexingOptions(...)), m.compact()

Build object, full-text and geo indexes, and merge stored segments.

fastrdf.set_memory_limit(...), memory_usage(), memory_limit()

Bound the memory queries may use (80% of system memory by default). Over the limit, joins, sorts and aggregations spill to disk.

A Model can be shared between threads: queries and writes to file run concurrently, while changes take an exclusive lock.

Claude Code skill

The repository DataTreehouse/fastrdf is also a Claude Code plugin with one skill, using-fastrdf. With it, Claude uses fastrdf where it would otherwise use rdflib, pyshacl, owlrl or SPARQLWrapper, and knows the fastrdf API: templates and map for DataFrames, SPARQL with DataFrame results, reasoning, SHACL validation, and how to translate rdflib code.

Install it in Claude Code:

/plugin marketplace add DataTreehouse/fastrdf
/plugin install fastrdf@fastrdf

Or copy the folder skills/using-fastrdf of that repository to ~/.claude/skills/ (for all your projects) or to .claude/skills/ in a project.

See Claude Code skill for what it covers.

License

fastrdf is licensed under the Business Source License 1.1 (BUSL-1.1); see LICENSE. It is not open source. pip install fastrdf installs the whole library; there is no separate edition.

  • Anyone may use fastrdf for free outside production: evaluation, development, testing and research.

  • Individuals may also use it for free in production for personal use: for their own, non-commercial purposes, and not on behalf of anyone else.

  • Accredited educational institutions may also use it for free in production, for teaching, learning and their own research.

  • All other production use, including by companies and government institutions, requires a commercial license from Data Treehouse AS: info@data-treehouse.com.

  • Each version becomes available under the Apache License 2.0 four years after it is published.

Learn more

To cite fastrdf: M. Bakken, “maplib: Interactive, Literal RDF Model Mapping for Industry,” IEEE Access, vol. 11, 2023, doi: 10.1109/ACCESS.2023.3269093.