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

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>

Related

Fetch snap SPARQL query using OWL API in java web

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.

Is Apache Jena in java do dereferencing URLs automatically?If yes then what I can do to restrict it

FirstTestingClass.java
package com.mycompany.sparqlwithjena1;
import org.apache.jena.query.Query;
import org.apache.jena.query.QueryFactory;
import org.apache.jena.query.ResultSet;
import org.apache.jena.query.ResultSetFormatter;
import org.apache.jena.sparql.engine.http.QueryEngineHTTP;
public class FirstTestingClass {
public static void main(String[] args)
{
sparqlQuery();
}
static void sparqlQuery()
{
String url4= "http://dbpedia.org/sparql/";
String queryString =
"PREFIX ol: <http://www.openlinksw.com/schemas/virtrdf#> "+
" SELECT ?person ?x"+
" WHERE { "+
" ?person a ?x . "+
//" FILTER ( regex( str(?person) , 'resource' ,'i') ) ."+
" }";
Query query = QueryFactory.create(queryString);
QueryEngineHTTP qe= new QueryEngineHTTP(url4,queryString);
ResultSet result = qe.execSelect();
ResultSetFormatter.out(result, query);
qe.close();
}
}
This gives this kind of output
| person | x |
| http://www.openlinksw.com/virtrdf-data-formats#default-iid | ol:QuadMapFormat |
| http://www.openlinksw.com/virtrdf-data-formats#default-iid-nullable | ol:QuadMapFormat |
I only pasted two tuples of output there were more than 100 tuples in output.So Why this is happening?.Is It because of automatically URL dereferencing?.
I try query for same URL(=url4) on librdf.org .It gives only one tuple as output.
I also try to check triplets form on rdf-translator.appspot.com for URL(=url4) by converting automatically to N3 form.It also show there should be only one tuple for given query.
Please help where I did wrong?
I am beginner please explain it.
You're asking Jena to run a SPARQL query against the endpoint at http://dbpedia.org/sparql. You can go to that endpoint manually in a web browser and run your same query. You get lots of results when you run your query there. You asked about some other places, like
I try query for same URL(=url4) on librdf.org .It gives only one tuple
as output.
I'm not sure what exactly you mean by that. Do you mean you ran the same query on some endpoint that they support? If you did that, of course you'd get different results, because it's a different endpoint.
For comparison, if you run the same SQL query on different databases, you can very well get different results, because the data in those databases is different. Or if you ask different people, "How many siblings do you have?" you'll get different answers, because different people have different numbers of siblings.
The answer to your question is:
No, Jena is not automatically dereferencing URIs.
Please have a look at your SPARQL query. It is similar to
SELECT ?s ?o WHERE {
?s a ?o .
}
That you give the variables human readable names does not mean that the semantics is recognized when processing the query.
The triples that you are asking for with your query are all triples that have rdf:type as predicate. And the triples that you have shown are some Virtuoso internal triples - the triples store on which DBpedia is deployed. It might be solved when you set as default graph http://dbpedia.org in your Jena code:
qe.addDefaultGraph("http://dbpedia.org");

Jena Sparql only return direct superclass of instance

I'm using Jena in Java with Pellet as the reasoner. Now I need to query the class of a specific URI, but the problem is is that I don't know before hand what kind of instance it is, in what kind of class hierarchy, so I can't use filter options. When using:
SELECT * WHERE {<" + uri + "> rdf:type ?x}
It returns all superclasses. My hierarchy for this specific example looks like:
-Thing
-Person
-Adult
-Animal
-Dog
Every class has multiple instances. I don't know what kind of instance I'm querying beforehand. But let's say for example I'm querying an URI of an instance who is a type Dog. It will also return Animal and Thing. But I only want it to return Dog. Is that possible? Using LIMIT 1 only returns the direct superclass.
There is an easy way to do this with Jena which provides a special predicate to query for direct types so in your code you can generate the query as follows:
"SELECT * { <" + ind + "> <" + ReasonerVocabulary.directRDFType + "> ?type }"
or simply use the URI for this predicate directly in the query:
SELECT * { <ind> <urn:x-hp-direct-predicate:http_//www.w3.org/1999/02/22-rdf-syntax-ns#type> ?type }
It is also possible to write a rather inefficient but portable SPARQL query that will query direct types:
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX owl: <http://www.w3.org/2002/07/owl#>
SELECT * {
<ind> rdf:type ?directType .
FILTER NOT EXISTS {
<ind> rdf:type ?type .
?type rdfs:subClassOf ?directType .
FILTER NOT EXISTS {
?type owl:equivalentClass ?directType .
}
}
}
A class is a direct type of an individual if there is no other type of the individual that is a subclass of this type. But a direct type might have equivalent classes. To handle these cases we have to use double negation in the query. This query is inefficient because it first retrieves all the types of the individual and filters the ones that are not direct. But on the plus side you can use it with systems other than Jena that does not provide a dedicated direct type predicate.

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