Michele
Michele

Reputation: 3

Length of path between nodes, allowing for multiple relation types (SPARQL)

I have to write a SPARQL query that returns the length of the path between two nodes (:persA and :persD) that are connected by these relationships:

@prefix : <http://www.example.org/> .

:persA :knows :knowRelation1 .
:knowRelation1 :hasPerson :persB .
:persB :knows :knowRelation2 .
:knowRelation2 :hasPerson :persC .
:persC :knows :knowRelation3 .
:knowRelation3 :hasPerson :persD .

I tried with this query:

PREFIX : <http://www.example.org/>

SELECT (COUNT(?mid) AS ?length)
WHERE 
{
    :persA (:knows | :hasPerson)* ?mid .
    ?mid (:knows | :hasPerson)+ :persD .
}

the result seems to be a infinite loop.

Any advice/examples of how this can be done?

Upvotes: 0

Views: 334

Answers (1)

Mark Miller
Mark Miller

Reputation: 3096

After fixing some syntax errors in your initial post, the provided triples and query work for me in GraphDB Free 8.2 and BlazeGraph 2.1.1. I have since applied these edits to your post itself.

  • added a trailing / to your definition of the empty prefix
  • added a trailing . to your prefix definition line (required if you want to start with a @)
  • fixed the spelling of length (OK, that's just a cosmetic fix)

.

@prefix : <http://www.example.org/> .

:persA :knows :knowRelation1 .
:knowRelation1 :hasPerson :persB .
:persB :knows :knowRelation2 .
:knowRelation2 :hasPerson :persC .
:persC :knows :knowRelation3 .
:knowRelation3 :hasPerson :persD .

.

PREFIX  :     <http://www.example.org/>

SELECT  (COUNT(?mid) AS ?length)
WHERE
  { :persA (:knows|:hasPerson)* ?mid .
    ?mid (:knows|:hasPerson)+ :persD
  }

result:

    length
"6"^^xsd:integer

enter image description here

Upvotes: 1

Related Questions