Search code examples
sparqlontologyturtle-rdf

SPARQL property path - Retrieve the closest node only


Suppose we have an ontology recording log events, with 2 distinct types of events: info and warning. Each entry is linked to the previous one via the non-transitive property hasPreviousEvent as shown below:

enter image description here

For all the info nodes I would like to retrieve the closest error node, no matter how many hops back it resides. Ideally, for the above sample dataset, I would like to have the following resultset:

entry prev
:info_2 :error_1
:info_3 :error_2
:info_4 :error_2

Using SPARQL property paths, the following query

SELECT * WHERE { 
?entry rdf:type :Info ;
    :hasPreviousEntry* ?prev .
?prev rdf:type :Error .
} ORDER BY ?entry

reasonably retrieves the following resultset:

entry prev
:info_2 :error_1
:info_3 :error_1
:info_3 :error_2
:info_4 :error_1
:info_4 :error_2

I cannot find how I could have the desired results. Any help would be highly appreciated.


Solution

  • Check that there doesn't exist another error linked by ?entry which in turn links to ?prev in at least one step.

    SELECT * WHERE { 
      ?entry rdf:type :Info ;
             :hasPreviousEntry* ?prev .
      ?prev rdf:type :Error .
      FILTER NOT EXISTS {
        ?entry :hasPreviousEntry* [ rdf:type :Error ;
                                    :hasPreviousEntry+ ?prev ] .
      }
    } ORDER BY ?entry