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 |
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> .
Using SPARQL¶
SPARQL is enabled by default in Grafeo:
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.