How to retrieve a column's value in sparql - sparql

Ineed to retrieve a column's value once the query is executed. The query runs and gives me the correct answer in the Eclipse console. I need to just retrieve one of the attribute value from the row.
The Complete code is stored in SemanticSearch.java. This function is called from Admin.java.
public int searchForUser(String userName, String password)
{
String prolog="PREFIX kb:<"+VUSER.getURI()+">";
System.out.println("Search for user in semantic search.java");
String queryString1=prolog
+"\n" +"SELECT interest "
+WHERE {?x kb:Uname ?username. ?x kb:Password ?password. ?x kb:Interest ?interest. "
+"FILTER regex(?username, \"" +userName +"\" )}";
System.out.println(queryString1);
Query query=QueryFactory.create(queryString1);
QueryExecution qexec = QueryExecutionFactory.create(query, model);
ResultSet results1 = qexec.execSelect();
//System.out.println(results1);
//ResultSetFormatter.out(results1);
ResultSetFormatter.out(System.out, results1,query);
if(results1.getRowNumber()>0)
{
QuerySolution soln=results1.nextSolution();
Literal RES=soln.getLiteral("Interest");
String RES=results1.
int res=results1.getRowNumber();
System.out.println(RES);
return res;
}
else
{
return 0;
}
}
The Output is:
PREFIX kb:http://protege.stanford.edu/kb#
SELECT * WHERE {?x kb:Uname ?username. ?x kb:Password ?password. ?x kb:Interest ?interest. FILTER regex(?username, "anu" )}
| x | username | password | interest |
| kb:Anvika | "anu" | "anu" | "C language" |
After this error comes:
Feb 10, 2011 10:50:56 AM org.apache.catalina.core.StandardWrapperValve invoke SEVERE:
Servlet.service() for servlet Admin threw exception java.util.NoSuchElementException: QueryIteratorCloseable
at com.hp.hpl.jena.sparql.engine.iterator.QueryIteratorBase.nextBinding(QueryIteratorBase.java:93)
at com.hp.hpl.jena.sparql.engine.ResultSetStream.nextBinding(ResultSetStream.java:74)
at com.hp.hpl.jena.sparql.engine.ResultSetStream.nextSolution(ResultSetStream.java:91)
at semanticsearch.SemanticSearch.searchForUser(SemanticSearch.java:126)
at controller.Admin.doGet(Admin.java:84) at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:857)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Unknown Source)
I am not able to retrieve the value at a column.
Help.
Regards.

Ok so then my next suspicion would be that you've tried to iterate past the end of the iterator. Using the condition results1.getRowNumber()>0 is a very bad idea since it is always going to be > 0 as far as I can tell (though this isn't clear from the Javadoc for ARQ).
Instead I would replace the condition with results1.hasNext() and see if that fixes it
Redacted Original Answer
I suspect this is just a case of variable names being case sensitive.
Replace the line:
Literal RES=soln.getLiteral("Interest");
With the line:
Literal RES=soln.getLiteral("interest");
And I suspect it will work fine.

Related

How to convert a class expression (from restriction unionOf) to a string?

A SPARQL query returns a result with restrictions with allValuesFrom and unionOf. I need do concat these values, but, when I use bind or str functions, the result is blank.
I tried bind, str and group_concat functions, but, all of it was unsuccessful. Group_concat return a blank node.
SELECT DISTINCT ?source ?is_succeeded_by
WHERE {
?source rdfs:subClassOf ?restriction .
?restriction owl:onProperty j.0:isSucceededBy .
?restriction owl:allValuesFrom ?is_succeeded_by .
FILTER (REGEX(STR(?source), 'gatw-Invoice_match'))
}
Result of SPARQL query in Protegé:
You can hardly obtain strings like 'xxx or yyy' programmatically in Jena,
since it is Manchester Syntax, an OWL-API native format, and it is not supported by Jena.
Any class expression is actually b-node, there are no such builtin symbols like 'or' in raw RDF.
To represent any anonymous class expression as a string, you can use ONT-API,
which is a jena-based OWL-API, and, therefore, both SPARQL and Manchester Syntax are supported there.
Here is an example based on pizza ontology:
// use pizza, since no example data provided in the question:
IRI pizza = IRI.create("https://raw.githubusercontent.com/owlcs/ont-api/master/src/test/resources/ontapi/pizza.ttl");
// get OWLOntologyManager instance from ONT-API
OntologyManager manager = OntManagers.createONT();
// as extended Jena model:
OntModel model = manager.loadOntology(pizza).asGraphModel();
// prepare query that looks like the original, but for pizza
String txt = "SELECT DISTINCT ?source ?is_succeeded_by\n" +
"WHERE {\n" +
" ?source rdfs:subClassOf ?restriction . \n" +
" ?restriction owl:onProperty :hasTopping . \n" +
" ?restriction owl:allValuesFrom ?is_succeeded_by .\n" +
" FILTER (REGEX(STR(?source), 'Am'))\n" +
"}";
Query q = new Query();
q.setPrefixMapping(model);
q = QueryFactory.parse(q, txt, null, Syntax.defaultQuerySyntax);
// from owlapi-parsers package:
OWLObjectRenderer renderer = new ManchesterOWLSyntaxOWLObjectRendererImpl();
// from ont-api (although it is a part of internal API, it is public):
InternalObjectFactory iof = new SimpleObjectFactory(manager.getOWLDataFactory());
// exec SPARQL query:
try (QueryExecution exec = QueryExecutionFactory.create(q, model)) {
ResultSet res = exec.execSelect();
while (res.hasNext()) {
QuerySolution qs = res.next();
List<Resource> vars = Iter.asStream(qs.varNames()).map(qs::getResource).collect(Collectors.toList());
if (vars.size() != 2)
throw new IllegalStateException("For the specified query and valid OWL must not happen");
// Resource (Jena) -> OntCE (ONT-API) -> ONTObject (ONT-API) -> OWLClassExpression (OWL-API)
OWLClassExpression ex = iof.getClass(vars.get(1).inModel(model).as(OntClass.class)).getOWLObject();
// format: 'class local name' ||| 'superclass string in ManSyn'
System.out.println(vars.get(0).getLocalName() + " ||| " + renderer.render(ex));
}
}
The output:
American ||| MozzarellaTopping or PeperoniSausageTopping or TomatoTopping
AmericanHot ||| HotGreenPepperTopping or JalapenoPepperTopping or MozzarellaTopping or PeperoniSausageTopping or TomatoTopping
Used env: ont-api:2.0.0, owl-api:5.1.11, jena-arq:3.13.1

