org.openrdf.query.BindingSet Java Examples
The following examples show how to use
org.openrdf.query.BindingSet.
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: DavidsTestBOps.java From database with GNU General Public License v2.0 | 6 votes |
public void testNamedGraphNoGraphKeyword2 () throws Exception { final BigdataSail sail = getTheSail () ; final ValueFactory vf = sail.getValueFactory(); final RepositoryConnection cxn = getRepositoryConnection ( sail ) ; try { String ns = "http://xyz.com/test#" ; String kb = String.format ( "<%ss> <%sp> <%so> .", ns, ns, ns ) ; String qs = String.format ( "select ?s from named <%sg1> from named <%sg2> where { ?s ?p ?o .}", ns, ns ) ; Resource graphs [] = new Resource [] { vf.createURI ( String.format ( "%sg1", ns ) ), vf.createURI ( String.format ( "%sg2", ns ) ) } ; Collection<BindingSet> expected = getExpected () ; run ( sail, cxn, kb, graphs, qs, expected ) ; } finally { cxn.close(); } }
Example #2
Source File: BlazeGraph.java From tinkerpop3 with GNU General Public License v2.0 | 6 votes |
/** * Binding set to vertex property (for Vertex elements). */ private final <V> Function<BindingSet, VertexProperty<V>> vertexProperty(final BlazeVertex v) { return bs -> { log.debug(() -> bs); final Literal val = (Literal) bs.getValue("val"); final BigdataBNode sid = (BigdataBNode) bs.getValue("vp"); final BigdataStatement stmt = sid.getStatement(); final URI key = stmt.getPredicate(); final String vpId = vertexPropertyId(stmt); final BlazeProperty<V> prop = new BlazeProperty<>(BlazeGraph.this, v, key, val); final BlazeVertexProperty<V> bvp = new BlazeVertexProperty<>(prop, vpId, sid); return bvp; }; }
Example #3
Source File: LoadPdb.java From database with GNU General Public License v2.0 | 6 votes |
public static void executeSelectQuery(Repository repo, String query) throws Exception { RepositoryConnection cxn = repo.getConnection(); int counter = 0; try { final TupleQuery tupleQuery = cxn.prepareTupleQuery(QueryLanguage.SPARQL, query); tupleQuery.setIncludeInferred(true /* includeInferred */); TupleQueryResult result = tupleQuery.evaluate(); // do something with the results while (result.hasNext()) { BindingSet bindingSet = result.next(); LOG.info(bindingSet); counter++; } } finally { // close the repository connection cxn.close(); // LOG.info System.err.println ("Number of results: " + counter); } }
Example #4
Source File: BlazeGraphEmbedded.java From tinkerpop3 with GNU General Public License v2.0 | 6 votes |
/** * {@inheritDoc} * * Logs the query at INFO and logs the optimized AST at TRACE. */ @Override protected Stream<BindingSet> _select( final String queryStr, final String extQueryId) { logQuery(queryStr); return Code.wrapThrow(() -> { final BigdataSailTupleQuery query = (BigdataSailTupleQuery) cxn().prepareTupleQuery(QueryLanguage.SPARQL, queryStr); setMaxQueryTime(query); final UUID queryId = setupQuery(query.getASTContainer(), QueryType.SELECT, extQueryId); sparqlLog.trace(() -> "optimized AST:\n"+query.optimize()); /* * Result is closed automatically by GraphStreamer. */ final TupleQueryResult result = query.evaluate(); final Optional<Runnable> onClose = Optional.of(() -> finalizeQuery(queryId)); return new GraphStreamer<>(result, onClose).stream(); }); }
Example #5
Source File: GPO.java From database with GNU General Public License v2.0 | 6 votes |
@Override public Map<URI, Long> getReverseLinkProperties() { materialize(); final Map<URI, Long> ret = new HashMap<URI, Long>(); final String query = "SELECT ?p (COUNT(?o) AS ?count)\n" + "WHERE { ?o ?p <" + getId().toString() + "> }\n" + "GROUP BY ?p"; final ICloseableIterator<BindingSet> res = m_om.evaluate(query); while (res.hasNext()) { final BindingSet bs = res.next(); final URI pred = (URI) bs.getBinding("p").getValue(); final Long count = ((Literal) bs.getBinding("count") .getValue()).longValue(); ret.put(pred, count); } return ret; }
Example #6
Source File: Concurrency.java From database with GNU General Public License v2.0 | 6 votes |
/** * Issue the query. * * @throws Exception */ private void doQuery() throws Exception { RepositoryConnection cxn = repo.getReadOnlyConnection(); try { final TupleQuery tupleQuery = cxn.prepareTupleQuery(QueryLanguage.SPARQL, query); tupleQuery.setIncludeInferred(true /* includeInferred */); TupleQueryResult result = tupleQuery.evaluate(); // do something with the results int resultCount = 0; while (result.hasNext()) { BindingSet bindingSet = result.next(); // log.info(bindingSet); resultCount++; } log.info(resultCount + " results"); } finally { // close the repository connection cxn.close(); } }
Example #7
Source File: SparqlEvaluator.java From anno4j with Apache License 2.0 | 6 votes |
public <T> Set<T> asSet(Class<T> of) throws OpenRDFException { if (of == null || Object.class.equals(of)) return asSet(); if (BindingSet.class.equals(of)) { TupleQueryResult result = asTupleQueryResult(); try { List<BindingSet> list = new ArrayList<BindingSet>(); while (result.hasNext()) { list.add(result.next()); } return (Set<T>) list; } finally { result.close(); } } if (Value.class.isAssignableFrom(of)) return (Set<T>) asSetOfValues(); if (Statement.class.equals(of)) return (Set<T>) asModel(); return asResult(of).asSet(); }
Example #8
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 Literal expected) throws RepositoryException, MalformedQueryException, QueryEvaluationException { final ValueFactory vf = conn.getValueFactory(); final String query = "select ?substring WHERE { BIND ( SUBSTR(?string, ?start) as ?substring ) . }"; final TupleQuery q = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); q.setBinding("string", string); q.setBinding("start", vf.createLiteral(start)); 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 #9
Source File: CachedPropertySet.java From anno4j with Apache License 2.0 | 6 votes |
@Override protected synchronized CloseableIteration<?, ?> getObjects() throws RepositoryException, QueryEvaluationException { if (creator == null || factory == null) { return super.getObjects(); } else if (binding == null) { ObjectQuery query = factory.createQuery(creator); if (query == null) return super.getObjects(); try { query.setBinding("self", getResource()); return query.evaluate(creator.getPropertyType()); } finally { factory.returnQuery(creator, query); } } else { CloseableIteratorIteration<BindingSet, QueryEvaluationException> result; result = new CloseableIteratorIteration<BindingSet, QueryEvaluationException>( bindings.iterator()); return new ObjectCursor(getObjectConnection(), result, binding); } }
Example #10
Source File: TestRemoteSparql11QueryBuilder.java From database with GNU General Public License v2.0 | 5 votes |
/** * Return the {@link IRemoteSparqlQueryBuilder} under test. * @param serviceNode * @param a * @return */ protected IRemoteSparqlQueryBuilder newFixture( final ServiceNode serviceNode, final BindingSet[] a) { // final RemoteServiceOptions options = new RemoteServiceOptions(); // // options.setSparql11(true); return new RemoteSparql11QueryBuilder(serviceNode); }
Example #11
Source File: OpenrdfNativeMockServiceFactory.java From database with GNU General Public License v2.0 | 5 votes |
@Override public ICloseableIterator<BindingSet> call( final BindingSet[] bindingSets) { TestOpenrdfNativeServiceEvaluation.assertNotNull(bindingSets); // System.err.println("ServiceCall: in="+Arrays.toString(bindingSets)); // // System.err.println("ServiceCall: out="+serviceSolutions); return new CloseableIteratorWrapper<BindingSet>( serviceSolutions.iterator()); }
Example #12
Source File: MutableTupleQueryResult.java From database with GNU General Public License v2.0 | 5 votes |
public <E extends Exception> MutableTupleQueryResult(Collection<String> bindingNames, Iteration<? extends BindingSet, E> bindingSetIter) throws E { this.bindingNames.addAll(bindingNames); Iterations.addAll(bindingSetIter, this.bindingSets); }
Example #13
Source File: TestRemoteSparql10QueryBuilder.java From database with GNU General Public License v2.0 | 5 votes |
/** * Return the {@link IRemoteSparqlQueryBuilder} under test. */ protected IRemoteSparqlQueryBuilder newFixture( final ServiceNode serviceNode, final BindingSet[] a) { // final RemoteServiceOptions options = new RemoteServiceOptions(); // // options.setSparql11(false); return new RemoteSparql10QueryBuilder( serviceNode); }
Example #14
Source File: TestOpenrdfNativeServiceEvaluation.java From database with GNU General Public License v2.0 | 5 votes |
/** * A simple SERVICE query. The service adds in a single solution which * restricts the set of solutions for the overall query. * * <pre> * PREFIX dc: <http://purl.org/dc/elements/1.1/> * PREFIX : <http://example.org/book/> * PREFIX ns: <http://example.org/ns#> * * SELECT ?book ?title ?price * { * SERVICE <http://www.bigdata.com/mockService/test_service_001> { * ?book :foo :bar * }. * ?book dc:title ?title ; * ns:price ?price . * } * </pre> */ public void test_service_001() throws Exception { final List<BindingSet> serviceSolutions = new LinkedList<BindingSet>(); { final MapBindingSet bset = new MapBindingSet(); bset.addBinding("book", new URIImpl("http://example.org/book/book1")); serviceSolutions.add(bset); } final URI serviceURI = new URIImpl( "http://www.bigdata.com/mockService/" + getName()); ServiceRegistry.getInstance().add(serviceURI, new OpenrdfNativeMockServiceFactory(serviceSolutions)); try { new TestHelper(// "sparql11-service-001", // testURI "sparql11-service-001.rq",// queryFileURL "sparql11-service-001.ttl",// dataFileURL "sparql11-service-001.srx"// resultFileURL ).runTest(); } finally { ServiceRegistry.getInstance().remove(serviceURI); } }
Example #15
Source File: SPARQLInferenceTest.java From neo4j-sparql-extension with GNU General Public License v3.0 | 5 votes |
public QueryResult( Multiset<BindingSet> expected, Multiset<BindingSet> actual, Multiset<BindingSet> noninf) { this.expect = expected; this.actual = actual; this.noninf = noninf; }
Example #16
Source File: AST2BOpUpdate.java From database with GNU General Public License v2.0 | 5 votes |
/** * Efficiently resolve openrdf {@link BindingSet} into a chunked bigdata * {@link IBindingSet}[] iterator. The closeable semantics of the iteration * pattern are preserved. * * @param r * The {@link LexiconRelation}. * @param chunkSize * When converting the openrdf binding set iteration pattern into * a chunked iterator pattern, this will be the target chunk * size. * @param result * The openrdf solutions. * @return An iterator visiting chunked bigdata solutions. * * TODO We should not have to do this. We should stay within native * bigdata IBindingSet[]s and the native bigdata iterators */ private static ICloseableIterator<IBindingSet[]> asBigdataIterator( final LexiconRelation r, final int chunkSize, final CloseableIteration<BindingSet, QueryEvaluationException> result) { // Wrap with streaming iterator pattern. final Striterator sitr = new Striterator( // Chunk up the openrdf solutions. new Chunkerator<BindingSet>( // Convert the Sesame iteration into a Bigdata iterator. new Sesame2BigdataIterator<BindingSet, QueryEvaluationException>( result), chunkSize)); // Add filter to batch resolve BindingSet[] => IBindingSet[]. sitr.addFilter(new Resolver() { private static final long serialVersionUID = 1L; @Override protected Object resolve(Object obj) { // Visiting openrdf BindingSet[] chunks. final BindingSet[] in = (BindingSet[]) obj; // Batch resolve to IBindingSet[]. final IBindingSet[] out = BigdataOpenRDFBindingSetsResolverator .resolveChunk(r, in); // Return Bigdata IBindingSet[]. return out; } }); return sitr; }
Example #17
Source File: RepositoryConnectionTest.java From database with GNU General Public License v2.0 | 5 votes |
@Test public void testPreparedTupleQuery2() throws Exception { testCon.add(alice, name, nameAlice, context2); testCon.add(alice, mbox, mboxAlice, context2); testCon.add(context2, publisher, nameAlice); testCon.add(bob, name, nameBob, context1); testCon.add(bob, mbox, mboxBob, context1); testCon.add(context1, publisher, nameBob); StringBuilder queryBuilder = new StringBuilder(); queryBuilder.append(" prefix foaf: <" + FOAF_NS + ">"); queryBuilder.append(" SELECT ?name ?mbox"); queryBuilder.append(" where { ?VAR foaf:name ?name . ?VAR foaf:mbox ?mbox . }"); TupleQuery query = testCon.prepareTupleQuery(QueryLanguage.SPARQL, queryBuilder.toString()); query.setBinding("VAR", bob); TupleQueryResult result = query.evaluate(); try { assertThat(result, is(notNullValue())); assertThat(result.hasNext(), is(equalTo(true))); while (result.hasNext()) { BindingSet solution = result.next(); assertThat(solution.hasBinding(NAME), is(equalTo(true))); assertThat(solution.hasBinding(MBOX), is(equalTo(true))); Value nameResult = solution.getValue(NAME); Value mboxResult = solution.getValue(MBOX); assertEquals("unexpected value for name: " + nameResult, nameBob, nameResult); assertEquals("unexpected value for mbox: " + mboxResult, mboxBob, mboxResult); } } finally { result.close(); } }
Example #18
Source File: BlazeGraph.java From tinkerpop3 with GNU General Public License v2.0 | 5 votes |
/** * Search query result to property. */ private final <V> Function<BindingSet, Property<V>> search() { return bs -> { log.debug(() -> bs); final Property<V> prop; if (bs.hasBinding("edge")) { /* * Edge property */ final BlazeEdge edge = (BlazeEdge) this.edge.apply(bs); prop = this.<V>property(edge).apply(bs); } else { final BlazeVertex vertex = (BlazeVertex) this.vertex.apply(bs); if (bs.hasBinding("vpVal")) { /* * VertexProperty property */ final MapBindingSet remap = new MapBindingSet() {{ addBinding("vp", bs.getValue("vp")); addBinding("val", bs.getValue("vpVal")); }}; final BlazeVertexProperty<V> vp = (BlazeVertexProperty<V>) this.<V>vertexProperty(vertex).apply(remap); prop = this.<V>property(vp).apply(bs); } else { /* * Vertex property */ prop = this.<V>vertexProperty(vertex).apply(bs); } } return prop; }; }
Example #19
Source File: MutableTupleQueryResult.java From database with GNU General Public License v2.0 | 5 votes |
public void insert(int index, BindingSet bindingSet) { bindingSets.add(index, bindingSet); if (currentIndex > index) { currentIndex++; } lastReturned = -1; }
Example #20
Source File: BlazeGraph.java From tinkerpop3 with GNU General Public License v2.0 | 5 votes |
/** * Run a Sparql count aggregation and parse the count from the result set. */ private int count(final String queryStr) { try (Stream<BindingSet> stream = _select(queryStr, nextQueryId())) { return stream.map(bs -> (Literal) bs.getValue("count")) .map(Literal::intValue) .findFirst().get(); } }
Example #21
Source File: Test_Ticket_605.java From database with GNU General Public License v2.0 | 5 votes |
/** * A Java version of the scala example. * * @throws Exception * * @see <a href="http://trac.bigdata.com/ticket/605" > Error in function * :rangeCount </a> */ public void test_ticket_605() throws Exception { final URI s = new URIImpl(":s"); final URI p = new URIImpl(":p"); final URI o = new URIImpl(":o"); final Statement[] a = new Statement[] { ValueFactoryImpl.getInstance() .createStatement(s, p, o) }; final AddOp addOp = new AddOp(Arrays.asList(a)); m_repo.add(addOp); final TupleQueryResult result = m_repo.prepareTupleQuery( "SELECT * {?s ?p ?o} LIMIT 100").evaluate(); try { while (result.hasNext()) { final BindingSet bset = result.next(); if (log.isInfoEnabled()) { log.info(bset); } System.out.println(bset); } } finally { result.close(); } }
Example #22
Source File: SesameMatch.java From trainbenchmark with Eclipse Public License 1.0 | 5 votes |
public static SesameMatch createMatch(final RailwayQuery query, final BindingSet bs) { switch (query) { case CONNECTEDSEGMENTS: return new SesameConnectedSegmentsMatch(bs); case CONNECTEDSEGMENTS_INJECT: return new SesameConnectedSegmentsInjectMatch(bs); case POSLENGTH: return new SesamePosLengthMatch(bs); case POSLENGTH_INJECT: return new SesamePosLengthInjectMatch(bs); case ROUTESENSOR: return new SesameRouteSensorMatch(bs); case ROUTESENSOR_INJECT: return new SesameRouteSensorInjectMatch(bs); case SEMAPHORENEIGHBOR: return new SesameSemaphoreNeighborMatch(bs); case SEMAPHORENEIGHBOR_INJECT: return new SesameSemaphoreNeighborInjectMatch(bs); case SWITCHMONITORED: return new SesameSwitchMonitoredMatch(bs); case SWITCHMONITORED_INJECT: return new SesameSwitchMonitoredInjectMatch(bs); case SWITCHSET: return new SesameSwitchSetMatch(bs); case SWITCHSET_INJECT: return new SesameSwitchSetInjectMatch(bs); default: throw new UnsupportedOperationException("Pattern not supported: " + query); } }
Example #23
Source File: RangeEvaluationStrategy.java From cumulusrdf with Apache License 2.0 | 5 votes |
public CloseableIteration<BindingSet, QueryEvaluationException> evaluate(StatementPattern sp, final BindingSet bindings) throws QueryEvaluationException { if (sp instanceof RangeStatementPattern) { return evaluate((RangeStatementPattern) sp, bindings); } else { return super.evaluate(sp, bindings); } }
Example #24
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 #25
Source File: SampleCode.java From database with GNU General Public License v2.0 | 5 votes |
/** * Execute a "select" query. * * @param repo * @param query * @param ql * @throws Exception */ public void executeSelectQuery(Repository repo, String query, QueryLanguage ql) throws Exception { /* * With MVCC, you read from a historical state to avoid blocking and * being blocked by writers. BigdataSailRepository.getQueryConnection * gives you a view of the repository at the last commit point. */ RepositoryConnection cxn; if (repo instanceof BigdataSailRepository) { cxn = ((BigdataSailRepository) repo).getReadOnlyConnection(); } else { cxn = repo.getConnection(); } try { final TupleQuery tupleQuery = cxn.prepareTupleQuery(ql, query); tupleQuery.setIncludeInferred(true /* includeInferred */); TupleQueryResult result = tupleQuery.evaluate(); // do something with the results while (result.hasNext()) { BindingSet bindingSet = result.next(); log.info(bindingSet); } } finally { // close the repository connection cxn.close(); } }
Example #26
Source File: SparqlEvaluator.java From anno4j with Apache License 2.0 | 5 votes |
public BindingSet asBindingSet() throws OpenRDFException { TupleQueryResult result = asTupleQueryResult(); try { if (result.hasNext()) { BindingSet bindings = result.next(); if (result.hasNext()) throw new MultipleResultException(); return bindings; } return null; } finally { result.close(); } }
Example #27
Source File: CumulusRDFSailConnection.java From cumulusrdf with Apache License 2.0 | 5 votes |
@Override protected CloseableIteration<? extends BindingSet, QueryEvaluationException> evaluateInternal(TupleExpr tupleExpr, Dataset dataset, BindingSet bindings, boolean includeInferred) throws SailException { // Lock stLock = _sail.getStatementsReadLock(); // Clone the tuple expression to allow for more aggressive optimizations tupleExpr = tupleExpr.clone(); if (!(tupleExpr instanceof QueryRoot)) { // Add a dummy root node to the tuple expressions to allow the // optimizers to modify the actual root node tupleExpr = new QueryRoot(tupleExpr); } TripleSource tripleSource = new CumulusRDFTripleSource(); EvaluationStrategy strategy = new RangeEvaluationStrategy(tripleSource, dataset); new BindingAssigner().optimize(tupleExpr, dataset, bindings); new ConstantOptimizer(strategy).optimize(tupleExpr, dataset, bindings); new CompareOptimizer().optimize(tupleExpr, dataset, bindings); new ConjunctiveConstraintSplitter().optimize(tupleExpr, dataset, bindings); new DisjunctiveConstraintOptimizer().optimize(tupleExpr, dataset, bindings); new SameTermFilterOptimizer().optimize(tupleExpr, dataset, bindings); new QueryModelNormalizer().optimize(tupleExpr, dataset, bindings); new CumulusQueryOptimizer(_crdf.isRangeIndexesSupportEnabled()).optimize(tupleExpr, dataset, bindings); new QueryJoinOptimizer(_select_est).optimize(tupleExpr, dataset, bindings); // new FilterOptimizer().optimize(tupleExpr, dataset, bindings); new IterativeEvaluationOptimizer().optimize(tupleExpr, dataset, bindings); new OrderLimitOptimizer().optimize(tupleExpr, dataset, bindings); try { return strategy.evaluate(tupleExpr, EmptyBindingSet.getInstance()); } catch (QueryEvaluationException e) { e.printStackTrace(); throw new SailException(e); } }
Example #28
Source File: ObjectArrayCursor.java From anno4j with Apache License 2.0 | 5 votes |
private Object createRDFObject(Value value, String binding, List<BindingSet> properties) throws QueryEvaluationException { if (value == null) return null; if (value instanceof Literal) return of.createObject((Literal) value); Object obj; if (properties.get(0).hasBinding(binding + "_class")) { Set<URI> list = new HashSet<URI>(properties.size()); for (BindingSet bindings : properties) { Value t = bindings.getValue(binding + "_class"); if (t instanceof URI) { list.add((URI) t); } } obj = manager.getObject(list, (Resource) value); } else { try { obj = manager.getObject(value); } catch (RepositoryException e) { throw new QueryEvaluationException(e); } } if (obj instanceof PropertyConsumer) { ((PropertyConsumer) obj).usePropertyBindings(binding, properties); } return obj; }
Example #29
Source File: ObjectCursor.java From anno4j with Apache License 2.0 | 5 votes |
public ObjectCursor(ObjectConnection manager, CloseableIteration<BindingSet, QueryEvaluationException> result, String binding) throws QueryEvaluationException { this.binding = binding; this.result = result; this.next = result.hasNext() ? result.next() : null; this.manager = manager; this.of = manager.getObjectFactory(); }
Example #30
Source File: ObjectCursor.java From anno4j with Apache License 2.0 | 5 votes |
private List<BindingSet> readProperties() throws QueryEvaluationException { Value resource = next.getValue(binding); List<BindingSet> properties = new ArrayList<BindingSet>(); while (next != null && equals(resource, next.getValue(binding))) { properties.add(next); next = result.hasNext() ? result.next() : null; } return properties; }