Sparql - recursion return depth

I did the first recursive query to find the entire child of a specific number:

SELECT distinct ?child
WHERE {
?child rdfs:subClassOf* num_108999. 
}

      

I would like to add recursion depth, for example if my data looks like this:

108999 --> 2004 --> 218

      

I want in return:

?child | ?depth
_______|_______
2004   | 1
218    | 2

      

To do this, I can use "UNION" and elt {n}:

SELECT * WHERE {
{
    SELECT distinct (1 as ?count) ?child
    WHERE {
    ?child rdfs:subClassOf{1} num_108999. 
    }
}UNION{
    SELECT distinct (2 as ?count) ?child
    WHERE {
    ?child rdfs:subClassOf{2} num_108999. 
    }
}

      

I think everything is ok with 2 depths, but in full data I have 20 depths ... How to pass the number of depths in an auto increment variable?

Thank!

Update: I found a small solution: split the elt {*} value into elt {+} and elt {*}.

SELECT distinct (count(?mid) as ?count) ?child
WHERE {
?mid rdfs:subClassOf+ num_108999. 
?child rdfs:subClassOf* ?mid. 
}

      

It works great with binary tree. But I don't have a binary tree, my data looks like this:

          /--> 2003 --\
108999 --/             \--> 218
         \---> 2004 --/

      

The previous queries count each path: 108999 to 2003, 2003 to 218, 108999 to 2004, and 2004 to 218.

So the return value is 4, not 2 ...

+3


source to share


1 answer


First, notice that

?child rdfs:subClassOf{1} num_108999. 

      

is not a legal SPARQL. SPARQL 1.1 did not include the {m, n} qualifiers for property paths, although this was in an earlier draft. However, Virtuoso supports it. The specification for it allows you to do

  {n} # exactly n
 {m,} # at least m
 {,n} # no more than n
{m,n} # at least m and no more than n

      



This last form is exactly what you want (as long as you use an endpoint that supports it):

?child rdfs:subClassOf{1,2} num_108999

      

It won't help you find the length of a specific path, but you can't do it in SPARQL in general. If there was only one path from beginning to end, then you could, but if there are multiple paths, you cannot.

0


source







All Articles