Java Code Examples for org.eclipse.rdf4j.query.GraphQuery#evaluate()
The following examples show how to use
org.eclipse.rdf4j.query.GraphQuery#evaluate() .
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: ComplexSPARQLQueryTest.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Test public void testDescribeAWhere() throws Exception { loadTestData("/testdata-query/dataset-describe.trig"); StringBuilder query = new StringBuilder(); query.append(getNamespaceDeclarations()); query.append("DESCRIBE ?x WHERE {?x rdfs:label \"a\". } "); GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query.toString()); ValueFactory f = conn.getValueFactory(); IRI a = f.createIRI("http://example.org/a"); IRI p = f.createIRI("http://example.org/p"); try (GraphQueryResult evaluate = gq.evaluate();) { Model result = QueryResults.asModel(evaluate); Set<Value> objects = result.filter(a, p, null).objects(); assertNotNull(objects); for (Value object : objects) { if (object instanceof BNode) { assertTrue(result.contains((Resource) object, null, null)); assertEquals(2, result.filter((Resource) object, null, null).size()); } } } }
Example 2
Source File: RepositoryModel.java From semweb4j with BSD 2-Clause "Simplified" License | 6 votes |
@Override public ClosableIterable<Statement> queryConstruct(String query, String querylanguage) throws QueryLanguageNotSupportedException { assertModel(); if (querylanguage.equalsIgnoreCase("SPARQL")) return sparqlConstruct(query); else { QueryLanguage ql = QueryLanguage.valueOf(querylanguage); if (ql == null) { throw new QueryLanguageNotSupportedException("Unsupported query language: '" + querylanguage + "'"); } try { GraphQuery prepared = this.connection.prepareGraphQuery(ql, query); GraphQueryResult graphQueryResult = prepared.evaluate(); return new GraphIterable(graphQueryResult, this); } catch (MalformedQueryException | RepositoryException | UnsupportedQueryLanguageException | QueryEvaluationException e) { throw new ModelRuntimeException(e); } } }
Example 3
Source File: ComplexSPARQLQueryTest.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Test public void testDescribeB() throws Exception { loadTestData("/testdata-query/dataset-describe.trig"); StringBuilder query = new StringBuilder(); query.append(getNamespaceDeclarations()); query.append("DESCRIBE ex:b"); GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query.toString()); ValueFactory f = conn.getValueFactory(); IRI b = f.createIRI("http://example.org/b"); IRI p = f.createIRI("http://example.org/p"); try (GraphQueryResult evaluate = gq.evaluate();) { Model result = QueryResults.asModel(evaluate); Set<Resource> subjects = result.filter(null, p, b).subjects(); assertNotNull(subjects); for (Value subject : subjects) { if (subject instanceof BNode) { assertTrue(result.contains(null, null, subject)); } } } }
Example 4
Source File: RepositoryModel.java From semweb4j with BSD 2-Clause "Simplified" License | 5 votes |
@Override public ClosableIterable<Statement> sparqlConstruct(String query) throws ModelRuntimeException { assertModel(); try { GraphQuery prepared = this.connection.prepareGraphQuery(QueryLanguage.SPARQL, query); GraphQueryResult graphQueryResult = prepared.evaluate(); return new GraphIterable(graphQueryResult, this); } catch (MalformedQueryException | RepositoryException | UnsupportedQueryLanguageException | QueryEvaluationException e) { throw new ModelRuntimeException(e); } }
Example 5
Source File: SpinInferencing.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
public static int executeRule(Resource subj, Resource rule, QueryPreparer queryPreparer, SpinParser parser, InferencerConnection conn) throws OpenRDFException { int nofInferred; TripleSource tripleSource = queryPreparer.getTripleSource(); ParsedOperation parsedOp = parser.parse(rule, tripleSource); if (parsedOp instanceof ParsedGraphQuery) { ParsedGraphQuery graphQuery = (ParsedGraphQuery) parsedOp; GraphQuery queryOp = queryPreparer.prepare(graphQuery); addBindings(subj, rule, graphQuery, queryOp, tripleSource, parser); CountingRDFInferencerInserter handler = new CountingRDFInferencerInserter(conn, tripleSource.getValueFactory()); queryOp.evaluate(handler); nofInferred = handler.getStatementCount(); } else if (parsedOp instanceof ParsedUpdate) { ParsedUpdate graphUpdate = (ParsedUpdate) parsedOp; Update updateOp = queryPreparer.prepare(graphUpdate); addBindings(subj, rule, graphUpdate, updateOp, tripleSource, parser); UpdateCountListener listener = new UpdateCountListener(); conn.addConnectionListener(listener); updateOp.execute(); conn.removeConnectionListener(listener); // number of statement changes nofInferred = listener.getAddedStatementCount() + listener.getRemovedStatementCount(); } else { throw new MalformedSpinException("Invalid rule: " + rule); } return nofInferred; }
Example 6
Source File: BasicTests.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Test public void testSingleSource_SetBinding() throws Exception { /* test a single source select query where we set a binding */ prepareTest(Arrays.asList("/tests/basic/data01endpoint1.ttl", "/tests/basic/data01endpoint2.ttl")); try (RepositoryConnection conn = fedxRule.getRepository().getConnection()) { // SELECT query TupleQuery tq = conn .prepareTupleQuery("SELECT ?person WHERE { ?person <http://xmlns.com/foaf/0.1/name> ?name }"); tq.setBinding("name", l("Alan")); TupleQueryResult tqr = tq.evaluate(); List<BindingSet> res = Iterations.asList(tqr); assertContainsAll(res, "person", Sets.newHashSet(iri("http://example.org/", "a"))); // CONSTRUCT query GraphQuery gq = conn.prepareGraphQuery( "CONSTRUCT { ?person <http://xmlns.com/foaf/0.1/name> ?name } WHERE { ?person <http://xmlns.com/foaf/0.1/name> ?name }"); gq.setBinding("name", l("Alan")); GraphQueryResult gqr = gq.evaluate(); List<Statement> stmts = Iterations.asList(gqr); Assertions.assertEquals(1, stmts.size()); Assertions.assertEquals(iri("http://example.org/", "a"), stmts.get(0).getSubject()); // BOOLEAN query BooleanQuery bq = conn.prepareBooleanQuery("ASK { ?person <http://xmlns.com/foaf/0.1/name> ?name }"); bq.setBinding("name", l("non-existing-name")); Assertions.assertEquals(false, bq.evaluate()); } }
Example 7
Source File: RepositoryModel.java From semweb4j with BSD 2-Clause "Simplified" License | 5 votes |
@Override public ClosableIterable<Statement> sparqlDescribe(String query) throws ModelRuntimeException { assertModel(); try { GraphQuery prepared = this.connection.prepareGraphQuery(QueryLanguage.SPARQL, query); GraphQueryResult graphQueryResult = prepared.evaluate(); return new GraphIterable(graphQueryResult, this); } catch (MalformedQueryException | RepositoryException | UnsupportedQueryLanguageException | QueryEvaluationException e) { throw new ModelRuntimeException(e); } }
Example 8
Source File: LuceneSailExample.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
private static void graphQuery(String queryString, RepositoryConnection connection) throws RepositoryException, MalformedQueryException, QueryEvaluationException { System.out.println("Running query: \n" + queryString); GraphQuery query = connection.prepareGraphQuery(QueryLanguage.SPARQL, queryString); try (GraphQueryResult result = query.evaluate()) { // print the results while (result.hasNext()) { Statement stmt = result.next(); System.out.println("found match: " + stmt.getSubject().stringValue() + "\t" + stmt.getPredicate().stringValue() + "\t" + stmt.getObject().stringValue()); } } }
Example 9
Source File: TripleSourceBase.java From CostFed with GNU Affero General Public License v3.0 | 5 votes |
@Override public CloseableIteration<BindingSet, QueryEvaluationException> getStatements( String preparedQuery, RepositoryConnection conn, QueryType queryType) throws RepositoryException, MalformedQueryException, QueryEvaluationException { switch (queryType) { case SELECT: monitorRemoteRequest(); TupleQuery tQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, preparedQuery); disableInference(tQuery); return tQuery.evaluate(); case CONSTRUCT: monitorRemoteRequest(); GraphQuery gQuery = conn.prepareGraphQuery(QueryLanguage.SPARQL, preparedQuery); disableInference(gQuery); return new GraphToBindingSetConversionIteration(gQuery.evaluate()); case ASK: monitorRemoteRequest(); BooleanQuery bQuery = conn.prepareBooleanQuery(QueryLanguage.SPARQL, preparedQuery); disableInference(bQuery); return booleanToBindingSetIteration(bQuery.evaluate()); default: throw new UnsupportedOperationException( "Operation not supported for query type " + queryType); } }
Example 10
Source File: ComplexSPARQLQueryTest.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Test public void testDescribeF() throws Exception { loadTestData("/testdata-query/dataset-describe.trig"); StringBuilder query = new StringBuilder(); query.append(getNamespaceDeclarations()); query.append("DESCRIBE ex:f"); GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query.toString()); ValueFactory vf = conn.getValueFactory(); IRI f = vf.createIRI("http://example.org/f"); IRI p = vf.createIRI("http://example.org/p"); try (GraphQueryResult evaluate = gq.evaluate();) { Model result = QueryResults.asModel(evaluate); assertNotNull(result); assertEquals(4, result.size()); Set<Value> objects = result.filter(f, p, null).objects(); assertNotNull(objects); for (Value object : objects) { if (object instanceof BNode) { Set<Value> childObjects = result.filter((BNode) object, null, null).objects(); assertNotNull(childObjects); for (Value childObject : childObjects) { if (childObject instanceof BNode) { assertTrue(result.contains((BNode) childObject, null, null)); } } } } } }
Example 11
Source File: ComplexSPARQLQueryTest.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Test public void testDescribeD() throws Exception { loadTestData("/testdata-query/dataset-describe.trig"); StringBuilder query = new StringBuilder(); query.append(getNamespaceDeclarations()); query.append("DESCRIBE ex:d"); GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query.toString()); ValueFactory f = conn.getValueFactory(); IRI d = f.createIRI("http://example.org/d"); IRI p = f.createIRI("http://example.org/p"); IRI e = f.createIRI("http://example.org/e"); try (GraphQueryResult evaluate = gq.evaluate();) { Model result = QueryResults.asModel(evaluate); assertNotNull(result); assertTrue(result.contains(null, p, e)); assertFalse(result.contains(e, null, null)); Set<Value> objects = result.filter(d, p, null).objects(); assertNotNull(objects); for (Value object : objects) { if (object instanceof BNode) { Set<Value> childObjects = result.filter((BNode) object, null, null).objects(); assertNotNull(childObjects); for (Value childObject : childObjects) { if (childObject instanceof BNode) { assertTrue(result.contains((BNode) childObject, null, null)); } } } } } }
Example 12
Source File: ComplexSPARQLQueryTest.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Test public void testDescribeWhere() throws Exception { loadTestData("/testdata-query/dataset-describe.trig"); StringBuilder query = new StringBuilder(); query.append(getNamespaceDeclarations()); query.append("DESCRIBE ?x WHERE {?x rdfs:label ?y . } "); GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query.toString()); ValueFactory vf = conn.getValueFactory(); IRI a = vf.createIRI("http://example.org/a"); IRI b = vf.createIRI("http://example.org/b"); IRI c = vf.createIRI("http://example.org/c"); IRI e = vf.createIRI("http://example.org/e"); IRI f = vf.createIRI("http://example.org/f"); IRI p = vf.createIRI("http://example.org/p"); try (GraphQueryResult evaluate = gq.evaluate();) { Model result = QueryResults.asModel(evaluate); assertTrue(result.contains(a, p, null)); assertTrue(result.contains(b, RDFS.LABEL, null)); assertTrue(result.contains(c, RDFS.LABEL, null)); assertTrue(result.contains(null, p, b)); assertTrue(result.contains(e, RDFS.LABEL, null)); assertTrue(result.contains(null, p, e)); assertFalse(result.contains(f, null, null)); Set<Value> objects = result.filter(a, p, null).objects(); assertNotNull(objects); for (Value object : objects) { if (object instanceof BNode) { assertTrue(result.contains((Resource) object, null, null)); assertEquals(2, result.filter((Resource) object, null, null).size()); } } } }
Example 13
Source File: RepositoryModelSet.java From semweb4j with BSD 2-Clause "Simplified" License | 5 votes |
@Override public ClosableIterable<Statement> sparqlConstruct(String queryString) throws ModelRuntimeException { this.assertModel(); GraphQuery query; try { query = this.connection.prepareGraphQuery(QueryLanguage.SPARQL, queryString); GraphQueryResult graphQueryResult = query.evaluate(); return new StatementIterable(graphQueryResult, null); } catch(RDF4JException e) { throw new ModelRuntimeException(e); } }
Example 14
Source File: SailRepositoryConnectionTest.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Test public void testPrepareGraphQuery_not_bypassed() throws Exception { Optional<TupleExpr> response = Optional.empty(); when(sailConnection.prepareQuery(any(), eq(Query.QueryType.GRAPH), any(), any())).thenReturn(response); when(sailConnection.evaluate(any(), any(), any(), anyBoolean())).thenReturn(new EmptyIteration<>()); GraphQuery query = subject.prepareGraphQuery("CONSTRUCT WHERE { ?s ?p ?o }"); query.evaluate(); // check that evaluation is still called, and not with an empty TupleExpr verify(sailConnection).evaluate(any(TupleExpr.class), any(), any(), anyBoolean()); }
Example 15
Source File: ElasticsearchSailExample.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
private static void graphQuery(String queryString, RepositoryConnection connection) throws RepositoryException, MalformedQueryException, QueryEvaluationException { System.out.println("Running query: \n" + queryString); GraphQuery query = connection.prepareGraphQuery(QueryLanguage.SPARQL, queryString); try (GraphQueryResult result = query.evaluate()) { // print the results while (result.hasNext()) { Statement stmt = result.next(); System.out.println("found match: " + stmt.getSubject().stringValue() + "\t" + stmt.getPredicate().stringValue() + "\t" + stmt.getObject().stringValue()); } } }
Example 16
Source File: SPARQLConnection.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
private RepositoryResult<Statement> getStatementGeneral(Resource subj, IRI pred, Value obj, boolean includeInferred, Resource... contexts) throws RepositoryException, MalformedQueryException, QueryEvaluationException { GraphQueryResult gRes = null; RepositoryResult<Statement> result = null; boolean allGood = false; try { GraphQuery query = prepareGraphQuery(SPARQL, EVERYTHING, ""); query.setIncludeInferred(includeInferred); setBindings(query, subj, pred, obj, contexts); gRes = query.evaluate(); result = new RepositoryResult<>( new ExceptionConvertingIteration<Statement, RepositoryException>(gRes) { @Override protected RepositoryException convert(Exception e) { return new RepositoryException(e); } }); allGood = true; return result; } finally { if (!allGood) { try { if (result != null) { result.close(); } } finally { if (gRes != null) { gRes.close(); } } } } }
Example 17
Source File: LuceneSailTupleFunctionTest.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 4 votes |
/** * Reproduce #235 with following query: <code> * construct { * ?pred a <urn:ontology/Phrase> . * ?pred <urn:ontology/label> ?label . * ?pred <urn:ontology/score> ?score . * } where { * ?pred search:matches[ * search:query "ornare"; * search:score ?score * ] . * ?pred rdfs:label ?label . * } * </code> * * @throws Exception */ @Test public void test235Issue() throws Exception { StringBuilder buffer = new StringBuilder(); buffer.append(" construct {\n"); buffer.append(" ?pred a <urn:ontology/Phrase> .\n"); buffer.append(" ?pred <urn:ontology/label> ?label .\n"); buffer.append(" ?pred <urn:ontology/score> ?score . \n"); buffer.append(" } where {\n"); // buffer.append("select * where {\n"); buffer.append(" ?pred <" + MATCHES + "> [\n"); buffer.append(" <" + QUERY + "> \"ornare\";\n"); buffer.append(" <" + SCORE + "> ?score \n"); buffer.append(" ] .\n"); buffer.append(" ?pred rdfs:label ?label .\n"); buffer.append(" }"); log.info("Request query: \n{}\n", buffer.toString()); try { connection.begin(); GraphQuery query = connection.prepareGraphQuery(QueryLanguage.SPARQL, buffer.toString()); printGraphResult(query); try (GraphQueryResult res = query.evaluate()) { int cnt = countGraphResults(res); log.info("+++++ count triples: {}", cnt); Assert.assertTrue(String.format("count triples: {}", cnt), cnt == 3); } /* * TupleQuery query = connection.prepareTupleQuery(QueryLanguage.SPARQL, buffer.toString()); * ByteArrayOutputStream resultoutput = new ByteArrayOutputStream(); query.evaluate(new * SPARQLResultsCSVWriter(resultoutput)); log.info("tuple response: "); log.info(new * String(resultoutput.toByteArray())); */ /* * try (TupleQueryResult res = query.evaluate()) { int count = countTupleResults(res); log.info( * "count statements: {}", count); Assert.assertTrue(count == 2); } */ } catch (Exception e) { connection.rollback(); throw e; } finally { connection.commit(); } }
Example 18
Source File: RdfController.java From rya with Apache License 2.0 | 4 votes |
private void performGraphQuery(final String query, final RepositoryConnection conn, final String auth, final String infer, final String nullout, final RDFHandler handler) throws RepositoryException, MalformedQueryException, QueryEvaluationException, RDFHandlerException { final GraphQuery graphQuery = conn.prepareGraphQuery(QueryLanguage.SPARQL, query); if (auth != null && auth.length() > 0) { graphQuery.setBinding(RdfCloudTripleStoreConfiguration.CONF_QUERY_AUTH, VALUE_FACTORY.createLiteral(auth)); } if (infer != null && infer.length() > 0) { graphQuery.setBinding(RdfCloudTripleStoreConfiguration.CONF_INFER, VALUE_FACTORY.createLiteral(Boolean.parseBoolean(infer))); } if (nullout != null && nullout.length() > 0) { //output nothing, but still run query // TODO this seems like a strange use case. graphQuery.evaluate(new RDFHandler() { @Override public void startRDF() throws RDFHandlerException { } @Override public void endRDF() throws RDFHandlerException { } @Override public void handleNamespace(final String prefix, final String uri) throws RDFHandlerException { } @Override public void handleStatement(final Statement st) throws RDFHandlerException { } @Override public void handleComment(final String comment) throws RDFHandlerException { } }); } else { final long startTime = System.currentTimeMillis(); graphQuery.evaluate(handler); log.info(String.format("Query Time = %.3f\n", (System.currentTimeMillis() - startTime) / 1000.)); } }
Example 19
Source File: AbstractLuceneSailTest.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 4 votes |
@Test public void testGraphQuery() throws QueryEvaluationException, MalformedQueryException, RepositoryException { IRI score = vf.createIRI(LuceneSailSchema.NAMESPACE + "score"); StringBuilder query = new StringBuilder(); // here we would expect two links from SUBJECT3 to SUBJECT1 and SUBJECT2 // and one link from SUBJECT3 to its score query.append("CONSTRUCT DISTINCT \n"); query.append(" {r} <" + PREDICATE_3 + "> {r2} , \n"); query.append(" {r} <" + score + "> {s} \n"); query.append("FROM \n"); query.append(" {r} lucenesail:matches {match} lucenesail:query {\"four\"}; \n"); query.append(" lucenesail:score {s}, \n"); query.append(" {r} <" + PREDICATE_3.toString() + "> {r2} \n"); query.append("USING NAMESPACE\n"); query.append(" lucenesail = <" + LuceneSailSchema.NAMESPACE + "> \n"); int r = 0; int n = 0; try (RepositoryConnection connection = repository.getConnection()) { GraphQuery gq = connection.prepareGraphQuery(QueryLanguage.SERQL, query.toString()); try (GraphQueryResult result = gq.evaluate()) { while (result.hasNext()) { Statement statement = result.next(); n++; if (statement.getSubject().equals(SUBJECT_3) && statement.getPredicate().equals(PREDICATE_3) && statement.getObject().equals(SUBJECT_1)) { r |= 1; continue; } if (statement.getSubject().equals(SUBJECT_3) && statement.getPredicate().equals(PREDICATE_3) && statement.getObject().equals(SUBJECT_2)) { r |= 2; continue; } if (statement.getSubject().equals(SUBJECT_3) && statement.getPredicate().equals(score)) { r |= 4; continue; } } assertEquals(3, n); assertEquals(7, r); } } }
Example 20
Source File: AbstractLuceneSailSpinTest.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 4 votes |
public void printGraphResult(GraphQuery query) { ByteArrayOutputStream resultoutput = new ByteArrayOutputStream(); query.evaluate(new TurtleWriter(resultoutput)); log.info("graph result:"); log.info("\n=============\n" + new String(resultoutput.toByteArray()) + "\n============="); }