BGP joins
A basic graph pattern (BGP) is a group of triple patterns that must all match. When patterns share a variable, pgRDF joins them on it, and PostgreSQL's planner chooses the join order and indexes.
Examples use the sample data.
Example
People who have both a name and a mailbox:
sql
SELECT * FROM pgrdf.sparql($$
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
SELECT ?p ?name ?mbox
WHERE { ?p foaf:name ?name .
?p foaf:mbox ?mbox }
ORDER BY ?name
$$);
-- {"p": "http://example.org/alice", "mbox": "mailto:alice@example.org", "name": "Alice"}
-- {"p": "http://example.org/carol", "mbox": "mailto:carol@example.org", "name": "Carol"}?p appears in both patterns, so only subjects that have both properties are returned. Bob has a name but no mailbox, so he is left out; use OPTIONAL to keep him.
Shorthand
Turtle-style abbreviations work in WHERE:
| Write | Means |
|---|---|
?p foaf:name ?name ; ex:age ?age | ; repeats the subject |
?p foaf:knows ex:bob , ex:carol | , repeats the subject and predicate |
?p a foaf:Person | a is rdf:type |
sql
SELECT * FROM pgrdf.sparql($$
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX ex: <http://example.org/>
SELECT ?p WHERE { ?p foaf:knows ex:bob , ex:carol }
$$);
-- {"p": "http://example.org/alice"}Things to know
- A pattern without a
GRAPHclause matches across all graphs, including the default graph. To look in one graph, useGRAPH <iri> { … }. - Use variables, not blank nodes:
_:xor[]in a query pattern is refused with an error. - A path such as
?s foaf:knows/foaf:name ?nis not supported; write it as two patterns joined on a variable:?s foaf:knows ?friend . ?friend foaf:name ?n.