7

I need to write a SPARQL query to find a superclass/subclasses of a given class.

For example, given http://139.91.183.30:9090/RDF/VRP/Examples/Phenomenon.rdf RDFS vocabulary file, I want to find the superclass of 'AcousticWave' (which is 'Wave').

Similarly if user enters 'Wave', I want to get all sub classes of 'Wave' (which are 'AcousticWave', 'GravityWave', 'InternalWave' and Tide').

enter image description here

How would I write such SPARQL query?

Ajinkya Kulkarni
  • 984
  • 2
  • 11
  • 19

1 Answers1

12

The predicate used in rdfs for state sub/super class relationships is rdfs:subClassOf. With that in mind you just need to write triple patterns in your SPARQL query that bind that predicate and the subject or object that you want to match --- AcousticWave in your case.

I hope that the following queries are self-explanatory.

for super classes ...

PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX ns: <http://www.domain.com/your/namespace/>

SELECT ?superClass WHERE { ns:AcousticWave rdfs:subClassOf ?superClass . }

And for sub classes ...

SELECT ?subClass WHERE { ?subClass rdfs:subClassOf ns:Wave . }

If you want to retrieve the labels for every subclass of ns:Wave you would do something like ...

SELECT ?subClass ?label WHERE { 
        ?subClass rdfs:subClassOf ns:Wave . 
        ?subClass rdfs:label ?label . 
}

If you need the transitive closure of sub/super classes then you have two options:

  1. Iterate recursively over these queries until you have collected the closure.
  2. Pass your RDF data through a RDF/RDFS reasoner to forward chain all entailments and assert these in your RDF database.
Manuel Salvadores
  • 16,287
  • 5
  • 37
  • 56
  • Which namespace should i use for class Wave here in above file ? – user1583465 Feb 04 '15 at 09:43
  • It really depends on the data. I put a sample namespace because I did not know when I answer the question here. – Manuel Salvadores Feb 04 '15 at 15:35
  • 6
    There a SPARQL way to do transitive query using operator * or + over predicate see the [Property Path](https://www.w3.org/TR/sparql11-query/#propertypaths) part from the W3C. For all transitive sub classes of owl:thing : `SELECT ?subClass WHERE { ?subClass rdfs:subClassOf* owl:thing .}` It should answer : ns:Wave, ns:Tide… See also [this question](http://stackoverflow.com/questions/8569810/sparql-querying-transitive). – Marc_Alx Apr 04 '16 at 15:56