Skip to content

SPARQL Query Language

SPARQL (SPARQL Protocol and RDF Query Language) is the W3C standard query language for RDF (Resource Description Framework) data. Grafeo implements SPARQL 1.1 for querying RDF graphs.

Overview

SPARQL uses triple patterns to match RDF data. It's designed for querying semantic web data and knowledge graphs.

Quick Reference

Operation Syntax
Select variables SELECT ?x ?y
Match triples ?s ?p ?o
Filter results FILTER(?x > value)
Optional patterns OPTIONAL { ?s ?p ?o }
Union patterns { ... } UNION { ... }
Aggregate COUNT(?x), SUM(?x)
Order results ORDER BY ?x
Limit results LIMIT 10
Insert triples INSERT DATA { ... }
Delete triples DELETE DATA { ... }
Explain plan EXPLAIN SELECT ...
Validate shapes db.validate_shacl(graph)

RDF Data Model

Unlike property graphs (LPG), RDF uses triples:

Subject --Predicate--> Object

Example triples:

<http://example.org/alix> <http://xmlns.com/foaf/0.1/name> "Alix" .
<http://example.org/alix> <http://xmlns.com/foaf/0.1/knows> <http://example.org/gus> .

Enabling SPARQL

SPARQL requires the sparql feature flag. The default Grafeo features (lpg, gql, parallel) do not include SPARQL.

cargo add grafeo --features sparql

The published grafeo Python package includes SPARQL support by default:

uv add grafeo

The published @grafeo-db/node package includes SPARQL support by default:

npm install @grafeo-db/node

Using SPARQL

import grafeo

db = grafeo.GrafeoDB()

# Insert RDF triples
db.execute_sparql("""
    INSERT DATA {
        <http://example.org/alix> <http://xmlns.com/foaf/0.1/name> "Alix" .
        <http://example.org/alix> <http://xmlns.com/foaf/0.1/knows> <http://example.org/gus> .
    }
""")

# Query triples
result = db.execute_sparql("""
    SELECT ?name WHERE {
        <http://example.org/alix> <http://xmlns.com/foaf/0.1/name> ?name .
    }
""")
for row in result:
    print(row)
use grafeo::GrafeoDB;

let db = GrafeoDB::new_in_memory();
let mut session = db.session();

session.execute_sparql(r#"
    SELECT ?s ?p ?o WHERE { ?s ?p ?o }
"#)?;

Learn More