Java Code Examples for org.apache.jena.query.QueryExecution#execSelect()
The following examples show how to use
org.apache.jena.query.QueryExecution#execSelect() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ExTDB5.java From xcurator with Apache License 2.0 | 6 votes |
public static void main(String... argv) { // Direct way: Make a TDB-back Jena model in the named directory. String directory = "MyDatabases/DB1" ; Dataset dataset = TDBFactory.createDataset(directory) ; // Potentially expensive query. String sparqlQueryString = "SELECT (count(*) AS ?count) { ?s ?p ?o }" ; // See http://incubator.apache.org/jena/documentation/query/app_api.html Query query = QueryFactory.create(sparqlQueryString) ; QueryExecution qexec = QueryExecutionFactory.create(query, dataset) ; try { ResultSet results = qexec.execSelect() ; for ( ; results.hasNext() ; ) { QuerySolution soln = results.nextSolution() ; int count = soln.getLiteral("count").getInt() ; System.out.println("count = "+count) ; } } finally { qexec.close() ; } // Close the dataset. dataset.close(); }
Example 2
Source File: ExTDB4.java From xcurator with Apache License 2.0 | 6 votes |
public static void main(String... argv) { // Direct way: Make a TDB-back Jena model in the named directory. String directory = "MyDatabases/DB1" ; Dataset dataset = TDBFactory.createDataset(directory) ; // Potentially expensive query. String sparqlQueryString = "SELECT (count(*) AS ?count) { ?s ?p ?o }" ; // See http://incubator.apache.org/jena/documentation/query/app_api.html Query query = QueryFactory.create(sparqlQueryString) ; QueryExecution qexec = QueryExecutionFactory.create(query, dataset) ; ResultSet results = qexec.execSelect() ; ResultSetFormatter.out(results) ; qexec.close() ; dataset.close(); }
Example 3
Source File: SPARQLExecutor.java From NLIWOD with GNU Affero General Public License v3.0 | 5 votes |
/** * An exact copy of this code is {@link SPARQL#executeSelect(String)}. * @param query * @param endpoint * @return */ @Deprecated public static Results executeSelect(final String query, final String endpoint) { QueryExecution qeExe = QueryExecutionFactory.sparqlService(endpoint, query); ResultSet rs = qeExe.execSelect(); Results res = new Results(); res.header.addAll(rs.getResultVars()); while(rs.hasNext()) { QuerySolution sol = rs.nextSolution(); res.table.add(new ArrayList<String>()); for(String head: res.header) { String answer = ""; if(sol.get(head).isResource()) { answer = sol.getResource(head).toString(); } else { String temp = sol.get(head).toString(); if(temp.contains("@")) { answer = "\"" + temp.substring(0, temp.indexOf("@")) + "\"" + temp.substring(temp.indexOf("@")); } else if (temp.contains("^^")){ answer = "\"" + temp.substring(0, temp.indexOf("^")) + "\"^^<" + temp.substring(temp.indexOf("^")+2) + ">"; } else { answer = temp; } } res.table.get(res.table.size()-1).add(answer); } } return res; }
Example 4
Source File: Utils.java From SDA with BSD 2-Clause "Simplified" License | 5 votes |
public static final void getTripleCount() throws Exception { String serviceURI = Utils.getSdaProperty("com.pineone.icbms.sda.knowledgebase.sparql.endpoint"); String queryString = "select (count(?s) as ?count) where {?s ?p ?o }"; QueryExecution queryExec = QueryExecutionFactory.sparqlService(serviceURI, queryString); ResultSet rs = queryExec.execSelect(); // 값을 console에 출력함 ResultSetFormatter.out(rs); }
Example 5
Source File: Test.java From SDA with BSD 2-Clause "Simplified" License | 5 votes |
public void updateTest() { // Add a new book to the collection // String service = "http://219.248.137.7:13030/icbms/update"; // UpdateRequest ur = UpdateFactory // .create("" // + "delete { <http://www.pineone.com/campus/TemperatureObservationValue_LB0001> <http://data.nasa.gov/qudt/owl/qudt#hasNumericValue> ?value . } " // + "insert { <http://www.pineone.com/campus/TemperatureObservationValue_LB0001> <http://data.nasa.gov/qudt/owl/qudt#hasNumericValue> \"19\" . } " //<-- 19대신 여기 온도를 넣어주세 // + "WHERE { <http://www.pineone.com/campus/TemperatureObservationValue_LB0001> <http://data.nasa.gov/qudt/owl/qudt#hasNumericValue> ?value . }"); // UpdateProcessor up = UpdateExecutionFactory.createRemote(ur, service); // up.execute(); // Query the collection, dump output // String service1 = "http://219.248.137.7:13030/icbms/"; // QueryExecution qe = QueryExecutionFactory.sparqlService(service1, // "SELECT * WHERE {<http://www.pineone.com/campus/Student_S00001> ?r ?y} limit 20 "); // // ResultSet results = qe.execSelect(); // ResultSetFormatter.out(System.out, results); // qe.close(); Model model = ModelFactory.createDefaultModel(); Statement s = model.createStatement(model.createResource("ex:e1"),model.createProperty("ex:p1"), ResourceFactory.createTypedLiteral(new String("0.6"))); model.add(s); String query = "select * {?s ?p ?o }"; QueryExecution qe = QueryExecutionFactory.create(query, model); ResultSet results = qe.execSelect(); ResultSetFormatter.out(System.out, results); qe.close(); }
Example 6
Source File: ExTDB_Txn1.java From xcurator with Apache License 2.0 | 5 votes |
public static void execQuery(String sparqlQueryString, Dataset dataset) { Query query = QueryFactory.create(sparqlQueryString) ; QueryExecution qexec = QueryExecutionFactory.create(query, dataset) ; try { ResultSet results = qexec.execSelect() ; for ( ; results.hasNext() ; ) { QuerySolution soln = results.nextSolution() ; int count = soln.getLiteral("count").getInt() ; System.out.println("count = "+count) ; } } finally { qexec.close() ; } }
Example 7
Source File: ClassSurfaceForms.java From NLIWOD with GNU Affero General Public License v3.0 | 5 votes |
public static void main(String[] args) throws IOException, InterruptedException { CLASS_SURFACE_FORMS = DIRECTORY + "class_surface_forms.ttl"; // create an empty model Model inputModel = ModelFactory.createDefaultModel(); // use the FileManager to find the input file InputStream in = FileManager.get().open(DBPEDIA_CLASSE_FILE); if (in == null) { throw new IllegalArgumentException("File: " + DBPEDIA_CLASSE_FILE + " not found"); } // read the RDF/XML file inputModel.read(in, null, "N-TRIPLE"); Model outputModel = ModelFactory.createDefaultModel(); QueryExecution qExec = QueryExecutionFactory .create("SELECT ?s ?label WHERE{?s a <http://www.w3.org/2002/07/owl#Class>." + " ?s <http://www.w3.org/2000/01/rdf-schema#label> ?label. " + "FILTER (lang(?label) = \"en\")}", inputModel); ResultSet rs = qExec.execSelect(); while (rs.hasNext()) { QuerySolution qs = rs.next(); Resource uri = qs.get("?s").asResource(); RDFNode label = qs.get("?label"); StatementImpl s = new StatementImpl(uri, RDFS.label, label); outputModel.add(s); } qExec.close(); FileOutputStream outputFile = new FileOutputStream(CLASS_SURFACE_FORMS); RDFDataMgr.write(outputFile, outputModel, RDFFormat.NTRIPLES); }
Example 8
Source File: Utils.java From SDA with BSD 2-Clause "Simplified" License | 5 votes |
/** * DW데이타 지우기 * @throws Exception * @return void */ public static final void deleteDWTripleAll2() throws Exception { String serviceURI = Utils.getSdaProperty("com.pineone.icbms.sda.knowledgebase.dw.sparql.endpoint"); String queryString = "delete data where {?s ?p ?o }"; QueryExecution queryExec = QueryExecutionFactory.sparqlService(serviceURI, queryString); ResultSet rs = queryExec.execSelect(); ResultSetFormatter.out(rs); }
Example 9
Source File: SPARQLDataProxy.java From Knowage-Server with GNU Affero General Public License v3.0 | 5 votes |
private ResultSet executeSPARQLQuery(QueryExecution queryExecution) { queryExecution.setTimeout(executionTimeout * 1000); Monitor monitor = MonitorFactory.start("Knowage.SPARQLDataProxy.executeSPARQLQuery"); ResultSet resultSet = null; try { resultSet = queryExecution.execSelect(); } finally { monitor.stop(); } return resultSet; }
Example 10
Source File: SPARQL.java From NLIWOD with GNU Affero General Public License v3.0 | 5 votes |
/** * Executes a select query for the given endpoint and query. Returns the answer as an {@link Results} object. * @param query * @param endpoint * @return */ public static Results executeSelect(final String query, final String endpoint) { QueryExecutionFactory qef = new QueryExecutionFactoryHttp(endpoint); QueryExecution qe = qef.createQueryExecution(query); ResultSet rs = qe.execSelect(); Results res = new Results(); res.header.addAll(rs.getResultVars()); while(rs.hasNext()) { QuerySolution sol = rs.nextSolution(); res.table.add(new ArrayList<String>()); for(String head: res.header) { String answer = ""; if(sol.get(head).isResource()) { answer = sol.getResource(head).toString(); } else { String temp = sol.get(head).toString(); if(temp.contains("@")) { answer = "\"" + temp.substring(0, temp.indexOf("@")) + "\"" + temp.substring(temp.indexOf("@")); } else if (temp.contains("^^")){ answer = "\"" + temp.substring(0, temp.indexOf("^")) + "\"^^<" + temp.substring(temp.indexOf("^")+2) + ">"; } else { answer = temp; } } res.table.get(res.table.size()-1).add(answer); } } closeExecFactory(qef); return res; }
Example 11
Source File: SPARQL.java From NLIWOD with GNU Affero General Public License v3.0 | 5 votes |
/** * Fire a sparql query against endpoint defined in constructor. * <p> * <b>NOTE:</b> This will block. To set a maximum execution time, use {@link ThreadedSPARQL} * <p> * For string representation of answers, see {@link #extractAnswerStrings(Set)} * * @param query * - a sparql query * @return */ public Set<RDFNode> sparql(final String query) { Set<RDFNode> set = Sets.newHashSet(); QueryExecution qe = qef.createQueryExecution(query); if ((qe != null) && (query != null)) { if (QALD4_EvaluationUtils.isAskType(query)) { set.add(new ResourceImpl(String.valueOf(qe.execAsk()))); } else { ResultSet results = qe.execSelect(); String firstVarName = results.getResultVars().get(0); while (results.hasNext()) { RDFNode node = results.next().get(firstVarName); /** * Instead of returning a set with size 1 and value (null) in it, when no answers are found, this ensures that Set is empty */ if (node != null) { set.add(node); } } } qe.close(); } return set; }
Example 12
Source File: QueryAnswerTypeAnalyzer.java From NLIWOD with GNU Affero General Public License v3.0 | 5 votes |
/*** * Queries the DBpedia SPARQL endpoint for the range of the given property. * @param property * @return range of the property */ private String queryRange(String property) { String q = "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> SELECT ?x {<" + property + "> rdfs:range ?x. }"; QueryExecution qe = QueryExecutionFactory.sparqlService(SERVICE, q); ResultSet rs = qe.execSelect(); if(rs.hasNext()) { QuerySolution solution = rs.nextSolution(); RDFNode node = solution.get("?x"); return node.toString(); } return "Misc"; }
Example 13
Source File: DBpediaToWikiId.java From gerbil with GNU Affero General Public License v3.0 | 5 votes |
/** * The Wikipedia Id or -1 if the Id couldn't be retrieved. * * FIXME The method throws an exception for "http://DBpedia.org/resource/Origin_of_the_name_"Empire_State"". this * might be happen because of the quotes inside the URI. * * @param dbpediaUri * @return */ @Deprecated public static int getIdFromDBpedia(String dbpediaUri) { int id = -1; ParameterizedSparqlString query = new ParameterizedSparqlString( "SELECT ?id WHERE { ?dbpedia dbo:wikiPageID ?id .}", prefixes); query.setIri("dbpedia", dbpediaUri); QueryExecution qexec = null; try { qexec = QueryExecutionFactory.create(query.asQuery(), model); } catch (QueryParseException e) { LOGGER.error("Got a bad dbpediaUri \"" + dbpediaUri + "\" which couldn't be parse inside of a SPARQL query. Returning -1.", e); return id; } ResultSet result = qexec.execSelect(); if (result.hasNext()) { id = result.next().get("id").asLiteral().getInt(); return id; } qexec = QueryExecutionFactory.sparqlService( "http://dbpedia.org/sparql", query.asQuery()); result = qexec.execSelect(); if (result.hasNext()) { id = result.next().get("id").asLiteral().getInt(); model.add(new StatementImpl(model.createResource(dbpediaUri), model .createProperty("http://dbpedia.org/ontology/wikiPageID"), model.createTypedLiteral(id))); return id; } model.add(new StatementImpl(model.createResource(dbpediaUri), model .createProperty("http://dbpedia.org/ontology/wikiPageID"), model.createTypedLiteral(id))); return id; }
Example 14
Source File: Utils.java From SDA with BSD 2-Clause "Simplified" License | 5 votes |
public static final void getTripleAll() throws Exception { String serviceURI = Utils.getSdaProperty("com.pineone.icbms.sda.knowledgebase.sparql.endpoint"); String queryString = "select ?s ?p ?o {?s ?p ?o}"; QueryExecution queryExec = QueryExecutionFactory.sparqlService(serviceURI, queryString); ResultSet rs = queryExec.execSelect(); ResultSetFormatter.out(rs); }
Example 15
Source File: Utils.java From SDA with BSD 2-Clause "Simplified" License | 5 votes |
public static final void getTripleCount() throws Exception { String serviceURI = Utils.getSdaProperty("com.pineone.icbms.sda.knowledgebase.sparql.endpoint"); String queryString = "select (count(?s) as ?count) where {?s ?p ?o }"; QueryExecution queryExec = QueryExecutionFactory.sparqlService(serviceURI, queryString); ResultSet rs = queryExec.execSelect(); // 값을 console에 출력함 ResultSetFormatter.out(rs); }
Example 16
Source File: KnowledgeCardCreator.java From NLIWOD with GNU Affero General Public License v3.0 | 4 votes |
public List<Field> getRelevantProperties(String uri, List<String> Answer, HashSet<String> properties) { List<Field> fields = new ArrayList<Field>(); try { TreeMap<Float, String> propertyMap = new TreeMap<Float, String>(); List<ExplorerProperties> explorerProperties = readCSVWithExplorerProperties(properties); for (ExplorerProperties property : explorerProperties) { // Check if the property matches one of the list of classes(types) found for the entity if (Answer.contains(property.getClassName())) { propertyMap.put(Float.parseFloat(property.getScore()), property.getProperty()); } } if (propertyMap.size() > 0) { int count = 0; Iterator<Float> iterator = propertyMap.descendingKeySet().iterator(); // Sorts descending order String property_uris = ""; while (count < MAX_FIELD_SIZE && iterator.hasNext()) { property_uris += "<" + propertyMap.get(iterator.next()) + "> "; count++; } String query = PREFIXES + "SELECT ?property_label (group_concat(distinct ?value;separator='__') as ?values) (group_concat(distinct ?value_label;separator='__') as ?value_labels) where {\n" + "VALUES ?property {" + property_uris + "}\n" + "<" + uri + "> ?property ?value . \n" + "?property rdfs:label ?property_label . FILTER(lang(?property_label)='en'). \n" + "OPTIONAL {?value rdfs:label ?value_label . FILTER(lang(?value_label) = 'en') }\n" + "} GROUP BY ?property_label"; QueryExecution queryExecution = executeQuery(query); try { Iterator<QuerySolution> results = queryExecution.execSelect(); while (results.hasNext()) { QuerySolution result = results.next(); Field field = new Field(); field.setName(result.get("property_label").asLiteral().getString()); // If Value Label String is empty then we use Value String instead which means // the value is a literal. So we are only taking the first element before space if (result.get("value_labels").asLiteral().getString().equals("")) { field.setValue(result.get("values").asLiteral().getString().split("__")[0]); } else { LinkedHashMap<String, String> map = new LinkedHashMap<String, String>(); String[] keyArray = result.get("values").asLiteral().getString().split("__"); String[] valueArray = result.get("value_labels").asLiteral().getString().split("__"); for (int index = 0; index < keyArray.length; index++) { map.put(keyArray[index], valueArray[index]); } field.setValues(map); } fields.add(field); } return fields; } finally { queryExecution.close(); } } return fields; } catch (Exception e) { e.printStackTrace(); } return fields; }
Example 17
Source File: LoadTest.java From NLIWOD with GNU Affero General Public License v3.0 | 4 votes |
private boolean execQuery(final IQuestion q, final boolean hurry) { Query query = new Query(); // Execute the query and obtain results QueryExecutionFactoryHttp qef = new QueryExecutionFactoryHttp("http://139.18.2.164:3030/ds/sparql"); Boolean queryValid = true; if (hurry) { log.debug("Testing query for parsability: " + q.getId() + ": " + q.getLanguageToQuestion().get("en")); } else { log.debug("Testing query for parsability and returned results: " + q.getId() + ": " + q.getLanguageToQuestion().get("en")); } try { query = QueryFactory.create(q.getSparqlQuery()); // Execute the query and obtain results QueryExecution qe = qef.createQueryExecution(query.toString()); if (!q.getGoldenAnswers().isEmpty()) { if (!hurry) { ResultSet results = qe.execSelect(); if (results.toString().contains(q.getGoldenAnswers().toString())) { log.info("Question result doesn't contain golden answer!"); log.info("Actual results: " + results.toString()); log.info("Golden answers: " + q.getGoldenAnswers().toString()); } } log.debug("Query valid for q" + q.getId() + " - " + q.getLanguageToQuestion().get("en")); // log.debug(query.toString()); queryValid = (queryValid && true); qe.close(); } } catch (Exception e) { // FIXME bereits hier eine Assertion mit Message einbauen sonst // sieht man oben nur das das flag false ist aber nicht warum und // wieso if (e.getClass() != org.apache.jena.sparql.resultset.ResultSetException.class) { log.debug(q.getSparqlQuery()); log.info("Jena error: " + e.toString()); log.info("!!!! Query invalid for q" + q.getId() + " - " + q.getLanguageToQuestion().get("en")); queryValid = false; } else { if (q.getGoldenAnswers().isEmpty()) { log.debug("Query delivers no results for q" + q.getId() + " (expecting: empty) - " + q.getLanguageToQuestion().get("en")); queryValid = (queryValid && true); } else { if (q.getGoldenAnswers().contains("true") || q.getGoldenAnswers().contains("false")) { log.debug("Query delivers no results for q" + q.getId() + " (expecting: boolean) - " + q.getLanguageToQuestion().get("en")); queryValid = (queryValid && true); } log.info("Golden answer not returned! Expecting:" + q.getGoldenAnswers().toString()); queryValid = false; } } } finally { qef.close(); } return queryValid; }
Example 18
Source File: DatasetGenerator.java From NLIWOD with GNU Affero General Public License v3.0 | 4 votes |
private void evaluate(Set<String>answers,Query query,String question){ QueryExecution qe = qef.createQueryExecution(query); LOGGER.debug(query.toString()); LOGGER.debug("Question:"+ question); double truepositive=0; double falsepositive=0; try { ResultSet rs = qe.execSelect(); while (rs.hasNext()) { QuerySolution qs = rs.next(); RDFNode node = qs.get("s"); if (node != null && node.isResource()) { String resourceString = (node.asResource().toString().replace(NAMESPACE, "")); resourceString = resourceString.replace(NAMESPACE2, ""); if (answers.contains(resourceString)) { truepositive++; //LOGGER.debug("truepositive: " + resourceString); } else { falsepositive++; //LOGGER.debug("falsepositive: " + resourceString); } } } }catch(Exception e){ LOGGER.error("Executing SPARQL Query"+query.toString()+"failed"); } if(truepositive>0||falsepositive>0) { double falsenegative = answers.size() - truepositive; double recall = truepositive / (truepositive + falsepositive); double precision = truepositive / (truepositive + falsenegative); double accuracy = truepositive / (truepositive + falsenegative + falsepositive); double f1 = 2 * (precision * recall) / (precision + recall); if(f1==1.0) correct++; if(Double.isNaN(f1)) f1=0.0; f1sum+=f1; if(Double.isNaN(accuracy)) accuracy=0.0; accsum+=accuracy; LOGGER.debug("Evaluation: tp:" + truepositive + " fp:" + falsepositive + " fn:" + falsenegative + " recall:" + recall + " precision:" + precision + " f1:" + f1 + " accuracy:" + accuracy); evaluation.add(new String[]{question, truepositive + "", falsepositive + "" , falsenegative + "", recall + "", precision + "", f1 + "", accuracy + ""}); } else{ LOGGER.debug("No results for question: "+question); f1sum+=0.0; accsum+=0.0; evaluation.add(new String[]{question,"0.0","0.0","0.0","0.0","0.0","0.0","0.0"}); } }
Example 19
Source File: PatternQueryHandler.java From IGUANA with GNU Affero General Public License v3.0 | 4 votes |
protected ResultSet getInstanceVars(ParameterizedSparqlString pss, Set<String> varNames) { QueryExecution exec = QueryExecutionFactory.createServiceRequest(service, convertToSelect(pss,varNames)); //return result set return exec.execSelect(); }
Example 20
Source File: CombineManifest.java From incubator-taverna-language with Apache License 2.0 | 4 votes |
private static String nameForAgent(Resource agentResource) { logger.fine("Finding name of " + agentResource); String queryStr = sparqlPrefixes + "SELECT ?name WHERE { \n" + " { ?agent foaf:name ?name } \n" + " UNION \n" + " { ?agent vcard:fn ?name } \n" + " UNION \n" + " { ?agent vcard:FN ?name } \n" + // legacy " UNION \n" + " { ?agent rdfs:label ?name } \n" + " UNION \n" + " { \n" + " { ?agent vcard:n ?n } UNION { ?agent vcard:hasName ?n } \n" + " ?n vcard:family-name ?family ; \n" + " vcard:given-name ?given . \n" + " BIND(CONCAT(?given, \" \", ?family) AS ?name) \n" + " } \n" + " UNION \n" + " { " + " ?agent foaf:givenName ?given ; \n" + " foaf:familyName ?family \n" + " BIND(CONCAT(?given, \" \", ?family) AS ?name) \n" + " } \n" + " UNION \n" + " { " + " ?agent foaf:firstName ?given ; \n" + " foaf:surname ?family \n" + " BIND(CONCAT(?given, \" \", ?family) AS ?name) \n" + " } \n" + " } \n"; logger.finer(QueryFactory.create(queryStr).toString()); QueryExecution qexec = QueryExecutionFactory.create(queryStr, agentResource.getModel()); QuerySolutionMap binding = new QuerySolutionMap(); binding.add("agent", agentResource); qexec.setInitialBinding(binding); ResultSet select = qexec.execSelect(); if (select.hasNext()) { String name = select.next().getLiteral("name").getString(); logger.fine(name); return name; } logger.fine("(null)"); return null; }