SPARQL which is the path connecting two objects?

我只是一个虾纸丫 提交于 2019-12-07 20:03:31

问题


Hi all I'd like to discover if there is a relation between two nodes and if any the predicates connecting them. Let's say my graph is like following

                    [Uri1]
                 /          \
          (pred:a)          (pred:b)    
         /      \           /       \
    [Uri2]      [Uri3]  [Uri4]      [Uri5]
    /     \ 
(pred:c) (pred:d)  
  /             \
[Uri6]         [Uri7]
                  \
                  (pred:a)
                     \
                     [Uri8]

If the query is looking for the relations between Uri8 and Uri1, the expected result should be

[Uri7] = pred:a

[Uri2] = pred:d

[Uri1] = pred:a

Consider that predicates (relations) between nodes may vary and also lengths.

the two following: SPARQL: is there any path between two nodes? and Is it possible to return relationships between two objects in SPARQL? do not work


回答1:


The approaches in those questions do work, although the explanations in Is it possible to get the position of an element in an RDF Collection in SPARQL? and Finding all steps in property path might help even more in understanding the solution. Here's some data to test with, if I've understood your example correctly:

@prefix : <urn:ex:>

:uri1 :a :uri2, :uri3 ;
      :b :uri4, :uri5 .

:uri2 :c :uri6 ;
      :d :uri7 .

:uri7 :a :uri8 .

Here's the query. The idea is to follow a wildcard path from the beginning (:uri1) to some point ?x. Then we take a link from ?x to its object ?o, and then find a wildcard path from ?o to the ?end (:uri8). (Note that I'm using (:|!:) as a property wildcard; it matches everything since every IRI is either : or not :.)

prefix : <urn:ex:>

select ?x ?p where {
  :uri1 (:|!:)* ?x .
  ?x ?p ?o .
  ?o (:|!:)* :uri8 .
}

The results are just like what you asked for:

--------------
| x     | p  |
==============
| :uri1 | :a |
| :uri2 | :d |
| :uri7 | :a |
--------------


来源:https://stackoverflow.com/questions/35408237/sparql-which-is-the-path-connecting-two-objects

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