Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arbitrary path length query in SPARQL

Tags:

rdf

neo4j

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.

like image 747
Amit Avatar asked Mar 05 '14 22:03

Amit


People also ask

What types of queries does SPARQL support?

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.

What is FOAF in SPARQL?

Dataset: Friend of a Friend (FOAF) @prefix card: <http://www.w3.org/People/Berners-Lee/card#> . @prefix foaf: <http://xmlns.com/foaf/0.1/> .

What is the result type of an SPARQL ask query?

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.

What is optional SPARQL?

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).


1 Answers

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.

like image 127
Joshua Taylor Avatar answered Sep 21 '22 09:09

Joshua Taylor