Amit
Amit

Reputation: 455

Arbitrary path length query in SPARQL

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.

Upvotes: 5

Views: 695

Answers (1)

Joshua Taylor
Joshua Taylor

Reputation: 85913

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.

Upvotes: 9

Related Questions