SPARQL: How to get an insance of an ontology, if depth of the class hierarchy is unknown?
Asked Answered
A

1

8

I have a question about SPARQL. I have an ontology of animals:

Animals  (is a superclass with object property <hasColor>)
------ Mammals (subclass of Animals)
------------- Dog (subclass of Mammals)
---------------- dog1 (a instance with property <hasColor>="white")
---------------- dog2 (a instance with property <hasColor>="red"   )
------ Bird (subclass of Animals)

Is it possible to find with SPARQL "all Animals, that are 'white' " or "all instances of Animals"? And backwards: How can I know, if a instance (dog1) belongs to Animals?

NOTE: The depth and breadth of the class hierarchy is unknown in advance.

Also the query below will not work

SELECT ?x WHERE  {?x rdfs:subClassOf  :Animals .  ?x :hasСolor "white"}

And the next query (find all Animals, that are 'white') works only if the depth of class hierarchy is known. (So if the hierarchy is known, can I make the specified steps (from top of hierarchy to bottom) to reach the goal: in this case 2 steps.

SELECT ?z WHERE  {
?x  rdfs:subClassOf :Animals .
?y  rdfs:subClassOf ?x .
?z  rdf:type ?y .
?z :hasColor "white"
}

The same is true for the next example - "find all instances of Animals"

SELECT ?z WHERE  {
?x  rdfs:subClassOf :Animals .
?y  rdfs:subClassOf ?x .
?z  rdf:type ?y .
}

What to do, if the hierarchie is unknown?

The query will be processed with SDB (is a component of Jena).

I want something like : select ?x where {?x rdfs:subClassOf :Animals . ?x :hasСolor "white"})

UPD. Solution for "find all Animals (instances), that are 'white'" might look like this:

SELECT ?y WHERE { ?x rdfs:subClassOf* :Animals . ?y rdf:type ?x . ?y :hasColor "white"}

Anselme answered 30/3, 2012 at 11:41 Comment(0)
P
14

You can use transitivity in your SPARQL query (using *) :

SELECT ?y WHERE { ?x rdfs:subClassOf* :Animals . 
                  ?y rdf:type ?x . 
                  ?y :hasColor "white" }
Pohai answered 30/3, 2012 at 12:18 Comment(4)
Thanks! I tested the query with Protege. SELECT ?x WHERE {?x rdfs:subClassOf* :Animals } works fine. But SELECT ?x WHERE {?x rdfs:subClassOf* :Animals . ?x :hasСolor "white"} find no matchesAnselme
its strange the query SELECT ?x ?y WHERE {?x rdfs:subClassOf* :Animals . ?y rdf:type ?x ."} works fine too and returns all instances, but if adding (?x :hasСolor "white") finds it no matchesAnselme
@Anselme : and what about SELECT ?x WHERE {?x rdfs:subClassOf* :Animals . ?y rdf:type ?x . ?y :hasColor "white"} ?Pohai
That query will return all classes that is a descendant of Animals and have a colour "white". What you want is to find all instances of such classes, where the instance has a the colour "white". Something like this "SELECT ?x WHERE {?t rdfs:subClassOf* :Animals . ?x a t . ?x :hasСolor "white"}Hipolitohipp

© 2022 - 2024 — McMap. All rights reserved.