Filter by predicate attributes

How can I get all chairpersons, which are still holding this job (where the predicate has no end date?).
My current version returns all chairpersons:
SELECT ?chairperson ?x WHERE {
?university wdt:P488 ?chairperson.
}

Null pointer exception error while using BIND in SPARQL query in JENA virtuoso

I am getting below error while running SPARQL query,
ERROR [main] (RDFDefaultErrorHandler.java:40) - (line 7 column 7): {E201} The attributes on this property element, are not permitted with any content; expecting end element tag.
ERROR [main] (RDFDefaultErrorHandler.java:40) - (line 7 column 38): {E201} XML element <res:binding> inside an empty property element, whose attributes prohibit any content.
ERROR [main] (RDFDefaultErrorHandler.java:40) - (line 7 column 52): {E201} XML element <res:variable> inside an empty property element, whose attributes prohibit any content.
ERROR [main] (RDFDefaultErrorHandler.java:40) - (line 7 column 57): {E201} The attributes on this property element, are not permitted with any content; expecting end element tag.
WARN [main] (RDFDefaultErrorHandler.java:36) - (line 8 column 135): {W102} unqualified use of rdf:datatype is deprecated.
java.lang.NullPointerException
at com.hp.hpl.jena.rdf.arp.impl.XMLHandler.endElement(XMLHandler.java:149)
at org.apache.xerces.parsers.AbstractSAXParser.endElement(Unknown Source)
at org.apache.xerces.impl.XMLNamespaceBinder.handleEndElement(Unknown Source)
at org.apache.xerces.impl.XMLNamespaceBinder.endElement(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanEndElement(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl$FragmentContentDispatcher.dispatch(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
at org.apache.xerces.parsers.DTDConfiguration.parse(Unknown Source)
at org.apache.xerces.parsers.DTDConfiguration.parse(Unknown Source)
at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source)
at com.hp.hpl.jena.rdf.arp.impl.RDFXMLParser.parse(RDFXMLParser.java:142)
at com.hp.hpl.jena.rdf.arp.JenaReader.read(JenaReader.java:158)
at com.hp.hpl.jena.rdf.arp.JenaReader.read(JenaReader.java:145)
at com.hp.hpl.jena.rdf.arp.JenaReader.read(JenaReader.java:215)
at com.hp.hpl.jena.rdf.model.impl.ModelCom.read(ModelCom.java:197)
at com.hp.hpl.jena.sparql.engine.http.QueryEngineHTTP.execModel(QueryEngineHTTP.java:169)
at com.hp.hpl.jena.sparql.engine.http.QueryEngineHTTP.execDescribe(QueryEngineHTTP.java:162)
at com.hp.hpl.jena.sparql.engine.http.QueryEngineHTTP.execDescribe(QueryEngineHTTP.java:160)
at com.hospital.SPARQLQuery.main(SPARQLQuery.java:34)
Sample TTL file data
#prefix dc: <http://purl.org/dc/elements/1.1/> .
#prefix : <http://example.org/book/> .
#prefix ns: <http://example.org/ns#> .
:book1 dc:title "SPARQL Tutorial" .
:book1 ns:price 42 .
:book1 ns:discount 0.2 .
:book2 dc:title "The Semantic Web" .
:book2 ns:price 23 .
:book2 ns:discount 0.25 .
I am using the Virtuoso SPARQL endpoint to run a query
here is my code which i am running.
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.rdf.model.Model;
public class SPARQLQuery {
private static final Logger logger = LogManager.getLogger(SPARQLQuery.class);
public static void main(String[] args) {
try {
String queryString = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\r\n" +
"PREFIX ns: <http://example.org/ns#>\r\n" +
"\r\n" +
"SELECT ?title ?price\r\n" +
"{ ?x ns:price ?p .\r\n" +
" ?x ns:discount ?discount\r\n" +
" BIND (?p*(1-?discount) AS ?price)\r\n" +
" FILTER(?price < 20)\r\n" +
" ?x dc:title ?title . \r\n" +
"}";
QueryExecution qexec = QueryExecutionFactory.sparqlService("http://localhost:8890/sparql", queryString);
Model results = qexec.execDescribe();
results.write(System.out,"TTL");
}catch(Exception ex) {
ex.printStackTrace();
}
}
}
Maven dependency
<dependency>
<groupId>com.hp.hpl.jena</groupId>
<artifactId>arq</artifactId>
<version>2.8.8</version>
</dependency>
I am facing strange issue while using BIND in my SPARQL query. I don't understand what's the actual problem or I can't figure out why this is happening. Also, I am using the Virtuoso for graph data store and I am using Jena lib for running the SPARQL query. While running the query I am getting error.I didn't find any solution on google.
As revealed in comments by #AKSW, answer is to
update to current Jena (and possibly current Virtuoso server [whether Enterprise or Open Source], Virtuoso Provider for Jena, and/or Virtuoso JDBC driver)
use correct call/query pairing (i.e., call Jena .execSelect() with a SPARQL SELECT query, or call Jena .execDescribe() with a SPARQL DESCRIBE query).

How to solve SPARQL warning?

I am trying to retrieve the name of inkers of Comic books. I am trying to build an ontology. Inkers has dbpprop and I have imported rdlib and sparqlWrapper whilst I am having following error. Is there any one who understand this problem?
Abcde-MacBook-Pro:example Abcde$ python basicTest.py
WARNING:rdflib.term: does not look like a valid URI, trying to serialize this will break.
Abcde-MacBook-Pro:example Abcde$ python basicTest.py
Traceback (most recent call last):
File "basicTest.py", line 78, in <module>
g = sparql.query().convert()
File "build/bdist.macosx-10.10-intel/egg/SPARQLWrapper/Wrapper.py", line 535, in query
File "build/bdist.macosx-10.10-intel/egg/SPARQLWrapper/Wrapper.py", line 513, in _query
SPARQLWrapper.SPARQLExceptions.EndPointInternalError: EndPointInternalError: endpoint returned code 500 and response.
Response:
Virtuoso RDF01 Error Bad variable value in CONSTRUCT: "Malcolm Jones III" (tag 246 box flags 0) is not a valid subject, only object of a triple can be a literal
SPARQL query:
define sql:big-data-const 0
#output-format:application/rdf+xml
My code looks like
CONSTRUCT {
?comics ma:inked_by ?inker .
?inker rdf:type ma:Inker .
}
WHERE{
?comics rdf:type dbpedia-owl:Comics .
?comics foaf:name ?name .
OPTIONAL {?comics dbpprop:inkers ?inker}
FILTER regex(str(?name), "Batman")
}"""
I think the problem arises when you get the ?inker out. Sometime it is a URI and sometime it is a string. For example, the following are the top two outputs:
"Malcolm Jones III"
http://dbpedia.org/resource/Vince_Colletta
I think you need to change your code in a way that your inker is either a URI or a string. The following will save the URI in your ontology, if it exists. If you need a string use the ?inkername instead.
CONSTRUCT {
?comics ma:inked_by ?inker.
?inker a ma:Inker.
}
where {
?comics a dbpedia-owl:Comics.
?comics foaf:name ?name .
optional{
?comics dbpprop:inkers ?inker.
?inker foaf:name ?inkername.
}
FILTER regex(str(?name), "Batman")
}

Simple Jena SPARQL query not working

What am I doing wrong here?
public class SimpleSearchTest {
public static void main(String[] args) throws Exception {
Model model = ModelFactory.createDefaultModel();
model.getGraph().add(new Triple(Node.createURI("a"), Node.createURI("b"), Node.createURI("c")));
String queryString = "SELECT ?p ?o WHERE { <a> ?p ?o }";
Query query = QueryFactory.create(queryString);
QueryExecution qExec = QueryExecutionFactory.create(query, model);
ResultSetFormatter.out(qExec.execSelect());
}
}
I am expecting
-------------
| p | o |
=============
| <b> | <c> |
-------------
But instead I am getting no results:
---------
| p | o |
=========
---------
I am sure it is something dumb...
I think the SPARQL parser isn't liking your <a> because it's not a legal URI (though it's odd that you don't get a warning). If you change your code as follows:
model.getGraph().add(new Triple(Node.createURI("http://example.com/a"), Node.createURI("b"), Node.createURI("c")));
String queryString = "SELECT ?p ?o WHERE { <http://example.com/a> ?p ?o }";
you get the result you are expecting.
Parenthetically, by creating the test graph with Node.createURI() you are using the lower-level internal Graph API, rather than the more normally used Model API. It's perfectly fine to do this, but the Graph API generally assumes you know more what you are doing, and may have fewer checks against doing the unexpected.