I used Protege to create a small ontology.
I start with a class A, a class B, and a class C. Class C contains the subclasses x, y and z. The individuals populating this ontology fall under two classes: the first class is either A or B, the second one is one of the subclasses of C.
I want to retrieve all individuals which have a property H, and which are also either part of class x or y, but not z. I have been able to do that with the following query:
SELECT ?individual
WHERE {?individual ont:hasH ?individual.
FILTER(NOT EXISTS { ?individual rdf:type ont:z } )}
(ont is the prefix for my ontology)
This query does what I want. But for these individuals, I would also like to know whether they are part of class x or y. I've tried changing my query to the following, to no avail:
SELECT ?individual ?class
WHERE {?individual ont:hasH ?individual.
FILTER(NOT EXISTS { ?individual rdf:type ont:z } ) ?class rdf:type ont:C}
Since x and y belong to class C, what I need to know what the class C of the selected individuals is. How could I do that?
(Please bear in mind that I'm completely new to SPARQL.)
You say a couple of things that make the issue a bit confusing:
I start with a class A, a class B, and a class C. Class C contains the subclasses x, y and z.
…
Since x and y belong to class C,
We don't usually say that a class contains subclasses; we just say that a class has subclasses, or that one class is a subclass of another. When A is a subclass of B, then whenever some i is an A (ie, we have the triple [i rdf:type A]), then i is also a B (ie, we have the triple [i rdf:type B]).
At any rate, you can do the following to find out, for each individual that has an ont:hasH property and is not an instance of ont:z, whether it's an ont:x or an ont:y:
SELECT ?individual ?class WHERE {
#-- The first part, which you already provided, ensures that
#-- ?individual has a value for ont:hasH, and does not have
#-- type ont:z .
?individual ont:hasH ?individual.
FILTER( NOT EXISTS { ?individual rdf:type ont:z } )
#-- Since each of these individuals also has type ont:x or
#-- ont:y, you can bind a variable to ont:x and ont:y and
#-- match against it, too. For each result, ?xy will be
#-- bound to either ont:X or ont:y, depending on what type
#-- ?individual has.
values ?xy { ont:x ont:y }
?individual rdf:type ?xy
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.