Java Code Examples for org.openrdf.query.TupleQuery#evaluate()
The following examples show how to use
org.openrdf.query.TupleQuery#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: SemagrowSummariesGenerator.java From CostFed with GNU Affero General Public License v3.0 | 6 votes |
/** * Get total number of distinct objects for a predicate * @param pred Predicate * @param m model * @return triples */ public static long getDistinctSbj(String pred, String endpoint) throws Exception { String strQuery = "SELECT (COUNT(DISTINCT ?s) AS ?subjs) " + // "WHERE " + "{" + "?s <" + pred + "> ?o " + "} " ; SPARQLRepository repo = new SPARQLRepository(endpoint); repo.initialize(); RepositoryConnection conn = repo.getConnection(); try { TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, strQuery); TupleQueryResult rs = query.evaluate(); return Long.parseLong(rs.next().getValue("subjs").stringValue()); } finally { conn.close(); repo.shutDown(); } }
Example 2
Source File: TestTicket967.java From database with GNU General Public License v2.0 | 6 votes |
private void addDuringQueryExec(final RepositoryConnection conn, final Resource subj, final URI pred, final Value obj, final Resource... ctx) throws RepositoryException, MalformedQueryException, QueryEvaluationException { final TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, "select distinct ?s ?p ?o where{?s ?p ?t . ?t <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?o }" ); tq.setBinding("s", subj); tq.setBinding("p", pred); tq.setBinding("o", obj); final TupleQueryResult tqr = tq.evaluate(); try { if (!tqr.hasNext()) { conn.add(subj, pred, obj, ctx); } } finally { tqr.close(); } }
Example 3
Source File: SemagrowSummariesGenerator.java From CostFed with GNU Affero General Public License v3.0 | 6 votes |
/** * Get total number of distinct objects of a dataset * @return count */ public static long getObjectCount(String endpoint) throws Exception { String strQuery = "SELECT (COUNT(DISTINCT ?o) AS ?objts) " + // "WHERE " + "{" + "?s ?p ?o " + "} " ; SPARQLRepository repo = new SPARQLRepository(endpoint); repo.initialize(); RepositoryConnection conn = repo.getConnection(); try { TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, strQuery); TupleQueryResult rs = query.evaluate(); return Long.parseLong(rs.next().getValue("objts").stringValue()); } finally { conn.close(); repo.shutDown(); } }
Example 4
Source File: BigdataSailRemoteRepositoryConnectionTest.java From database with GNU General Public License v2.0 | 6 votes |
@Test public void testTupleQueryIncludeInferred() throws Exception { final TupleQuery tq = con.prepareTupleQuery(QueryLanguage.SPARQL, "select * where {?s ?p ?o}"); tq.setIncludeInferred(false); tq.evaluate(); assertEquals("false", remote.data.opts.getRequestParam(RemoteRepositoryDecls.INCLUDE_INFERRED)); assertEquals("false", remote.data.request.getParams().get(RemoteRepositoryDecls.INCLUDE_INFERRED).getValue()); tq.setIncludeInferred(true); final TupleQueryResult tqr = tq.evaluate(); try { assertEquals("true", remote.data.opts.getRequestParam(RemoteRepositoryDecls.INCLUDE_INFERRED)); assertEquals("true", remote.data.request.getParams().get(RemoteRepositoryDecls.INCLUDE_INFERRED).getValue()); } finally { tqr.close(); } }
Example 5
Source File: SemagrowSummariesGenerator.java From CostFed with GNU Affero General Public License v3.0 | 6 votes |
/** * Get Predicate List * @param endPointUrl SPARQL endPoint Url * @param graph Named graph * @return predLst Predicates List */ private static List<String> getPredicates(String endPointUrl, String graph) throws Exception { List<String> predLst = new ArrayList<String>(); String strQuery = getPredQuery(graph); SPARQLRepository repo = new SPARQLRepository(endPointUrl); repo.initialize(); RepositoryConnection conn = repo.getConnection(); try { TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, strQuery); TupleQueryResult res = query.evaluate(); while (res.hasNext()) { String pred = res.next().getValue("p").toString(); predLst.add(pred); } } finally { conn.close(); repo.shutDown(); } return predLst; }
Example 6
Source File: TestTicket4249.java From database with GNU General Public License v2.0 | 6 votes |
private void executeQuery(final RepositoryConnection conn, final Literal string, final int start, final int length, final Literal expected) throws RepositoryException, MalformedQueryException, QueryEvaluationException { final ValueFactory vf = conn.getValueFactory(); final String query = "select ?substring WHERE { BIND ( SUBSTR(?string, ?start, ?length) as ?substring ) . }"; final TupleQuery q = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); q.setBinding("string", string); q.setBinding("start", vf.createLiteral(start)); q.setBinding("length", vf.createLiteral(length)); final TupleQueryResult tqr = q.evaluate(); try { while (tqr.hasNext()) { final BindingSet bindings = tqr.next(); // assert expected value assertEquals(expected, bindings.getBinding("substring").getValue()); } } finally { tqr.close(); } }
Example 7
Source File: ComplexSPARQLQueryTest.java From database with GNU General Public License v2.0 | 5 votes |
@Test /** * @see http://www.openrdf.org/issues/browse/SES-1091 * @throws Exception */ public void testArbitraryLengthPathWithFilter3() throws Exception { loadTestData("/testdata-query/alp-testdata.ttl"); StringBuilder query = new StringBuilder(); query.append(getNamespaceDeclarations()); query.append("SELECT ?parent ?child "); query.append("WHERE { ?child rdfs:subClassOf+ ?parent . FILTER (?child = <http://example.org/C>) }"); TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query.toString()); try { TupleQueryResult result = tq.evaluate(); assertNotNull(result); int count = 0; while (result.hasNext()) { count++; BindingSet bs = result.next(); assertTrue(bs.hasBinding("child")); assertTrue(bs.hasBinding("parent")); } assertEquals(2, count); } catch (QueryEvaluationException e) { e.printStackTrace(); fail(e.getMessage()); } }
Example 8
Source File: TestTicket355.java From database with GNU General Public License v2.0 | 5 votes |
private void executeQuery(final SailRepository repo) throws RepositoryException, MalformedQueryException, QueryEvaluationException, RDFParseException, IOException, RDFHandlerException { try { repo.initialize(); final RepositoryConnection conn = repo.getConnection(); conn.setAutoCommit(false); try { final ValueFactory vf = conn.getValueFactory(); conn.add(vf.createURI("os:subject"), vf.createURI("os:prop"), vf.createLiteral("value")); conn.commit(); String query = "SELECT ?subj WHERE { " + "?subj <os:prop> ?val . " + "FILTER(STR(?val) != ?arg)}"; TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); tq.setBinding("arg", vf.createLiteral("notValue")); TupleQueryResult tqr = tq.evaluate(); assertTrue(tqr.hasNext()); tqr.close(); } finally { conn.close(); } } finally { repo.shutDown(); } }
Example 9
Source File: ComplexSPARQLQueryTest.java From database with GNU General Public License v2.0 | 5 votes |
@Test public void testValuesInOptional() throws Exception { loadTestData("/testdata-query/dataset-ses1692.trig"); StringBuilder query = new StringBuilder(); query.append(" PREFIX : <http://example.org/>\n"); query.append(" SELECT DISTINCT ?a ?name ?isX WHERE { ?b :p1 ?a . ?a :name ?name. OPTIONAL { ?a a :X . VALUES(?isX) { (:X) } } } "); TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query.toString()); TupleQueryResult result = tq.evaluate(); assertNotNull(result); assertTrue(result.hasNext()); int count = 0; while (result.hasNext()) { count++; BindingSet bs = result.next(); System.out.println(bs); URI a = (URI)bs.getValue("a"); assertNotNull(a); Value isX = bs.getValue("isX"); Literal name = (Literal)bs.getValue("name"); assertNotNull(name); if (a.stringValue().endsWith("a1")) { assertNotNull(isX); } else if (a.stringValue().endsWith(("a2"))) { assertNull(isX); } } assertEquals(2, count); }
Example 10
Source File: ObjectQueryTest.java From anno4j with Apache License 2.0 | 5 votes |
public void testTupleQueryBinding() throws Exception { Person jamie = con.addDesignation(con.getObjectFactory().createObject(), Person.class); jamie.getFoafNames().add("Jamie"); jamie.getFoafFamily_names().add("Leigh"); String q = PREFIX + "Select ?name where { ?person foaf:name ?name }"; TupleQuery query = con.prepareTupleQuery(q); query.setBinding("person", ((RDFObject)jamie).getResource()); TupleQueryResult result = query.evaluate(); assertTrue(result.hasNext()); assertEquals("Jamie", result.next().getValue("name").stringValue()); result.close(); }
Example 11
Source File: QueryEvaluation.java From CostFed with GNU Affero General Public License v3.0 | 5 votes |
public List<List<Object>> evaluate(String queries) throws Exception { List<List<Object>> report = new ArrayList<List<Object>>(); List<String> qnames = Arrays.asList(queries.split(" ")); for (String curQueryName : qnames) { List<Object> reportRow = new ArrayList<Object>(); report.add(reportRow); String curQuery = qp.getQuery(curQueryName); reportRow.add(curQueryName); long startTime = System.currentTimeMillis(); //ParsedOperation pO = QueryParserUtil.parseOperation(QueryLanguage.SPARQL, curQuery, null); RepositoryConnection repCon = this.repository.getConnection(); try { Query tempq = repCon.prepareQuery(QueryLanguage.SPARQL, curQuery); TupleQuery q = (TupleQuery)tempq; SyncTupleQueryResultHandler rhandler = new SyncTupleQueryResultHandler(); q.evaluate(rhandler); long runTime = System.currentTimeMillis() - startTime; reportRow.add((Long)rhandler.resultCount); reportRow.add((Long)runTime); log.info(curQueryName + ": Query exection time (msec): "+ runTime + ", Total Number of Records: " + rhandler.resultCount); } catch (Exception e) { reportRow.add(null); reportRow.add(null); } finally { repCon.close(); } } return report; }
Example 12
Source File: ComplexSPARQLQueryTest.java From database with GNU General Public License v2.0 | 5 votes |
@Test public void testPropertyPathInTree() throws Exception { loadTestData("/testdata-query/dataset-query.trig"); StringBuilder query = new StringBuilder(); query.append(getNamespaceDeclarations()); query.append(" SELECT ?node ?name "); query.append(" FROM ex:tree-graph "); query.append(" WHERE { ?node ex:hasParent+ ex:b . ?node ex:name ?name . }"); TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query.toString()); try { TupleQueryResult result = tq.evaluate(); assertNotNull(result); while (result.hasNext()) { BindingSet bs = result.next(); assertNotNull(bs); System.out.println(bs); } result.close(); } catch (QueryEvaluationException e) { e.printStackTrace(); fail(e.getMessage()); } }
Example 13
Source File: ComplexSPARQLQueryTest.java From database with GNU General Public License v2.0 | 4 votes |
@Test public void testSameTermRepeatInOptional() throws Exception { loadTestData("/testdata-query/dataset-query.trig"); StringBuilder query = new StringBuilder(); query.append(getNamespaceDeclarations()); query.append(" SELECT ?l ?opt1 ?opt2 "); query.append(" FROM ex:optional-sameterm-graph "); query.append(" WHERE { "); query.append(" ?s ex:p ex:A ; "); query.append(" { "); query.append(" { "); query.append(" ?s ?p ?l ."); query.append(" FILTER(?p = rdfs:label) "); query.append(" } "); query.append(" OPTIONAL { "); query.append(" ?s ?p ?opt1 . "); query.append(" FILTER (?p = ex:prop1) "); query.append(" } "); query.append(" OPTIONAL { "); query.append(" ?s ?p ?opt2 . "); query.append(" FILTER (?p = ex:prop2) "); query.append(" } "); query.append(" }"); query.append(" } "); TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query.toString()); try { TupleQueryResult result = tq.evaluate(); assertNotNull(result); int count = 0; while (result.hasNext()) { BindingSet bs = result.next(); count++; assertNotNull(bs); System.out.println(bs); Value l = bs.getValue("l"); assertTrue(l instanceof Literal); assertEquals("label", ((Literal)l).getLabel()); Value opt1 = bs.getValue("opt1"); assertNull(opt1); Value opt2 = bs.getValue("opt2"); assertNull(opt2); } result.close(); assertEquals(1, count); } catch (QueryEvaluationException e) { e.printStackTrace(); fail(e.getMessage()); } }
Example 14
Source File: TestBOps.java From database with GNU General Public License v2.0 | 4 votes |
public void testConcat() throws Exception { final BigdataSail sail = getSail(); try { sail.initialize(); final BigdataSailRepository repo = new BigdataSailRepository(sail); final BigdataSailRepositoryConnection cxn = (BigdataSailRepositoryConnection) repo.getConnection(); cxn.setAutoCommit(false); try { final String ns = BD.NAMESPACE; final URI foo = new URIImpl(ns+"foo"); final URI bar = new URIImpl(ns+"bar"); final URI plain = new URIImpl(ns+"plain"); final URI language = new URIImpl(ns+"language"); final URI string = new URIImpl(ns+"string"); final Literal fooPlain = new LiteralImpl("foo"); final Literal fooLanguage = new LiteralImpl("foo", "en"); final Literal fooString = new LiteralImpl("foo", XMLSchema.STRING); final Literal barPlain = new LiteralImpl("bar"); final Literal barLanguage = new LiteralImpl("bar", "en"); final Literal barString = new LiteralImpl("bar", XMLSchema.STRING); final Literal foobarPlain = new LiteralImpl("foobar"); final Literal foobarLanguage = new LiteralImpl("foobar", "en"); final Literal foobarString = new LiteralImpl("foobar", XMLSchema.STRING); /**/ cxn.setNamespace("ns", ns); cxn.add(foo, plain, fooPlain); cxn.add(bar, plain, barPlain); cxn.add(foo, language, fooLanguage); cxn.add(bar, language, barLanguage); cxn.add(foo, string, fooString); cxn.add(bar, string, barString); cxn.add(plain, plain, foobarPlain); cxn.add(language, language, foobarLanguage); cxn.add(string, string, foobarString); cxn.add(plain, string, foobarPlain); cxn.add(language, plain, foobarPlain); cxn.add(language, string, foobarPlain); /* * Note: The either flush() or commit() is required to flush the * statement buffers to the database before executing any operations * that go around the sail. */ cxn.flush();//commit(); cxn.commit();// if (log.isInfoEnabled()) { log.info("\n" + cxn.getTripleStore().dumpStore()); } { String query = "select ?o1 ?o2 ?o3 " + "WHERE { " + " ?s1 ?p1 ?o1 . " + " ?s2 ?p2 ?o2 . " + " ?p1 ?p2 ?o3 . " + " FILTER(concat(?o1, ?o2) = ?o3)"+ "}"; final TupleQuery tupleQuery = cxn.prepareTupleQuery(QueryLanguage.SPARQL, query); final TupleQueryResult result = tupleQuery.evaluate(); int cnt = 0; try { while(result.hasNext()) { cnt++; } } finally { result.close(); } assertEquals(6, cnt); } } finally { cxn.close(); } } finally { sail.__tearDownUnitTest(); } }
Example 15
Source File: TestBOps.java From database with GNU General Public License v2.0 | 4 votes |
public void testOrEquals() throws Exception { final BigdataSail sail = getSail(); try { sail.initialize(); final BigdataSailRepository repo = new BigdataSailRepository(sail); final BigdataSailRepositoryConnection cxn = (BigdataSailRepositoryConnection) repo.getConnection(); cxn.setAutoCommit(false); try { // final ValueFactory vf = sail.getValueFactory(); // // final LexiconRelation lex = sail.getDatabase().getLexiconRelation(); final String ns = BD.NAMESPACE; final URI mike = new URIImpl(ns+"Mike"); final URI bryan = new URIImpl(ns+"Bryan"); final URI martyn = new URIImpl(ns+"Martyn"); final URI person = new URIImpl(ns+"Person"); final URI p = new URIImpl(ns+"p"); final Literal l1 = new LiteralImpl("Mike"); final Literal l2 = new LiteralImpl("Bryan"); final Literal l3 = new LiteralImpl("Martyn"); /**/ cxn.setNamespace("ns", ns); cxn.add(mike, RDF.TYPE, person); cxn.add(mike, RDFS.LABEL, l1); cxn.add(bryan, RDF.TYPE, person); cxn.add(bryan, RDFS.COMMENT, l2); cxn.add(martyn, RDF.TYPE, person); cxn.add(martyn, p, l3); /* * Note: The either flush() or commit() is required to flush the * statement buffers to the database before executing any operations * that go around the sail. */ cxn.flush();//commit(); cxn.commit();// if (log.isInfoEnabled()) { log.info("\n" + cxn.getTripleStore().dumpStore()); } { String query = "PREFIX rdf: <"+RDF.NAMESPACE+"> " + "PREFIX rdfs: <"+RDFS.NAMESPACE+"> " + "PREFIX ns: <"+ns+"> " + "select * " + "WHERE { " + " ?s rdf:type ns:Person . " + " ?s ?p ?label . " + " FILTER ( ?p = rdfs:label || ?p = rdfs:comment ) . " + "}"; final TupleQuery tupleQuery = cxn.prepareTupleQuery(QueryLanguage.SPARQL, query); final TupleQueryResult result = tupleQuery.evaluate(); // while (result.hasNext()) { // System.err.println(result.next()); // } final Collection<BindingSet> solution = new LinkedList<BindingSet>(); solution.add(createBindingSet(new Binding[] { new BindingImpl("s", mike), new BindingImpl("p", RDFS.LABEL), new BindingImpl("label", l1) })); solution.add(createBindingSet(new Binding[] { new BindingImpl("s", bryan), new BindingImpl("p", RDFS.COMMENT), new BindingImpl("label", l2) })); compare(result, solution); } } finally { cxn.close(); } } finally { sail.__tearDownUnitTest(); } }
Example 16
Source File: TestTicket1785.java From database with GNU General Public License v2.0 | 4 votes |
private void executeQuery(final BigdataSailRepository repo) throws RepositoryException, MalformedQueryException, QueryEvaluationException, RDFParseException, IOException { try { repo.initialize(); final BigdataSailRepositoryConnection conn = repo.getConnection(); conn.setAutoCommit(false); try { conn.add(getClass().getResourceAsStream("TestTicket1785.n3"), "", RDFFormat.TURTLE); conn.commit(); final String query = "PREFIX wd: <http://my.test.namespace/A#> \r\n" + "PREFIX wdt: <http://my.test.namespace/B#> \r\n" + "\r\n" + "SELECT ?country\r\n" + "WHERE\r\n" + "{\r\n" + " FILTER(?country NOT IN (wd:Q148,wd:Q30) || false) \r\n" + " wd:Q513 wdt:P17 ?country .\r\n" + "}"; final TupleQuery q = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); final TupleQueryResult tqr = q.evaluate(); int cnt = 0; while (tqr.hasNext()) { BindingSet bindings = tqr.next(); cnt++; if(log.isInfoEnabled()) log.info("bindings="+bindings); } tqr.close(); assertEquals(1, cnt); } finally { conn.close(); } } finally { repo.shutDown(); } }
Example 17
Source File: TestOrderBy.java From database with GNU General Public License v2.0 | 4 votes |
public void testOrderBy() throws Exception { final BigdataSail sail = getSail(); sail.initialize(); final BigdataSailRepository repo = new BigdataSailRepository(sail); final BigdataSailRepositoryConnection cxn = (BigdataSailRepositoryConnection) repo.getConnection(); cxn.setAutoCommit(false); try { final ValueFactory vf = sail.getValueFactory(); // This fails with BigData trunk of 21-07-2010 final URI s1 = vf.createURI("s:1"); final URI s2 = vf.createURI("s:2"); final URI s3 = vf.createURI("s:3"); final URI pred1 = vf.createURI("p:1"); final URI pred2 = vf.createURI("p:2"); cxn.add(s1, pred1, vf.createLiteral(3)); cxn.add(s1, pred2, vf.createLiteral("a")); cxn.add(s2, pred1, vf.createLiteral(1)); cxn.add(s2, pred2, vf.createLiteral("b")); cxn.add(s3, pred1, vf.createLiteral(2)); cxn.add(s3, pred2, vf.createLiteral("c")); final TupleQuery tq = cxn.prepareTupleQuery(QueryLanguage.SPARQL, "SELECT ?s ?lit " + "WHERE { " + " ?s <p:1> ?val. " + " ?s <p:2> ?lit " + "} " + "ORDER BY ?val" ); final TupleQueryResult result = tq.evaluate(); try { assertTrue(result.hasNext()); assertEquals(s2, result.next().getValue("s")); assertTrue(result.hasNext()); assertEquals(s3, result.next().getValue("s")); assertTrue(result.hasNext()); assertEquals(s1, result.next().getValue("s")); assertFalse(result.hasNext()); } finally { result.close(); } } finally { cxn.close(); sail.__tearDownUnitTest(); } }
Example 18
Source File: RangeQueriesTest.java From cumulusrdf with Apache License 2.0 | 4 votes |
/** * Compares range results obtained from SPARQL and Range query. * * @throws Exception never, otherwise the test fails. */ @Test public void rangeResults() throws Exception { final String sparql_query = String.format( "SELECT * WHERE { ?s <%s> ?o . FILTER(?o >= %s && ?o <= %s ) } ORDER BY ASC(?o)", _predicate, _lowerBound, _upperBound); final TupleQuery q = _repositoryConnection.prepareTupleQuery(QueryLanguage.SPARQL, sparql_query); final TupleQueryResult sparqlResults = q.evaluate(); assertTrue(sparqlResults != null && sparqlResults.hasNext()); final Value[] query = { null, buildResource(_predicate) }; final Iterator<Statement> rangeResultIterator = _tripleStore.range( query, buildLiteral(String.valueOf(_lowerBound)), true, buildLiteral(String.valueOf(_upperBound)), true, false, Integer.MAX_VALUE); assertTrue(rangeResultIterator != null && rangeResultIterator.hasNext()); final List<Statement> rangeResult = asList(rangeResultIterator); int howManyBindings = 0; int howManyTriples = rangeResult.size(); while (sparqlResults.hasNext()) { howManyBindings++; final BindingSet sparqlBindings = sparqlResults.next(); final Literal objectFromSparqlQuery = (Literal) sparqlBindings.getValue("o"); for (Iterator<Statement> iterator = rangeResult.iterator(); iterator.hasNext();) { final Statement rangeResultTriple = iterator.next(); final Literal objectFromRangeQuery = (Literal) rangeResultTriple.getObject(); final BigDecimal valueFromRangeQuery = ((TripleStore) _tripleStore).asDecimal(objectFromRangeQuery, null); assertNotNull("Literal object cannot be null for this kind of (range) query result.", valueFromRangeQuery); final BigDecimal valueFromSparqlQuery = ((TripleStore) _tripleStore).asDecimal(objectFromSparqlQuery, null); assertNotNull("Literal object cannot be null for this kind of (SPARQL) query result.", valueFromSparqlQuery); if (isTheSameValue(valueFromRangeQuery.doubleValue(), valueFromSparqlQuery.doubleValue(), 1 / 10 ^ 6)) { iterator.remove(); } } } assertTrue( "SPARQL returned " + howManyBindings + " bindings, RangeQuery returned " + howManyTriples + ", remaining triples : " + rangeResult, rangeResult.isEmpty()); }
Example 19
Source File: TestBOpUtility.java From database with GNU General Public License v2.0 | 4 votes |
public void testOpenWorldEq() throws Exception { final Sail sail = new MemoryStore(); final Repository repo = new SailRepository(sail); repo.initialize(); final RepositoryConnection cxn = repo.getConnection(); try { final ValueFactory vf = sail.getValueFactory(); final URI mike = vf.createURI(BD.NAMESPACE + "mike"); final URI age = vf.createURI(BD.NAMESPACE + "age"); final Literal mikeAge = vf.createLiteral(34); cxn.add(vf.createStatement(mike, RDF.TYPE, RDFS.RESOURCE)); cxn.add(vf.createStatement(mike, age, mikeAge)); final String query = "select * " + "where { " + " ?s ?p ?o . " + " filter (?o < 40) " + "}"; final TupleQuery tupleQuery = cxn.prepareTupleQuery(QueryLanguage.SPARQL, query); final TupleQueryResult result = tupleQuery.evaluate(); while (result.hasNext()) { final BindingSet tmp = result.next(); if(log.isInfoEnabled()) log.info(tmp.toString()); } } finally { cxn.close(); repo.shutDown(); } }
Example 20
Source File: TestBOps.java From database with GNU General Public License v2.0 | 4 votes |
public void testSimpleConstraint() throws Exception { final BigdataSail sail = getSail(); try { sail.initialize(); final BigdataSailRepository repo = new BigdataSailRepository(sail); final BigdataSailRepositoryConnection cxn = (BigdataSailRepositoryConnection) repo.getConnection(); cxn.setAutoCommit(false); try { final ValueFactory vf = sail.getValueFactory(); final String ns = BD.NAMESPACE; final URI jill = new URIImpl(ns+"Jill"); final URI jane = new URIImpl(ns+"Jane"); final URI person = new URIImpl(ns+"Person"); final URI age = new URIImpl(ns+"age"); final URI IQ = new URIImpl(ns+"IQ"); final Literal l1 = new LiteralImpl("Jill"); final Literal l2 = new LiteralImpl("Jane"); final Literal age1 = vf.createLiteral(20); final Literal age2 = vf.createLiteral(30); final Literal IQ1 = vf.createLiteral(130); final Literal IQ2 = vf.createLiteral(140); /**/ cxn.setNamespace("ns", ns); cxn.add(jill, RDF.TYPE, person); cxn.add(jill, RDFS.LABEL, l1); cxn.add(jill, age, age1); cxn.add(jill, IQ, IQ1); cxn.add(jane, RDF.TYPE, person); cxn.add(jane, RDFS.LABEL, l2); cxn.add(jane, age, age2); cxn.add(jane, IQ, IQ2); /* * Note: The either flush() or commit() is required to flush the * statement buffers to the database before executing any operations * that go around the sail. */ cxn.flush();//commit(); cxn.commit();// if (log.isInfoEnabled()) { log.info("\n" + cxn.getTripleStore().dumpStore()); } { final String query = "PREFIX rdf: <"+RDF.NAMESPACE+"> " + "PREFIX rdfs: <"+RDFS.NAMESPACE+"> " + "PREFIX ns: <"+ns+"> " + "select * " + "WHERE { " + " ?s rdf:type ns:Person . " + " ?s ns:age ?age . " + " ?s ns:IQ ?iq . " + " ?s rdfs:label ?label . " + " FILTER( ?age < 25 && ?iq > 125 ) . " + "}"; final TupleQuery tupleQuery = cxn.prepareTupleQuery(QueryLanguage.SPARQL, query); final TupleQueryResult result = tupleQuery.evaluate(); // while (result.hasNext()) { // System.err.println(result.next()); // } final Collection<BindingSet> solution = new LinkedList<BindingSet>(); solution.add(createBindingSet(new Binding[] { new BindingImpl("s", jill), new BindingImpl("age", age1), new BindingImpl("iq", IQ1), new BindingImpl("label", l1) })); compare(result, solution); } } finally { cxn.close(); } } finally { sail.__tearDownUnitTest(); } }