Documentation
DataFrames in. Knowledge graph. DataFrames out.
fastrdf is written in Rust, built on Apache Arrow via Polars, and uses the Oxigraph libraries for linked data and SPARQL parsing. Wrangle data in Pandas or Polars, map it into a knowledge graph with OTTR templates, then query, validate, reason over and federate the result, all from Python. It stores the graph in memory, hybrid or on disk, and in memory about 100 million triples fit in 16 GB of RAM. Query results come back as Polars DataFrames, transferred zero-copy from Rust to Python.
pizza.pyPython
import polars as pl
pi = "https://github.com/DataTreehouse/fastrdf/pizza#"
df = pl.DataFrame({
"p": [pi + "Hawaiian", pi + "Grandiosa"],
"c": [pi + "CAN", pi + "NOR"],
"ings": [[pi + "Pineapple", pi + "Ham"],
[pi + "Pepper", pi + "Meat"]]
})
Any Polars DataFrame can be the source.
Define a template, map it, query it
An OTTR template describes the shape of the triples once. Expand it over the DataFrame above, insert a derived fact with CONSTRUCT, then query the result, all from the same Model.
pizza.pyPython
from fastrdf import Model, Prefix, Template, Argument, Parameter, Variable, RDFType, Triple, a
pi = Prefix(pi)
p_var, c_var, ings_var = Variable("p"), Variable("c"), Variable("ings")
template = Template(
iri=pi.suf("PizzaTemplate"),
parameters=[
Parameter(variable=p_var, rdf_type=RDFType.IRI),
Parameter(variable=c_var, rdf_type=RDFType.IRI),
Parameter(variable=ings_var, rdf_type=RDFType.Nested(RDFType.IRI)),
],
instances=[
Triple(p_var, a, pi.suf("Pizza")),
Triple(p_var, pi.suf("fromCountry"), c_var),
Triple(p_var, pi.suf("hasIngredient"),
Argument(term=ings_var, list_expand=True), list_expander="cross"),
],
)
m = Model()
m.map(template, df)
# derive a fact, then query it straight back out
m.insert("""
PREFIX pi:<https://github.com/DataTreehouse/fastrdf/pizza#>
CONSTRUCT { ?p a pi:HeterodoxPizza }
WHERE { ?p a pi:Pizza ; pi:hasIngredient pi:Pineapple . }
""")
m.query("""
PREFIX pi:<https://github.com/DataTreehouse/fastrdf/pizza#>
SELECT ?p ?i WHERE { ?p a pi:Pizza ; pi:hasIngredient ?i . }
""") # -> Polars DataFrame, 4 rows
Based on the pizza example of the usage guide and the associated paper.
What's in the guide
- Mapping: get tabular, JSON, XML or relational data into the graph with OTTR templates, Facade-X, R2RML or RML, and read OPC UA NodeSets and industrial sources.
- SPARQL: query and mutate the graph with standard SPARQL.
- Reasoning: derive new facts from existing ones with Datalog rules, OWL and RDFS.
- Validation: check the graph against SHACL shapes.
- Explorer: a local web UI to browse the graph and run SPARQL interactively.
- Virtualisation: one SPARQL query spanning the graph and an external time-series source.
- Reading & writing RDF: Turtle, TriG, N-Triples, N-Quads, RDF/XML, JSON-LD, HDT, Jelly and CIM/XML.
- Disk-based storage: hybrid and disk storage, for graphs too large to keep in memory.
- Claude Code skill: Claude's best buddy when building knowledge graphs.
This page is an introduction. The full documentation, with the usage guide, the API reference, the vocabulary and the change log, is at datatreehouse.github.io/fastrdf.
pip install fastrdf installs the whole library. It is free outside production, for personal use and for accredited educational institutions; other production use needs a commercial licence.
Background & licensing
fastrdf grew out of doctoral research into knowledge graph systems, described in M. Bakken, “maplib: Interactive, Literal RDF Model Mapping for Industry,” IEEE Access, 2023 (DOI 10.1109/ACCESS.2023.3269093), and builds on OTTR templates (Skjæveland et al., WOP 2021). fastrdf is © Data Treehouse AS.
Guide · Mapping
Mapping
Get tabular, JSON or XML data into the graph. An OTTR template describes the shape of the triples once, and mapping applies it to any matching data. Facade-X maps JSON, XML and DataFrames without a template, and R2RML covers relational sources.
OTTR templates
Define a template as Turtle-flavoured OTTR, then map the band catalog through it.
mapping.pyPython
from fastrdf import Model
m = Model()
m.add_template("""
@prefix mu:<http://example.org/music/>.
@prefix xsd:<http://www.w3.org/2001/XMLSchema#>.
mu:Band [ ottr:IRI ?iri, xsd:string ?name, xsd:string ?genre,
xsd:string ?country, xsd:long ?formed ] :: {
ottr:Triple(?iri, a, mu:Band),
ottr:Triple(?iri, mu:name, ?name),
ottr:Triple(?iri, mu:genre, ?genre),
ottr:Triple(?iri, mu:country, ?country),
ottr:Triple(?iri, mu:formed, ?formed)
} .
""")
bands_iri = bands.with_columns(
(pl.lit("http://example.org/music/band/") + pl.col("name").str.replace_all(" ", "_")).alias("iri")
)
m.map("http://example.org/music/Band", bands_iri)
Programmatic templates
The same template, built from Python objects instead of a Turtle string. This is useful when a template is generated rather than hand-written. Triple is the triple pattern of OTTR, and a Prefix makes the IRIs of a namespace.
mapping_prog.pyPython
from fastrdf import Template, Parameter, Variable, Prefix, RDFType, Triple, a, xsd
mu = Prefix("http://example.org/music/")
band, name, genre, country, formed = (
Variable(n) for n in ("iri", "name", "genre", "country", "formed")
)
tmpl = Template(
iri=mu.suf("Band"),
parameters=[
Parameter(band, rdf_type=RDFType.IRI),
Parameter(name, rdf_type=RDFType.Literal(xsd.string)),
Parameter(genre, rdf_type=RDFType.Literal(xsd.string)),
Parameter(country, rdf_type=RDFType.Literal(xsd.string)),
Parameter(formed, rdf_type=RDFType.Literal(xsd.long)),
],
instances=[
Triple(band, a, mu.suf("Band")),
Triple(band, mu.suf("name"), name),
Triple(band, mu.suf("genre"), genre),
Triple(band, mu.suf("country"), country),
Triple(band, mu.suf("formed"), formed),
],
)
m.add_template(tmpl)
m.map("http://example.org/music/Band", bands_iri)
Facade-X: JSON, XML & DataFrames
fastrdf also maps JSON and XML directly, using the Facade-X meta-model, so no template is needed. Both methods can map many documents in one call, and m.map_df does the same for a DataFrame.
json_xml.pyPython
m.map_json("""
{
"name": "Pink Floyd",
"genre": "Prog Rock",
"formed": 1965
}
""")
# m.map_json("bands.json") # …or from a file
m.map_xml("""
<band>
<name>Pink Floyd</name>
<genre>Prog Rock</genre>
<formed>1965</formed>
</band>
""")
# m.map_xml("bands.xml") # …or from a file
If your DataFrame already has a primary-key column, m.map_default(df, "iri") generates a template for you.
Other sources
Each of these maps a source in one call. The usage guide has an example of each.
| Source | Method | What it does |
| Relational databases | m.map_r2rml | Maps tables with a W3C R2RML mapping, through a database connection, DuckDB or DataFrames. |
| CSV, JSON and XML with RML | m.map_rml | Maps files with an RML mapping, with JSONPath and XPath. |
| CSV on the Web | m.map_csvw | Converts CSV and TSV files as the W3C CSVW recommendations specify. |
| OPC UA | m.map_opc_ua | Maps a folder of OPC UA NodeSet2 XML files. m.opcua.add_typing_shapes() then generates SHACL shapes from their type definitions. |
| Microsoft Fabric | m.map_fabric | Converts a Fabric IQ ontology to OWL and maps the lakehouse data behind it. |
| Cognite Data Fusion | m.map_cdf | Maps a data model and virtualises its time series. |
| OSIsoft / AVEVA PI | m.map_osipi, m.map_pi_points | Reads an Asset Framework model or the PI Points of a server and virtualises their values. |
| Siemens Insights Hub | m.map_insights_hub | Reads an asset model and virtualises its time series. |
| AspenTech InfoPlus.21 | fastrdf.ip21.map_ip21 | Adds the tags of a historian and virtualises their values. |
Guide · SPARQL
SPARQL
Query and mutate the graph with standard SPARQL. SELECT returns a Polars DataFrame, so a graph query fits into a data pipeline like any other step.
Query
query.pyPython
df = m.query("""
PREFIX mu:<http://example.org/music/>
SELECT ?name ?genre WHERE {
?b a mu:Band ; mu:name ?name ; mu:genre ?genre .
}
ORDER BY ?name
""")
Update & insert
UPDATE rewrites matching triples; CONSTRUCT through insert enriches the graph in place.
update.pyPython
m.update("""
PREFIX mu:<http://example.org/music/>
DELETE { ?b mu:genre "Prog Rock" }
INSERT { ?b mu:genre "Progressive Rock" }
WHERE { ?b mu:genre "Prog Rock" }
""")
m.insert("""
PREFIX mu:<http://example.org/music/>
CONSTRUCT { ?b a mu:VeteranBand }
WHERE { ?b a mu:Band ; mu:formed ?y . FILTER(?y < 1990) }
""")
Guide · Reasoning
Reasoning
Derive new facts from existing ones with Datalog rules, OWL and RDFS reasoning, or recursive SPARQL CONSTRUCT.
Datalog
reasoning.pyPython
import polars as pl
m.map_triples(pl.DataFrame({
"subject": ["…/band/Rush", "…/band/Mogwai"],
"object": ["…/band/Pink_Floyd", "…/band/Rush"],
}), predicate="http://example.org/music/influencedBy")
m.infer("""
PREFIX mu: <http://example.org/music/>
[?a, mu:influencedBy, ?c] :- [?a, mu:influencedBy, ?b], [?b, mu:influencedBy, ?c] .
""")
Recursive SPARQL CONSTRUCT
recursive.pyPython
m.infer("""
PREFIX mu:<http://example.org/music/>
CONSTRUCT { ?a mu:influencedBy ?c }
WHERE {
?a mu:influencedBy ?b .
?b mu:influencedBy ?c .
}
""")
OWL and RDFS
m.infer(profile="owl-rl") reasons over the OWL axioms in the graph with the OWL 2 RL rules: equality, property axioms such as inverse, transitive and functional properties and property chains, class expressions and class axioms. Inconsistencies are reported as violations. The profiles "rdfs-plus" and "rdfs" are cheaper. The ontology is compiled into Datalog rules, which run to a fixpoint.
Guide · Validation
Validation
Check the graph against SHACL shapes before anything downstream depends on it, for example that every band has a name and a formed year.
validate.pyPython
m.read("shapes.ttl", graph="urn:g:shapes")
report = m.validate(shape_graph="urn:g:shapes")
print(report.conforms) # True or False
print(report.results()) # Polars DataFrame of violations
The SHACL engine is fast enough to run on every load, also on large graphs.
Guide · Explorer
Explorer
A local web UI to browse the graph and run SPARQL interactively. It is useful while you are still developing a mapping or a set of shapes.
explore.pyPython
server = m.explore(port=8000) # runs the Model portal in the background, with full-text search
print(server.url) # open it in a browser
# ... explore ...
server.stop()
Guide · Virtualisation
Virtualisation
Time series usually stay in the database that already holds them. fastrdf virtualises them, so a single SPARQL query spans the graph and the external source.
Connectors: DuckDB, Snowflake, BigQuery, Databricks, TimescaleDB, SQL Server, Microsoft Fabric warehouses, lakehouses and Eventhouses, Azure Data Explorer, InfluxDB, OPC UA History Access, AspenTech IP.21, OSIsoft PI, Siemens Insights Hub and Cognite Data Fusion.
virtualisation.pyPython
m.add_virtualization(
virtualized_database=vdb, # wraps your DuckDB, Snowflake, BigQuery, OPC UA, ...
resources={"streams": streams_template},
)
m.query("""
PREFIX mu:<http://example.org/music/>
PREFIX fastrdf:<https://datatreehouse.github.io/fastrdf/vocab#>
SELECT ?name (AVG(?plays) AS ?avg_monthly_plays)
WHERE {
?b mu:name ?name ; fastrdf:hasTimeseries ?ts .
?ts fastrdf:hasDataPoint ?dp .
?dp fastrdf:hasValue ?plays .
}
GROUP BY ?name
""")
Guide · Reading & writing RDF
Reading & writing RDF
Turtle, TriG, N-Triples, N-Quads, RDF/XML, JSON-LD, HDT, Jelly and CIM/XML. The format is inferred from the file extension unless you pass format=.
rdf_io.pyPython
# Turtle
m.read("catalog.ttl")
m.write("out.ttl", format="turtle")
# N-Triples
m.read("catalog.nt")
s = m.writes(format="ntriples") # returns a string
# RDF/XML
m.read("catalog.rdf")
m.write("out.rdf", format="rdf/xml")
# Jelly, a binary format
m.read("catalog.jelly")
m.write("out.jelly", format="jelly")
# CIM/XML
m.write_cim_xml("model.xml", profile_graph="urn:graph:profiles",
version="22", description="My CIM model")
Performance
How many triples per second each format is written and read at, and the size of a file of 5 million triples, measured on a modern Mac. Select a column heading to sort by it. The fastrdf file is the library's own format, written with m.serialize and read with Model.deserialize.
| Format | Write, million triples/s | Read, million triples/s | File size, MB |
| Jelly | 38 | 11 | 74 |
| fastrdf file | 25 | 114 | 61 |
| N-Triples | 14 | 8.2 | 574 |
| JSON-LD | 12 | 0.7 | 441 |
| RDF/XML | 12 | 4.8 | 456 |
| Turtle | 11 | 1.9 | 345 |
| HDT | 11 | 13 | 32 |
| N-Quads | 4.9 | 8.2 | 574 |
| TriG | 3.2 | 1.8 | 449 |
Synthetic data, five triples per entity: a class, a name, an integer, a link to another entity and a timestamp. Each format is written from the same model in memory and read into an empty model. Best of three runs on a modern Mac (Apple silicon, 15 cores), with a release build of fastrdf from December 2026 (commit aacc0002).
Guide · Disk-based storage
Disk-based storage
For graphs too large to keep in memory, create the model with a storage folder. With storage="hybrid", the default when a folder is given, the dictionaries of IRIs and literals are kept on disk and the triple tables in memory. With storage="disk" the triple tables are also on disk, as Parquet files.
storage.pyPython
from fastrdf import Model
# Hybrid: dictionaries on disk, triple tables in memory
m = Model(storage="hybrid", storage_folder=storage_path)
# Disk: dictionaries and triple tables on disk
m = Model(storage="disk", storage_folder=storage_path)
Guide · Claude Code skill
Claude Code skill
Claude's best buddy when building knowledge graphs for data integration. Work at the speed of thought on large datasets, for instance when analysing energy grid data.
Claude CodeInstall
/plugin marketplace add DataTreehouse/fastrdf
/plugin install fastrdf@fastrdf
More in the documentation.
Guide · Licensing
Licensing
fastrdf is licensed under the Business Source License 1.1. It is not open source. pip install fastrdf installs the whole library; there is no separate edition.
| Use | Licence |
| Outside production, by anyone: evaluation, development, testing and research | Free |
| Personal use in production: an individual's own, non-commercial purposes, not on behalf of anyone else | Free |
| Accredited educational institutions in production: teaching, learning and their own research | Free |
| All other production use, including by companies and government institutions | Commercial licence from Data Treehouse AS |
The licence text governs. See Licensing on the front page, or get in touch about a licence.