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:
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.
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)
Learn More¶
-
SELECT, WHERE and basic triple patterns.
-
Matching subjects, predicates and objects.
-
FILTER expressions and conditions.
-
COUNT, SUM, AVG, GROUP BY and HAVING.
-
Path expressions for traversing relationships.
-
String, numeric and date/time functions.
-
Turtle, N-Triples, N-Quads import and streaming load.
-
INSERT DATA, DELETE DATA, pattern-based updates, and named graph operations.
-
Inspect query execution plans and profile operator performance.
-
Validate RDF data against SHACL shapes with SHACL Core constraint types.