Is it possible to do arbitrary length of path queries in SPARQL. Lets say i have neo4j store which has a graph that only represents PARENT_OF relationships (consider a family tree for example). A cypher query to get all ancestors of a person would look like
start n (some node from index query) match n<-[:PARENT_OF*]-k return k
How would this query look like in SPARQL if this neo store were to be represented as a RDF based triple store. Is this even possible.
SPARQL contains capabilities for querying required and optional graph patterns along with their conjunctions and disjunctions. SPARQL also supports aggregation, subqueries, negation, creating values by expressions, extensible value testing, and constraining queries by source RDF graph.
Dataset: Friend of a Friend (FOAF) @prefix card: <http://www.w3.org/People/Berners-Lee/card#> . @prefix foaf: <http://xmlns.com/foaf/0.1/> .
SPARQL also supports extensible value testing and constraining queries by source RDF graph. The results of SPARQL queries can be results sets or RDF graphs.
OPTIONAL is a binary operator that combines two graph patterns. The optional pattern is any group pattern and may involve any SPARQL pattern types. If the group matches, the solution is extended, if not, the original solution is given (q-opt3. rq).
If you have data like this:
@prefix : <http://stackoverflow.com/q/22210295/1281433/> .
:a :parentOf :b .
:b :parentOf :c .
:c :parentOf :d .
then you can use a query like this, using SPARQL 1.1's property paths:
prefix : <http://stackoverflow.com/q/22210295/1281433/>
select ?ancestor ?descendent where {
?ancestor :parentOf+ ?descendent
}
to get results like this:
-------------------------
| ancestor | descendent |
=========================
| :a | :b |
| :a | :c |
| :a | :d |
| :b | :c |
| :b | :d |
| :c | :d |
-------------------------
Note that using *
permits zero occurrences of the relation, and relates each node to itself. If you want each thing to be an ancestor of itself, then you could replace +
with *
in my query.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With