Finding shortest path with SPARQL query

走远了吗. 提交于 2019-12-09 06:27:24

问题


I am trying to understand the computational limitations of the SPARQL query, and I would like know how to write a query that will determine if there is a directed path between two objects.

I know a way to do it for a path of a specific length:

SELECT ?a ?b ?c ?d
WHERE { ?a  <http://graphtheory/hasNeighbor>  ?b . 
        ?b  <http://graphtheory/hasNeighbor>  ?c .
        ?c  <http://graphtheory/hasNeighbor>  ?d .
        FILTER (?a != ?c && ?b != ?d
                && ?a = <http://graphtheory/node/1>
                && ?d = <http://graphtheory/node/2>)
      }
LIMIT 10

Is there a way to search for any length path in a single query? Is this impossible with SPARQL?


回答1:


AndyS gave all the elements to answer this question, but there are some typos that might make it hard to apply them. As he says:

SPARQL 1.1 has property path which includes the * operator for any number of.

It does not tell you what the path is nor the length of the shortest path - only whether there is such a path.

The way to do this (based on AndyS, but with two little fixes) is:

PREFIX : <http://graphtheory/>
PREFIX node: <http://graphtheory/node/>

ASK { node:1 :hasNeighbor* node:2 }

As far as I can tell, there is no way to do this without using property paths.




回答2:


SPARQL 1.1 has property paths which include the * operator for “any number of”.

It does not tell you what the path is nor the length of the shortest path—only whether there is such a path.

PREFIX : <http://graphtheory/node/>
PREFIX node: <http://graphtheory/node/>

ASK { node:1 :hasNeighbor* node:2 }

(You don't need the ?a = and ?d =, you can write the values into the query.)

Adding a path datatype into the language is a place for future work—a few experimental systems have taken a look at the problem.



来源:https://stackoverflow.com/questions/14388864/finding-shortest-path-with-sparql-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!