Tomas
Tomas

Reputation: 1667

How to write SPARQL query to find a literal match in all objects of all classes using Jena?

(1) I have some ontology with the next structure:enter image description here Each individual has a "Data Property" with name "value_of_individual" and literal.
For example, individualA1 has value_of_individual with literal valueA1; individualB2 has value_of_individual with literal valueB2 etc.

(2) I want to create next query: find a literal match in all objects of all classes. If there is a coincidence - return true, if there is no coincidence - return false.

(3) I found that I need use ASK query. For, example:

QueryExecution queryExecution = QueryExecutionFactory.create(""
            + "ASK { GRAPH ?g { ?s ?p ?o } }"
            + "", dataset);
    boolean res = queryExecution.execAsk();
    System.out.println("The result is " + res);

(4) My question:
How do I write the query described in clause 2 and combine it with the query described in clause 3?

Edit:
I have input word, for example, "MyLiteral". I want to know if there are Individuals in the ClassA, ClassB, ClassC that have a literal as a "MyLiteral" in the data property.

Upvotes: 1

Views: 1157

Answers (1)

UninformedUser
UninformedUser

Reputation: 8465

(I'm still not sure if I understood your question correctly, especially because you wrote "find a literal match in all objects of all classes" and the "all objects" is confusing...)

You have to invert the result of the following query to get the answer to your original question which I simply rewrote as:

"Is there a class that doesn't contain at least one individual with "MyLiteral" as value of the property :value_of_individual?" :

PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
PREFIX owl: <http://www.w3.org/2002/07/owl#>
PREFIX : <http://www.semanticweb.org/test-ontology#> 
ASK { 
?cls a owl:Class
FILTER NOT EXISTS {
 ?s a ?cls .
 ?s :value_of_individual "MyLiteral"^^xsd:string
}
}

Update

As per comment from @StansilavKralin, if the question is more about to check whether there is "any class with an individual having the given value" the question would be exactly what @StansilavKralin wrote in his other comment:

PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> 
PREFIX : <http://www.semanticweb.org/test-ontology#> 
ASK {
  ?s :value_of_individual "MyLiteral"^^xsd:string
}

Final solution

PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> 
PREFIX test: <http://www.semanticweb.org/test-ontology#> 
ASK {
 VALUES ?cls {test:ClassA test:ClassB test:ClassC} 
 ?s a ?cls .
 ?s test:value_of_individual "valueC3"^^xsd:string 
}

Upvotes: 2

Related Questions