i want to avoid using substring to eliminate by example #en in my
ontology:abstract or ontology:label, it work with sparql explorer but when i use http query in jena it dont give any result... i tried this query in android project with jena library (androjena)
SELECT ?type (STR(?l) AS ?label) {
?type a owl:Class;
rdfs:label ?l .
FILTER (LANG(?l) = "en")
}
once i put this in my Jena httpquery (STR(?l) AS ?label)it dont give any result anymore. someone can help me?
here is the part of the code that i try to manage to change to avoid use of substrings :
private String entityQuery(String entity, String keyWord, String language) {
return addPrefix("rdfs: <http://www.w3.org/2000/01/rdf-schema#>") +
addPrefix("ontology: <http://dbpedia.org/ontology/>") +
addQuery("SELECT ?name ?desc ?thumb WHERE {\n"
+"?author a ontology:" + entity + ";\n"
+"rdfs:label ?name;\n"
+"ontology:abstract ?desc.\n"
+"FILTER(<bif:contains>(?desc,\"'"+keyWord+"'\") && langMatches(lang(?desc), \""+language+"\") " +
"&& langMatches( lang(?name), \""+language+"\"))\n"
+"OPTIONAL { ?author ontology:thumbnail ?thumb }.\n"
+"}ORDER BY ?name\n");
}
private LinkedList<Entity> collectEntities(ResultSet results) {
LinkedList<Entity> temp = new LinkedList<>();
/* do stuff with the results */
while (results.hasNext()) {
Entity a = new Entity();
QuerySolution row = results.next();
if (row.getResource("thumb") != null)
a.setPictureURL(row.get("thumb").toString());
a.setTitle(row.get("name").toString().substring(0, row.get("name").toString().indexOf("#")));
a.setSummary(row.get("desc").toString().substring(0, row.get("desc").toString().indexOf("#")));
temp.add(a);
}
return temp;
}
private String addPrefix(String prefix) {
return "PREFIX " + prefix + "\n";
}
private String addQuery(String query) {
return query;
}
i use substring here :
a.setTitle(row.get("name").toString().substring(0, row.get("name").toString().indexOf("#")));
a.setSummary(row.get("desc").toString().substring(0, row.get("desc").toString().indexOf("#")));
Related
I can write a SPARQL query to concat words in a sentence found in individual triples to a single sentence:
SELECT ?sent (sample (?sf1) as ?sf11) (group_concat(?wf) as ?sf2)
WHERE
{ ?sent a nlp:Sentence .
{select *
{ ?w rdfs:partOf ?sent .
?w a nlp:Token .
?w nlp:wordForm ?wf .
} order by ?w
}
} group by ?sent
limit 20
but I cannot find a way to use this select statement in another query, where I find the sentence ?sent and would like to insert this select statement:
select *
where
{ ?tok a wn:Locomote.
?tok nlp:lemma3 ?lem .
?tok rdfs:partOf ?sent .
?sent a nlp:Sentence .
?werk ^rdfs:partOf ?sent .
{SELECT ?sent (group_concat(?wf) as ?sf2)
WHERE
{ ?sent a nlp:Sentence .
{select *
{ ?w rdfs:partOf ?sent .
?w a nlp:Token .
?w nlp:wordForm ?wf .
} order by ?w
}
} group by ?sent
}
}
The result is a not the sentence found in the first part, but it seems as ?sent in the nested query is not restricted by the outer query.
I do not see how to nest properly.
Thank you for help!
Example of custom aggregate in Jena:
package org.stackoverflow.jena.customaggregate;
import com.google.common.base.Joiner;
import org.apache.jena.atlas.logging.LogCtl;
import org.apache.jena.graph.Graph;
import org.apache.jena.query.*;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.sparql.engine.binding.Binding;
import org.apache.jena.sparql.expr.Expr;
import org.apache.jena.sparql.expr.ExprEvalException;
import org.apache.jena.sparql.expr.ExprList;
import org.apache.jena.sparql.expr.NodeValue;
import org.apache.jena.sparql.expr.aggregate.Accumulator;
import org.apache.jena.sparql.expr.aggregate.AccumulatorFactory;
import org.apache.jena.sparql.expr.aggregate.AggCustom;
import org.apache.jena.sparql.expr.aggregate.AggregateRegistry;
import org.apache.jena.sparql.function.FunctionEnv;
import org.apache.jena.sparql.graph.NodeConst;
import org.apache.jena.sparql.sse.SSE;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class AggGroupConcatSorted {
static {
LogCtl.setCmdLogging();
}
static AccumulatorFactory accumulatorFactory = (agg, distinct) -> new AccGroupConcatSorted(agg);
static class AccGroupConcatSorted implements Accumulator {
private AggCustom agg;
private List<String> nodeStrList = new ArrayList<>();
AccGroupConcatSorted(AggCustom agg) {
this.agg = agg;
}
#Override
public void accumulate(Binding binding, FunctionEnv functionEnv) {
ExprList exprList = agg.getExprList();
for (Expr expr : exprList) {
try {
NodeValue nv = expr.eval(binding, functionEnv);
// Evaluation succeeded, add string to list
nodeStrList.add(nv.asString());
} catch (ExprEvalException ex) {
}
}
}
#Override
public NodeValue getValue() {
// sort list
Collections.sort(nodeStrList);
// return single node which in fact is the concatenated string of the list elements
return NodeValue.makeString(Joiner.on(" ").join(nodeStrList));
}
}
public static void main(String[] args) {
// Example aggregate that concatenates the node values in sorted order
String aggUri = "http://example.org/group_concat_sorted" ;
// register the custom aggregate - returns unbound for no rows
AggregateRegistry.register(aggUri, accumulatorFactory, NodeConst.nodeMinusOne);
// sample data
Graph g = SSE.parseGraph("(graph (:s :p \"b\") (:s :p \"bc\") (:s :p \"abc\"))") ;
String qs = "SELECT (<http://example.org/group_concat_sorted>(?o) AS ?x) {?s ?p ?o}" ;
// query execution
Query q = QueryFactory.create(qs) ;
try ( QueryExecution qexec = QueryExecutionFactory.create(q, ModelFactory.createModelForGraph(g)) ) {
ResultSet rs = qexec.execSelect() ;
ResultSetFormatter.out(rs);
}
}
}
public class Main {
public static void main(String args[]){
//read an ontology
String filename = "IOTOntology.owl";
Model model = ModelFactory.createDefaultModel();
OntModel model1 = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM);
//over
// Waits for the device ID
System.out.print("Enter name of man: ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String devID = null;
try {
devID = br.readLine();
} catch (IOException ioe) {
System.out.println("IO error trying to read device ID!");
System.exit(1);
}
try {
File file=new File(filename);
FileInputStream reader=new FileInputStream(file);
System.out.println("The absolute path of the file is:"+ file.getAbsolutePath());
model.read(reader, "RDF/XML");
// Create a SPARQL query from the given string.
String queryString = "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> "+
"PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> "+
"PREFIX owl: <http://www.w3.org/2002/07/owl#>" +
"PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>" +
//"PREFIX act: <http://www.semanticweb.org/project/ontologies/2016/0/Actor#>" +
"select ?name "+
"where { "+
" ?User a rdf:name"+
"} \n ";
Query query = QueryFactory.create(queryString);
try ( // Execute the query and obtain results
QueryExecution qe = QueryExecutionFactory.create(query, model)) {
ResultSet results = qe.execSelect();
// Output query results
ResultSetFormatter.out(System.out, results, query);
qe.close();
}
model.close();
} catch(Exception e) {
System.out.println(e.getMessage());
}
}
}
I have some problem because my table is empty, it writes in command line only this:
--------
| name |
========
--------
and this is the link to my ontology:
https://github.com/isidoramalkata/IOTOntology.git
I think you need to read some more about RDF and SPARQL first...
Your query is
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX owl: <http://www.w3.org/2002/07/owl#>
PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
PREFIX act: <http://www.semanticweb.org/project/ontologies/2016/0/Actor#>
select ?name where {
?User a rdf:name
}
That doesn't make any sense:
You select a variable ?name that doesn't occur in the query
you're using a as predicate which is a shortcut for rdf:type property, which in fact assigns resources to classes, thus, you would aak for resources that are of a type rdf:name
which moreover doesn't exist in your ontology
Have a look at the triple pattern:
?User a rdf:name
Your data is
<owl:NamedIndividual rdf:about="file://SHOnt.owl#UserIsidora">
<rdf:type rdf:resource="file://SHOnt.owl#User"/>
<SHOnt:phoneNumber rdf:datatype="http://www.w3.org/2001/XMLSchema#string">0605222024</SHOnt:phoneNumber>
<SHOnt:name rdf:datatype="http://www.w3.org/2001/XMLSchema#string">Isidora</SHOnt:name>
<SHOnt:email rdf:datatype="http://www.w3.org/2001/XMLSchema#string">isibojovic#gmail.com</SHOnt:email>
</owl:NamedIndividual>
There is no triple in your data that matches this pattern.
RDF triple means
subject predicate object
i.e.
#prefix shont: <file://SHOnt.owl#> .
#prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
shont:UserIsidora shont:name "Isidora"^^xsd:string .
This is Turtle syntax which is what SPARQL is based on, thus, it's always good to have a look at your data in this syntax.
SPARQL query:
prefix shont: <file://SHOnt.owl#>
prefix xsd: <http://www.w3.org/2001/XMLSchema#>
select ?name where {
?User shont:name ?name
}
As I said, you really should read an RDF tutorial first.
This question might sound lame but I am really confused...This is my code for normal query :
public class test4query extends Object {
public static String[] arr=new String[30];
public void mai (String s) {
String directory = "EMAILADDRESS" ;
Dataset ds = TDBFactory.createDataset(directory) ;
ds.begin(ReadWrite.READ) ;
Model model = ds.getDefaultModel() ;
QueryExecution qExec = QueryExecutionFactory.create(s, ds) ;
int i=0;
try{
ResultSet rs = qExec.execSelect() ;
String x=rs.toString();
while (rs.hasNext()) {
QuerySolution qs = rs.next();
String rds;
if(qs.get("x")!=null) {
rds = qs.get("x").toString();
} else {
rds="hi";
}
if(rds==null) {
break;
}
System.out.println(rds);
arr[i] = rds;
i++;
}
} finally
{qExec.close() ;
ds.commit();
ds.end();
}
}
}
But this does not work for delete queries ..It shows error :
Was expecting one of:
"base" ...
"prefix" ...
"select" ...
"describe" ...
"construct" ...
"ask" ...
I know some changes need to be made for update queries?Can somebody give some hint?Any link will be helpful!!
SPARQL Query and SPARQL Update are different languages, and there are different factories for parsing them. QueryFactory is for the SPARQL 1.1 Query Language. For the SPARQL 1.1 Update, you need to use UpdateFactory.
I'm trying to get information about some concepts on DBpedia. I found out how to get 1, but for more it fails. I've been told filtering should help, but the processing time is too long and i get timeouts.
The thing i can't do is VALUES ?s { dbpedia:Facebook dbpedia:Google }
So I've looked for an alternative way, but it still isn;t working. Here's where I'm now:
public static String concepts[] = { "Facebook", "Google" };
public static String getQuery(String concept) {
return "prefix dbpediaowl: <http://dbpedia.org/ontology/>"
+ " prefix dbpedia: <http://dbpedia.org/resource/>"
+ " prefix owl: <http://www.w3.org/2002/07/owl#>"
+ " prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> "
+ " PREFIX dbpprop: <http://dbpedia.org/property/>"
+ " prefix dbpedia-owl: <http://dbpedia.org/ontology/>"
+ " select ?s ?p ?o where { "
+ " values ?web { dbpedia:"
+ "Facebook"
+ " } "
+ " { ?web ?p ?o bind( ?web as ?s ) } " + " union "
+ " { ?s ?p ?web bind( ?web as ?o ) } " + " filter( ?p in ( "
+ "dbpprop:available, " + "dbpprop:company, "
+ "dbpprop:inventor, " + "dbpedia-owl:foundedBy, "
+ "dbpedia-owl:subsidiary, " + "dbpprop:foundation, "
+ "dbpprop:founder, " + "dbpprop:industry, "
+ "dbpprop:programmingLanguage, " + "dbpedia-owl:successor )) ";
}
public static void main(String[] args) {
OutputStream os;
PrintStream printStream;
try {
os = new FileOutputStream("C:/Users/alex/Desktop/data.txt");
printStream = new PrintStream(os);
printStream.println("am scris");
for (int i = 0; i < concepts.length; i++) {
printStream.println(i+ " concept");
Query query = QueryFactory.create(getQuery(concepts[i]));
QueryExecution qExe = QueryExecutionFactory.sparqlService(
"http://lod.openlinksw.com/sparql", query);
ResultSet results = qExe.execSelect();
while (results.hasNext()) {
printStream.println(results.nextSolution().toString());
}
}
printStream.close();
os.close();
} catch (Exception e) {
e.printStackTrace();
System.out.println(e.getCause());
}
}
For one concept at a time, in the SPARQL it works fine, but I need to call about 50 of them. So I need to know how i can do it programatically. Also, it would be great if you could help me select the predicates as well ( without the filtering ) because I also need to allow about 30-40 of them.
Thanks a lot! Hope you can help.
I thought we'd solved the problem with VALUES ?s { dbpedia:Facebook dbpedia:Google } in your previous question, Sparql about dbpedia:World_Wide_Web. Instead of doing values ?s { dbpedia:Facebook dbpedia:Google }, you can use filter( ?s in (dbpedia:Facebook, dbpedia:Google) }. This works just fine for subjects and properties. E.g., if you wanted to get the English abstracts and labels for Google and Facebook, you could use a query like this:
select ?s ?p ?o where {
?s ?p ?o
filter( ?s in (dbpedia:Google, dbpedia:Facebook) )
filter( ?p in (rdfs:label, dbpedia-owl:abstract) )
filter( !isLiteral(?o) || langMatches(lang(?o),"en") )
}
SPARQL results
Now, if you can get rid of that union (which you might be able to do, if you're really just looking for the values of certain properties from certain subjects), then you actually can use the values blocks in the way that you'd like to. (Really, I think the problematic behavior seen in your other question is due to a DBpedia bug; I think you should be able to use values and union together.) That is, to select non-literals, and literals with an English language tag for some specified properties, you can do:
select ?s ?p ?o where {
values ?s { dbpedia:Google dbpedia:Facebook }
values ?p { rdfs:label dbpedia-owl:abstract }
?s ?p ?o
filter( !isLiteral(?o) || langMatches(lang(?o),"en") )
}
SPARQL results
On my database, I have triples like:
DocumentUri -> dc.title -> title
DocumentUri -> dc.language -> language
DocumentUri -> dc.description -> description
DocumentUri -> dc.creator -> AuthorUri
I'd like to be able to search for a documenttitle and then get all the properties from all the documents matching the title search.
I'm trying to do that with Jena and SPARQL. I made a query that receives a title to get the Uris from the documents that have the given title. That's the method, it gets the uris returned and store them in a list called webDocumentListInicial:
public void searchUriByTitle() {
RDFNode documentUriNode;
String queryString = "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> " +
"PREFIX dc: <http://purl.org/dc/elements/1.1/> SELECT ?document WHERE { " +
"?document dc:title ?title." +
"FILTER (?title = \"" + this.getTitle() + "\" ). }";
Query query = QueryFactory.create(queryString);
QueryExecution qe = QueryExecutionFactory.create(query, databaseModel);
ResultSet results = qe.execSelect();
while( results.hasNext() ) {
QuerySolution querySolution = results.next();
documentUriNode = querySolution.get("document");
WebDocument document = new WebDocument(documentUriNode.toString());
this.webDocumentListInicial.add(document);
}
qe.close();
}
To get the document's creator I made another query, because in this case tha value from the triple is another resource. Here, I iterate the list of document URIs that was filled in the method above.
public void searchAuthorByTitle() {
for( WebDocument doc : this.webDocumentListInicial ) {
RDFNode authorUriNode;
String queryString = "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> " +
"PREFIX dc: <http://purl.org/dc/elements/1.1/> SELECT ?author WHERE { " +
"?document dc:creator ?author." +
"FILTER (?document = <" + doc.getUri() + "> ). }";
Query query = QueryFactory.create(queryString);
QueryExecution qe = QueryExecutionFactory.create(query, databaseModel);
ResultSet results = qe.execSelect();
while( results.hasNext() ) {
QuerySolution querySolution = results.next();
authorUriNode = querySolution.get("author");
WebAuthor author;
author = this.searchAuthorProperties(authorUriNode.toString(), new WebAuthor(authorUriNode.toString()) );
doc.addAuthor(author);
}
qe.close();
}
}
And to get the other document properties, I do like in the example below, where I iterate the list that was filled in the first method I showed above.
public void searchDescription() {
for( WebDocument doc : this.webDocumentListInicial ) {
String description = "";
Resource resource = ResourceFactory.createResource(doc.getUri());
StmtIterator descriptionStmtIt = databaseModel.listStatements(resource, DC.description,(RDFNode) null);
while( descriptionStmtIt.hasNext() ) {
description = descriptionStmtIt.next().getObject().toString();
}
doc.setDescription(description);
}
}
This way I'm handling with the data isn't very productive because I need a different query for each property I get.
Is it possible to make only one query to get the document URI and all the other document's properties at once? I tried that once, like this:
String queryString = "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> " +
"PREFIX dc: <http://purl.org/dc/elements/1.1/> SELECT ?document ?description " +
"?language ?author WHERE { " +
"?document dc:title ?title." +
"?document dc.language ?language" +
"?document dc.description ?description" +
"?document dc.creator ?author" +
"FILTER (?title = \"" + this.getTitle() + "\" ). }";
But when I had more than one document matching the given title, it was difficult to know which properties returned belonged to each document.
Thank you!!
Building a better query
It sounds like you're doing a lot more work than you need to. If you have data like this:
#prefix : <http://stackoverflow.com/q/20436820/1281433/>
:doc1 :title "Title1" ; :author :author1 ; :date "date-1" .
:doc2 :title "Title2" ; :author :author2 ; :date "date-2" .
:doc3 :title "Title3" ; :author :author3 ; :date "date-3" .
:doc4 :title "Title4" ; :author :author4 ; :date "date-4" .
:doc5 :title "Title5" ; :author :author5 ; :date "date-5" .
And a list of titles, say "Title1" "Title4" "Title5" and you want retrieve the resource of the document with each title, along with the associated author and date, you can use a query like this:
prefix : <http://stackoverflow.com/q/20436820/1281433/>
select ?document ?author ?date where {
values ?title { "Title1" "Title4" "Title5" }
?document :title ?title ;
:author ?author ;
:date ?date .
}
You'll get results like this in one ResultSet. There's no need to make multiple queries.
----------------------------------
| document | author | date |
==================================
| :doc1 | :author1 | "date-1" |
| :doc4 | :author4 | "date-4" |
| :doc5 | :author5 | "date-5" |
----------------------------------
Building a map of the results
Based on your comments, it sounds like you need to construct some other kind of associative structure from the ResultSet. Here's one way that you could construct a Map<RDFNode,Map<String,RDFNode>> that takes each document IRI to another map that takes each of the variable named to the associated value.
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.RDFNode;
public class HashedResultsExample {
final static String DATA =
"#prefix : <http://stackoverflow.com/q/20436820/1281433/>\n" +
"\n" +
":doc1 :title 'Title1' ; :author :author1 ; :date 'date-1' .\n" +
":doc2 :title 'Title2' ; :author :author2 ; :date 'date-2' .\n" +
":doc3 :title 'Title3' ; :author :author3 ; :date 'date-3' .\n" +
":doc4 :title 'Title4' ; :author :author4 ; :date 'date-4' .\n" +
":doc5 :title 'Title5' ; :author :author5 ; :date 'date-5' .\n" ;
final static String QUERY =
"prefix : <http://stackoverflow.com/q/20436820/1281433/>\n" +
"select ?document ?author ?date where {\n" +
" values ?title { \"Title1\" \"Title4\" \"Title5\" }\n" +
" ?document :title ?title ; :author ?author ; :date ?date .\n" +
"}" ;
public static void main(String[] args) throws IOException {
final Model model = ModelFactory.createDefaultModel();
try ( final InputStream in = new ByteArrayInputStream( DATA.getBytes() )) {
model.read( in, null, "TTL" );
}
final ResultSet rs = QueryExecutionFactory.create( QUERY, model ).execSelect();
final Map<RDFNode,Map<String,RDFNode>> map = new HashMap<>();
while ( rs.hasNext() ) {
final QuerySolution qs = rs.next();
final Map<String,RDFNode> rowMap = new HashMap<>();
for ( final Iterator<String> varNames = qs.varNames(); varNames.hasNext(); ) {
final String varName = varNames.next();
rowMap.put( varName, qs.get( varName ));
}
map.put( qs.get( "document" ), rowMap );
}
System.out.println( map );
}
}
The output (since the map is printed at the end) with some newlines for readability is:
{http://stackoverflow.com/q/20436820/1281433/doc4=
{author=http://stackoverflow.com/q/20436820/1281433/author4,
document=http://stackoverflow.com/q/20436820/1281433/doc4,
date=date-4},
http://stackoverflow.com/q/20436820/1281433/doc1=
{author=http://stackoverflow.com/q/20436820/1281433/author1,
document=http://stackoverflow.com/q/20436820/1281433/doc1,
date=date-1},
http://stackoverflow.com/q/20436820/1281433/doc5=
{author=http://stackoverflow.com/q/20436820/1281433/author5,
document=http://stackoverflow.com/q/20436820/1281433/doc5,
date=date-5}}