Sparql request for kids, grandchildren, .. class

I have an owl file that I created in Protege. What is a sparql query that will select all subclasses of a class and all subclasses of those subclasses, and so on and so forth. (Breadth First Search Sort of Manner)?

+2


source to share


1 answer


This may be answered by a Sparql or EquivalentTo subclass , but this question and its answer have a lot more information about what you are asking here. You can't really enforce a search strategy (depth vs depth first), but you can (sort) the order of the subclasses by their distance from the root if there is a unique path from the root to the subclass. First, let's get some sample data:

@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>.
@prefix : <https://stackoverflow.com/q/23094361/1281433/>.

#            a
#          /   \
#         b     c
#        / \   / \
#       d   e f   g 

:b rdfs:subClassOf :a .
:c rdfs:subClassOf :a .

:d rdfs:subClassOf :b .
:e rdfs:subClassOf :b .

:f rdfs:subClassOf :c .
:g rdfs:subClassOf :c .

      

You can use a query like this to get subclasses :a

:

prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>
prefix : <https://stackoverflow.com/q/23094361/1281433/>

select ?subclass where {
  ?subclass rdfs:subClassOf* :a
}

      

------------
| subclass |
============
| :a       |
| :c       |
| :g       |
| :f       |
| :b       |
| :e       |
| :d       |
------------

      



The results include :a

because we used the path rdfs:subClassOf*

. This is logically correct since the class is a subclass of itself, but if you don't want to include :a

, you can use rdfs:subClassOf+

, or you can filter :a

with filter( ?subclass != :a )

.

In case there is one path from the root to the subclass, you can count the intermediate nodes between them to determine their depth. If you order in depth this way, you will get your results in something like the first breadth search will give you the following. This method is described in more detail in Is it possible to get the position of an element in an RDF collection in SPARQL? and Calculate path length between nodes? ...

prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>
prefix : <https://stackoverflow.com/q/23094361/1281433/>

select ?subclass (count(?intermediate)-1 as ?depth) where {
  ?subclass rdfs:subClassOf* ?intermediate .
  ?intermediate rdfs:subClassOf* :a .
}
group by ?subclass
order by ?depth

      

 
--------------------
| subclass | depth |
====================
| :a       | 0     |
| :b       | 1     |
| :c       | 1     |
| :d       | 2     |
| :e       | 2     |
| :f       | 2     |
| :g       | 2     |
--------------------

      

+6


source







All Articles