Fetch snap SPARQL query using OWL API in java web - java

oke, I have this snap SPARQL query using protege
PREFIX owl: <http://www.w3.org/2002/07/owl#>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX :<http://www.semanticweb.org/astrid/ontologies/2019/5/mpasiv2#>
SELECT ?resep_makanan
WHERE {
?resep_makanan rdf:type :resep_makanan.
?resep_makanan :resep_untuk :6-7_bulan.
}
ORDER BY ?resep_makanan
and it works, i get instance for my resep_makanan which are food name, with object property resep_untuk (recipe_for) baby who is 6-7_bulan (6-7_month old).
then in my java web code, i write
PREFIX :<http://www.semanticweb.org/astrid/ontologies/2019/5/mpasiv2#>
SELECT DISTINCT ?resep_makanan
WHERE {
Type (?resep_makanan, :resep_makanan),
PropertyValue(?resep_makanan, :resep_untuk, :6-7_bulan)
}
order by ?resep_makanan
But i get 0 query result.
Im using OWL API.
How should i write it correctly?

Looking up 'snap SPARQL' brings the https://github.com/protegeproject/snap-sparql-query project, which I believe is what you're actually using to run your queries (as it's used in Protege).
If that's the case, you're not using OWL API for the SPARQL part of your code, as OWL API does not support SPARQL itself; I don't know the snap sparql project but, as it integrates with Protege, which is OWL API based, I assume OWL API is used for interfacing a SPARQL based API with Protege. From the project dependencies, I think that's de-derivo-sparqldlapi.
To answer your question, if the same query does not produce a result outside of Protege this must depend on it not being sent to the same SPARQL endpoint or to a different set up of the endpoint (e.g., does your query depend on reasoning for its results?)
Some of this information might be in the code that you're running and have not shown here, but we won't be able to tell without seeing it.

Related

How to add a SERVICE clause to SelectBuilder using Apache Jena's query builder?

I’m using the Jena query builder from the Jena-extras and I was wondering if there was a way to add a SERVICE clause to a SelectBuilder object.
My code right now looks like this:
SelectBuilder builder = new SelectBuilder()
.addPrefix( "rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#" )
.addPrefix("dbo", "http://dbpedia.org/ontology/")
.addVar("?uri")
.addWhere("?uri", "rdf:type", "dbo:Company")
.setLimit(100);
Query query = builder.build();
System.out.println(query);
which outputs this:
PREFIX dbo: <http://dbpedia.org/ontology/>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
SELECT ?uri
WHERE
{ ?uri rdf:type dbo:Company}
LIMIT 100
I’ve also tried adding the SERVICE clause to a Query object after calling builder.build(), but it seems like it’s only possible through the ARQ API using body.addElement(new ElementService("http://any.domain/sparql", elementBlock)). The problem is that you can’t get the elementBlock from a Query object or SelectBuilder object.
Is there a way to add a SERVICE clause using the query builder or are there known workarounds without resorting to the verbose ARQ API, or should I try and extend the SelectBuilder API myself?
For anyone having the same problem, I asked the devs who gave me a useful hint (thank you, Andy Seaborne), and the solution seems to be as follows:
SelectBuilder builder = new SelectBuilder()
.addPrefix( "rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#" )
.addPrefix("dbo", "http://dbpedia.org/ontology/")
.addVar("?uri")
.addWhere("?uri", "rdf:type", "dbo:Company")
.setLimit(100);
Query query = builder.build();
ElementGroup body = new ElementGroup();
body.addElement(new ElementService("http://dbpedia.org/sparql", query.getQueryPattern()));
query.setQueryPattern(body);
System.out.println(query);
This code outputs the following query:
PREFIX dbo: <http://dbpedia.org/ontology/>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
SELECT ?uri
WHERE
{ SERVICE <http://dbpedia.org/sparql>
{ ?uri rdf:type dbo:Company}
}
LIMIT 100
Too bad that this isn't a part of the query builder's fluent API out of the box, but any savvy Java engineer can write an extension or helper for this.

Sparql with Java Jena

