Anonymous
Anonymous

Reputation: 1

print multiple path in rdf graph using sparql query

My data which simply denotes two paths from :a to :v and k respectively is as follows:

@prefix : <http://m/questions/19587520/sparql-path-between-two-instance/> .

:a :z :d.    
:d :p :e .      
:e :g :f .    
:f :l :g .    
:g :m :h .    
:h :p :k .    
:k :p :c .    
:c :p :v . 

:a :p :x.    
:x :q :y.    
:y :z :c.    
:a :l :g .    
:g :m :h .    
:h :p :k .

The SPARQL queries that I tried are

     String querygraph=
 "PREFIX : <http://m/questions/19587520/sparql-path-between-two-instance/>" +

                 "SELECT ?start  ?end (count(?mid) as ?length)" +
                 "WHERE {" +
                   " values (?start ?end) { (:a :c) " +
                 " } " +
                    " ?start (: |!:)+ ?mid . " +
                  " ?mid (: | !:)* ?end . " +
                 " } " +
                 " group by ?start ?end " +
                   " ORDER BY ASC(?length)";


     String querygraph1=
             "PREFIX : <http://monika/questions/19587520/sparql-path-between-two-instance/>" +

         "select  (count(?m) as ?length) " +
                  "WHERE {" +
                  " values (?s ?d) { (:a :c) " +
                     " } " +
                  "?s  (:|!:)+ ?m ."+
                  " ?m (: | !:)* ?d . " +


                "}" ;

In this I need to print and calculate length of path but the problem is there are two paths from :a to :c. My code is not able to differentiate between them, it calculates it as one. Please help me to print both paths separately with their length.

Upvotes: 0

Views: 372

Answers (1)

Robin Keskisarkka
Robin Keskisarkka

Reputation: 896

This is not possible in the general case using SPARQL. But if you you know of some intermediate node that needs to be visited you can add this part as part of the triple pattern.

Another option that may work is if you put the two paths in different named graphs:

@prefix : <http://m/questions/19587520/sparql-path-between-two-instance/> .
GRAPH :path1 {
  :a :z :d.    
  :d :p :e .      
  :e :g :f .    
  :f :l :g .    
  :g :m :h .    
  :h :p :k .    
  :k :p :c .    
  :c :p :v . 
}
GRAPH :path2 {
  :a :p :x.    
  :x :q :y.    
  :y :z :c.    
  :a :l :g .    
  :g :m :h .    
  :h :p :k .
}

Then you could express a query against the first graph as:

PREFIX : <http://m/questions/19587520/sparql-path-between-two-instance/>

SELECT DISTINCT ?midI ?p ?midJ
FROM :path1
where {
  VALUES (?begin ?end) { (:a :k) }
  ?begin !:* ?midI .
  ?midI ?p ?midJ .
  ?midJ !:* ?end .
}

This way you can avoid having the two paths cross each other. However, property paths in SPARQL cannot guarantee a shortest path (or all paths for that matter), only that there is one. You can count the length as well. There is a useful question here on stackoverflow that is related to this problem that I would recommend having a look at: Finding all steps in property path.

Upvotes: 1

Related Questions