Search code examples
sparql

SPARQL In a query, how to filter out superclasses after a specific class has been found?


I want to find out the superclasses of a subclass but filter out all the superclass after finding a specific class. For example, this tree (from this question):

Main
   |__ Network
   |         |__ ATM
   |         |__ ARPANET
   |
   |__ Software
              |__ Linux
              |__ Windows
                        |__ XP
                        |__ Win7
                        |__ Win8

I want to find the superclasses for win7, but left out all superclasses above "Software" class:

Software
       |__ Windows
                 |__ Win7

This is the first thing I did:

SELECT ?superClass 
WHERE {
   :Win7 rdfs:subClassOf ?superClass .
   FILTER (?superClass != :Software)
}

But only left out :Software, and I want to filter our all other superclasses


Solution

  • Most direct way is to use prperty paths and FILTER NOT EXISTS to exclude everything above :Software e.g.:

    select * where { 
        :Win7 rdfs:subClassOf+ ?super .
        filter not exists {
            :Software rdfs:subClassOf+ ?super
        }
    }