I'm using next query in Wikidata Query Service:
PREFIX wd: <http://www.wikidata.org/entity/>
PREFIX wdt: <http://www.wikidata.org/prop/direct/>
PREFIX xsd: <www.w3.org/2001/XMLSchema#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
select ?lexemeId ?lemma WHERE {
?lexemeId <http://purl.org/dc/terms/language> wd:Q1860.
?lexemeId wikibase:lemma ?lemma.
FILTER (regex(?lemma, '^bank.*'))
}
It works fine when executing at https://query.wikidata.org/ but, if trying using Java Jena, it fails, cause:
Exception in thread "main" org.apache.jena.query.QueryParseException: Line 7, column 11: Unresolved prefixed name: wikibase:lemma
It can't resolve wikibase as a prefix.
Any clue?
Thx in advance, David.
When you use their SPARQL query page a number of prefixes are pre-declared, including wikibase. When querying the endpoint remotely these have to be declared. So use PREFIX wikibase: <http://wikiba.se/ontology#> in your query.
A list of prefixes is available in the wiki

How to get all properties from a URI (jena, RDF, dbpedia)?

Suppose the URI is http://dbpedia.org/page/Ansungtangmyun from the Named Graph http://dbpedia.org, within Data Space dbpedia.org
This resource includes the following properties:
dbo:abstract
dbo:wikipageid
dct:subject
rdfs:comment
etc.
What I have tried is to get one property at a time by exploring the graph. I am using Jena. To enhance the performance, I would like to ask whether there is a way/API to get all properties at once?
First thing, I'd use the resource ID URI --
http://dbpedia.org/resource/Ansungtangmyun
-- instead of the HTML page URI --
http://dbpedia.org/page/Ansungtangmyun
-- which is to say, this query (and its live results) --
SELECT ?p ?o
WHERE
{
<http://dbpedia.org/resource/Ansungtangmyun> ?p ?o
}
You might also be interested in this (and its live results) --
DESCRIBE <http://dbpedia.org/resource/Ansungtangmyun>
Try the following SPARQL query:
SELECT ?p
WHERE {
<http://dbpedia.org/page/Ansungtangmyun> ?p ?o
}
You can directly get a whole graph having your property as subject by using a simple DESCRIBE query.
DESCRIBE <http://dbpedia.org/resource/Ansungtangmyun>

How to add triples to a jena Query

Suppose I have some jena query object :
String query = "SELECT * WHERE{ ?s <some_uri> ?o ...etc. }";
Query q = QueryFactory.create(query, Syntax.syntaxARQ);
How would one go about getting information about the jena query object and adding in triples to it iteratively in an effective manner? For example, suppose I wanted to add in the triples
?o dcterms:title "TheBestTitle".
?o dcterms:date ?date.
to the query, and perhaps more.
Is there some way to add in these triples to the query, or do some magic to create a new query object which looks like the original with those triples added in? Assume that I may need to grab information from the original version of the query as well (for example, List resultVars = q.getResultVars();).
Some leads I have are to use the AlgebraGenerator and Op Classes provided by the Jena API, but I can't seem to find any reasonable use cases in a context such as this.
Thanks!
http://jena.apache.org/documentation/query/manipulating_sparql_using_arq.html
Construct an algebra expression and convert to a query (OpAsQuery)
The Query object, which is the cleaned up parsed struture, can be manipulated (Query.getQueryPattern)
Do it by string manipulation before parsing.

How to build SPARQL queries in java?

