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 runs in memory and holds around 100 million triples on 32 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 (or Pandas) DataFrame can be the source. This is the worked example from the project README.
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-ontology example used throughout the project's documentation and associated paper.
What's in the guide
- Mapping: get tabular, JSON, XML or relational data into the graph with OTTR templates, Facade-X or R2RML.
- SPARQL: query and mutate the graph with standard SPARQL.
- Reasoning: derive new facts from existing ones.
- 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 and CIM/XML.
- Disk-based storage: for graphs too large to keep in memory.
pip install fastrdf installs the full library. Enterprises need a licence to run it in production. Academic, educational and personal use is always free.
Roadmap
In progress and subject to change: support for Jelly, a binary RDF serialization.
Background & licensing
fastrdf grew out of doctoral research into knowledge graph systems, described in M. Bakken, “fastrdf: Interactive, Literal RDF Model Development for Industry,” IEEE Access, 2023 (DOI 10.1109/ACCESS.2023.3269093), and builds on OTTR templates (Skjæveland et al., WOP 2021). Code written since 1 August 2023 is © Data Treehouse AS under Apache 2.0; earlier code is © Prediktor AS under Apache 2.0, from PhD work financed by the Research Council of Norway (grant 316656) and Prediktor 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.
mapping_prog.pyPython
from fastrdf import Template, Parameter, Instance, Variable, IRI, RDFType, xsd
mu = "http://example.org/music/"
band = Variable("iri")
name = Variable("name")
formed = Variable("formed")
tmpl = Template(
iri=IRI(mu + "Band"),
parameters=[
Parameter(band, rdf_type=RDFType.IRI),
Parameter(name, rdf_type=RDFType.Literal(xsd.string)),
Parameter(formed, rdf_type=RDFType.Literal(xsd.long)),
],
instances=[
Instance(IRI("http://ns.ottr.xyz/0.4/Triple"), [band, IRI(mu + "name"), name]),
Instance(IRI("http://ns.ottr.xyz/0.4/Triple"), [band, IRI(mu + "formed"), formed]),
],
)
m.add_template(tmpl)
m.map(mu + "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.
R2RML & Microsoft Fabric
m.map_r2rml maps relational data with W3C R2RML mappings, from a DuckDB connection or Polars DataFrames. m.map_fabric converts a Microsoft Fabric IQ ontology to OWL and maps the lakehouse data behind it.
Guide · SPARQL
SPARQL
Query and mutate the graph with standard SPARQL. SELECT always 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, the OWL 2 RL, RDFS-Plus and RDFS profiles, 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/>.
mu:influencedBy(?a, ?c) :- mu:influencedBy(?a, ?b), mu:influencedBy(?b, ?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 .
}
""")
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) # bool
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) # opens a browser UI; add fts=True for full-text search
# ... 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 ct:<https://github.com/DataTreehouse/chrontext#>
SELECT ?name (AVG(?plays) AS ?avg_monthly_plays)
WHERE {
?b mu:name ?name ; ct:hasTimeseries ?ts .
?ts ct:hasDataPoint ?dp .
?dp ct:hasValue ?plays .
}
GROUP BY ?name
""")
Guide · Reading & writing RDF
Reading & writing RDF
Turtle, TriG, N-Triples, N-Quads, RDF/XML, JSON-LD, HDT 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")
# CIM/XML
m.write_cim_xml("model.xml", profile_graph="urn:graph:profiles",
version="22", description="My CIM model")
Guide · Disk-based storage
Disk-based storage
For graphs too large to keep in memory, point the model at a storage folder when you create it. fastrdf then keeps the graph on disk in its native, Parquet-based format instead of in RAM.
storage.pyPython
from fastrdf import Model
m = Model(storage_folder=storage_path)
Guide · Licensing
Licensing
The whole library is open, and pip install fastrdf gives everyone full access to every feature. Enterprises need a licence to run fastrdf in production. Academic, educational and personal use is always free.
| Use | Licence |
| Academic and educational use | Free |
| Personal use | Free |
| Enterprise use in production | Commercial licence |
See Licensing on the front page, or get in touch about a licence.
Reference · fastrdf API
fastrdf API
The core session object is Model. It covers mapping with OTTR templates, SPARQL queries and SHACL validation.
Modelconstructor
Model(indexing_options: IndexingOptions = None, storage_folder: Union[Path, str] = None)
Template management
| Method | Description |
add_template(template) | Incorporates a template into the model, replacing any existing one with the same identifier. |
get_templates() → List[Template] | Retrieves all currently held OTTR templates. |
templates_to_graph(graph=None) | Materialises templates into RDF using the fastrdf vocabulary. |
read_template(file_path) | Loads templates from a file. |
add_prefixes(prefixes) | Registers prefixes for SPARQL, Datalog and OTTR parsing. |
Mapping
| Method | Description |
map(template, data=None, graph=None, validate_iris=True) | Maps a template using a DataFrame. |
map_json(path_or_string, graph=None, transient=True) | Converts JSON to triples using Facade-X. |
map_xml(path_or_string, graph=None, transient=True) | Converts XML to triples using Facade-X. |
map_triples(data=None, predicate=None, graph=None, validate_iris=True) | Maps subject, predicate, object triples. |
map_default(data, primary_key_column, dry_run=False, ...) → str | Generates and applies a default template. |
map_df(df, graph=None) | Creates a default template using Facade-X mapping. |
map_opc_ua(folder, graph=None) | Maps OPC UA NodeSet2 XMLs to RDF. |
Query & exploration
| Method | Description |
query(query, parameters=None, graph=None, streaming=False, ...) | Executes SPARQL SELECT / CONSTRUCT queries. |
query_external(query, endpoint, ...) | Queries external SPARQL endpoints. |
explore(host="localhost", port=8000, fts=True, ...) → ExploreServer | Launches the interactive graph explorer. |
Data modification
| Method | Description |
update(update, parameters=None, graph=None, ...) | Inserts CONSTRUCT query results into the graph. |
insert(query, transient=False, source_graph=None, target_graph=None, ...) | Inserts CONSTRUCT results with transience control. |
I/O & serialization
| Method | Description |
read(file_path, format=None, ...) | Reads triples from a file: Turtle, TriG, N-Triples, N-Quads, RDF/XML, JSON-LD, HDT or CIM/XML. |
reads(s, format, ...) | Reads triples from a string. |
write(file_path, format, graph=None, prefixes=None) | Writes triples to a file. |
writes(format, graph=None, prefixes=None) → str | Writes triples to a string. |
write_cim_xml(file_path, profile_graph, ...) | Exports the legacy CIM XML format. |
serialize(path) | Exports named graphs to a folder. |
deserialize(path, storage_folder=None) → Model | Reconstructs serialized graphs. |
Validation & inference
| Method | Description |
validate(shape_graph=None, data_graph=None, include_details=False, ...) → ValidationReport | Validates the graph using SHACL shapes. |
infer(ruleset, graph=None, max_iterations=100000, ...) | Executes Datalog rules. |
infer_rdfs(graph=None) → int | Applies RDFS inference (rules 2, 3, 5, 6, 8, 9, 10, 11). |
Graph management
| Method | Description |
truncate_graph(graph=None) | Removes all triples from a graph. |
detach_graph(graph=None, preserve_name=False) → Model | Detaches a named graph as a separate Model. |
size(graph=None) → int | Returns the triple count. |
create_index(options=None, all=True, graph=None) | Creates indexes for performance. |
add_udf(iri, func, output_type, input_types=None) | Registers a custom function for use in queries. |
add_virtualization(virtualized_database, resources) | Integrates virtual (federated) database access. |
Supporting classes
Template(iri, parameters, instances) · Parameter(variable, optional=False, allow_blank=True, rdf_type=None, default_value=None) · Argument(term, list_expand=False) · IndexingOptions(object_sort_all=None, object_sort_some=None, fts=None, fts_path=None)
Reference · Vocabulary
Vocabulary
The terms fastrdf itself defines, at https://datatreehouse.github.io/fastrdf/vocab#. The namespace is dereferenceable, with an anchor for each IRI fragment and a machine-readable vocab.ttl file.
Functions
| Term | Signature | Description |
fastrdf:uuidv5 | (xsd:string, xsd:string) → IRI | Generates a deterministic UUID-based IRI from a namespace and a name. Usable in BIND / FILTER. |
fastrdf:struuidv5 | (xsd:string, xsd:string) → xsd:string | As uuidv5, but returns the scheme-specific part of the UUID as a plain string. |
Templates
| Term | Description |
fastrdf:ShaclReportTemplate | Serializes a complete SHACL validation report into RDF when fastrdf materializes results. |
fastrdf:ShaclResultTemplate | Serializes an individual SHACL validation violation into RDF, alongside the report template. |
A namespace migration is underway, from https://github.com/DataTreehouse/fastrdf# to https://datatreehouse.github.io/fastrdf/vocab#.