Is there a library, which is able to build SPARQL queries programmatically like the CriteriaBuilder in JPA or to build the queries like with a PreparedStatement for SQL?
Similar (for SQL): Cleanest way to build an SQL string in Java
You can build queries programmatically in Jena using two methods: syntax or algebra. There's an introduction in the jena wiki.
Using the algebra you'd do something like:
Op op;
BasicPattern pat = new BasicPattern(); // Make a pattern
pat.add(pattern); // Add our pattern match
op = new OpBGP(pat); // Make a BGP from this pattern
op = OpFilter.filter(e, op); // Filter that pattern with our expression
op = new OpProject(op, Arrays.asList(Var.alloc("s"))); // Reduce to just ?s
Query q = OpAsQuery.asQuery(op); // Convert to a query
q.setQuerySelectType(); // Make is a select query
(taken from the wiki page)
It's not CriteriaBuilder (nor was it intended to be), but is some of the way there. You OpJoin rather than AND, OpUnion when you want to OR, etc. The pain points are expressions in my experience: you probably want to parse them from a string.
The recent versions of Jena have added a StringBuilder style API for building query/update strings and parameterizing them if desired.
This class is called ParameterizedSparqlString, here's an example of using it to create a query:
ParameterizedSparqlString queryStr = new ParameterizedSparqlString();
queryStr.setNSPrefix("sw", "http://skunkworks.example.com/redacted#");
queryStr.append("SELECT ?a ?b ?c ?d");
queryStr.append("{");
queryStr.append(" ?rawHit sw:key");
queryStr.appendNode(someKey);
queryStr.append(".");
queryStr.append(" ?rawHit sw:a ?a .");
queryStr.append(" ?rawHit sw:b ?b .");
queryStr.append(" ?rawHit sw:c ?c . ");
queryStr.append(" ?rawHit sw:d ?d .");
queryStr.append("} ORDER BY DESC(d)");
Query q = queryStr.asQuery();
Disclaimer - I'm the developer who contributed this functionality to Jena
See What's the best way to parametize SPARQL queries? for more discussion on doing this across various APIs.
I implemented SPARQL Java - a kind of DSL for writing SPARQL queries in Java.
It solves the problem with IDE's auto formatting of concatenated SPARQL query strings and things like that.
As for example:
String shortQuery = Q.prefix("books", "http://example.org/books#")
.select("?book ?authorName", new where() {
{
$("?book books:author ?author");
$("?author books:authorName ?authorName");
}
}).get();
I recently started to use Sesame query builder. It looks promising except it doesn't provide much documentation and I struggled to find examples. Here is simple sample which may help you to get started:
ParsedTupleQuery query = QueryBuilderFactory
.select("pubProperty", "pubPropertyValue")
.group()
.atom(cmResource(resourceId), LinkPublicationsTransformation.REFERENCE_URI, "pubUri")
.atom("pubUri", "pubProperty", "pubPropertyValue")
.filter(isLiteral("pubPropertyValue"))
.closeGroup()
.query();
Just note that isLiteral and cmResource are my own little static helper classes. isLiteral stands for new IsLiteral(new Var("...")) for example where the latter one create URI with my heavily used prefix.
You might be then also interested in SPARQLQueryRenderer which can turn ParsedQuery into String which may be convenient for further usage.
If you end up using String(Builder) approach what I discourage you to do have at least a look on RenderUtils from sesame-queryrendered which has all the convenient methods to add < > around URIs, escape special characters etc.
The Eclipse RDF4J framework (the successor of Sesame) offers a Repository API which is somewhat similar to JDBC - it allows you to create a prepared Query object and inject variable bindings before executing it:
String query = "SELECT * WHERE {?X ?P ?Y }";
TupleQuery preparedQuery = conn.prepareQuery(QuerLanguage.SPARQL, query);
preparedQuery.setBinding("X", someValue);
...
TupleQueryResult result = preparedQuery.evaluate();
In addition, RDF4J has a SparqlBuilder (originally known as spanqit) - a Java DSL for SPARQL which allows you to create SPARQL queries in code like this:
query.prefix(foaf).select(name)
.where(x.has(foaf.iri("name"), name))
.orderBy(name)
.limit(5)
.offset(10);
I have just released a beta project to do just this, called Spanqit.
I strove for readability and an intuitive interface, for example, here is some example Spanqit syntax for creating a query:
query.prefix(foaf).select(name)
.where(x.has(foaf.iri("name"), name))
.orderBy(name)
.limit(5)
.offset(10);
Check it out, and feel free to comment and suggest improvements!
Jena provides a QueryBuilder in the Extras package.
https://jena.apache.org/documentation/extras/querybuilder/index.html
It does what you want.
You can use the Jena Semantic Framework (SPARQL documentation). Also take a look at this related question. Sadly, its syntax is closer to a SQL PreparedStatement than to the JPA.

Categories