org.eclipse.rdf4j.query.algebra.evaluation.QueryBindingSet Java Examples

The following examples show how to use org.eclipse.rdf4j.query.algebra.evaluation.QueryBindingSet. 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: PCJKeyToCrossProductBindingSetIterator.java    From rya with Apache License 2.0 6 votes vote down vote up
/**
 * This method compute the cross product of the BindingSet passed to the PCJ
 * and the PCJ BindingSet.  It verifies that only common variables are unassured
 * variables, and if leftBs and rightBs have distinct values for a given variable,
 * this method uses the value from leftBs in the cross product BindingSet - this
 * is effectively performing a LeftJoin.
 *
 * @param leftBs - BindingSet passed to PCJ
 * @param rightBs - PCJ BindingSet
 * @return - cross product BindingSet
 */
private BindingSet takeCrossProduct(BindingSet leftBs, BindingSet rightBs) {
	if (bindingSetsIntersect(leftBs, rightBs)) {
		return EMPTY_BINDINGSET;
	}
	QueryBindingSet bs = new QueryBindingSet(leftBs);

	//only add Bindings corresponding to variables that have no value
	//assigned.  This takes into account case where leftBs and rightBs
	//share a common, unAssuredVariable.  In this case, use value corresponding
	//to leftBs, which is effectively performing a LeftJoin.
	for(String s: rightBs.getBindingNames()) {
		if(bs.getValue(s) == null) {
			bs.addBinding(s, rightBs.getValue(s));
		}
	}
	return bs;
}
 
Example #2
Source File: AccumuloStatementMetadataOptimizerIT.java    From rya with Apache License 2.0 6 votes vote down vote up
@Test
public void simpleQueryWithoutBindingSet() throws Exception {
    StatementMetadata metadata = new StatementMetadata();
    metadata.addMetadata(new RyaIRI("http://createdBy"), new RyaType("Joe"));
    metadata.addMetadata(new RyaIRI("http://createdOn"), new RyaType(XMLSchema.DATE, "2017-01-04"));

    RyaStatement statement = new RyaStatement(new RyaIRI("http://Joe"), new RyaIRI("http://worksAt"),
            new RyaType("CoffeeShop"), new RyaIRI("http://context"), "", metadata);
    dao.add(statement);

    TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, query1).evaluate();

    QueryBindingSet bs = new QueryBindingSet();
    bs.addBinding("x", VF.createLiteral("CoffeeShop"));
    bs.addBinding("y", VF.createLiteral("Joe"));

    List<BindingSet> bsList = new ArrayList<>();
    while (result.hasNext()) {
        bsList.add(result.next());
    }

    System.out.println(bsList);
    Assert.assertEquals(1, bsList.size());
    Assert.assertEquals(bs, bsList.get(0));
    dao.delete(statement, (AccumuloRdfConfiguration) conf);
}
 
Example #3
Source File: StatementMetadataNode.java    From rya with Apache License 2.0 6 votes vote down vote up
/**
 * Builds BindingSet from Entry if possible. Otherwise returns an empty
 * Optional if no valid BindingSet can be built. Valid BindingSet can be
 * built if this class's property Map is consistent with
 * {@link StatementMetadata} properties for the specified RyaStatement
 * and if the BindingSet built form the StatementMetadata properties can
 * be joined with specified BindingSet.
 *
 * @param statement
 *            - RyaStatement
 * @param bindingSet
 *            - BindingSet
 * @return - Optional containing BindingSet is a valid BindingSet could
 *         be built
 */
private Optional<BindingSet> buildBindingSet(final RyaStatement statement, final BindingSet bindingSet) {

    final QueryBindingSet bs = new QueryBindingSet();
    final Optional<BindingSet> optPropBs = buildPropertyBindingSet(statement);
    if (!optPropBs.isPresent()) {
        return Optional.empty();
    }
    final BindingSet propBs = optPropBs.get();
    final BindingSet spBs = buildBindingSetFromStatementPattern(statement);
    if (!canJoinBindingSets(spBs, propBs)) {
        return Optional.empty();
    }
    bs.addAll(spBs);
    bs.addAll(propBs);
    if (!canJoinBindingSets(bs, bindingSet)) {
        return Optional.empty();
    }
    bs.addAll(bindingSet);
    return Optional.of(bs);

}
 
Example #4
Source File: StatementConversionIteration.java    From CostFed with GNU Affero General Public License v3.0 6 votes vote down vote up
protected BindingSet convert(Statement st) {
	QueryBindingSet result = new QueryBindingSet(bindings);

	if (updateSubj) {
		result.addBinding(stmt.getSubjectVar().getName(), st.getSubject());
	}
	if (updatePred) {
		result.addBinding(stmt.getPredicateVar().getName(), st.getPredicate());
	}
	if (updateObj) {
		result.addBinding(stmt.getObjectVar().getName(), st.getObject());
	}
	if (updateContext && st.getContext() != null) {
		result.addBinding(stmt.getContextVar().getName(), st.getContext());
	}

	return result;
}
 
Example #5
Source File: BoundJoinVALUESConversionIteration.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
protected BindingSet convert(BindingSet bIn) throws QueryEvaluationException {
	QueryBindingSet res = new QueryBindingSet();
	int bIndex = Integer.parseInt(bIn.getBinding(INDEX_BINDING_NAME).getValue().stringValue());
	Iterator<Binding> bIter = bIn.iterator();
	while (bIter.hasNext()) {
		Binding b = bIter.next();
		if (b.getName().equals(INDEX_BINDING_NAME)) {
			continue;
		}
		res.addBinding(b);
	}
	for (Binding bs : bindings.get(bIndex)) {
		res.setBinding(bs);
	}
	return res;
}
 
Example #6
Source File: HashJoinIterationTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testCartesianJoin() throws QueryEvaluationException {
	BindingSetAssignment left = new BindingSetAssignment();
	{
		QueryBindingSet leftb = new QueryBindingSet();
		leftb.addBinding("a", vf.createLiteral("1"));
		left.setBindingSets(Arrays.<BindingSet>asList(leftb));
	}

	BindingSetAssignment right = new BindingSetAssignment();
	{
		QueryBindingSet rightb = new QueryBindingSet();
		rightb.addBinding("b", vf.createLiteral("2"));
		right.setBindingSets(Arrays.<BindingSet>asList(rightb));
	}

	HashJoinIteration iter = new HashJoinIteration(evaluator, left, right, EmptyBindingSet.getInstance(), false);
	BindingSet actual = iter.next();

	assertEquals("1", actual.getValue("a").stringValue());
	assertEquals("2", actual.getValue("b").stringValue());
}
 
Example #7
Source File: ProjectionIterator.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static BindingSet project(ProjectionElemList projElemList, BindingSet sourceBindings,
		BindingSet parentBindings, boolean includeAllParentBindings) {
	final QueryBindingSet resultBindings = new QueryBindingSet();
	if (includeAllParentBindings) {
		resultBindings.addAll(parentBindings);
	}

	for (ProjectionElem pe : projElemList.getElements()) {
		Value targetValue = sourceBindings.getValue(pe.getSourceName());
		if (!includeAllParentBindings && targetValue == null) {
			targetValue = parentBindings.getValue(pe.getSourceName());
		}
		if (targetValue != null) {
			resultBindings.setBinding(pe.getTargetName(), targetValue);
		}
	}

	return resultBindings;
}
 
Example #8
Source File: EntityTupleSet.java    From rya with Apache License 2.0 6 votes vote down vote up
@Override
public CloseableIteration<BindingSet,QueryEvaluationException> evaluate(Collection<BindingSet> bindingset) throws QueryEvaluationException {

    if(bindingset.size() < 2 && !this.evalOptUsed) {
        BindingSet bs = new QueryBindingSet();
        if (bindingset.size() == 1) {
            bs = bindingset.iterator().next();
        }
        return this.evaluate(bs);
    }
    //TODO possibly refactor if bindingset.size() > 0 to take advantage of optimization in evaluate(BindingSet bindingset)
    AccumuloDocIdIndexer adi = null;
    try {
        adi = new AccumuloDocIdIndexer(conf);
        return adi.queryDocIndex(starQuery, bindingset);
    } catch (Exception e) {
        throw new QueryEvaluationException(e);
    } finally {
        IOUtils.closeQuietly(adi);
    }
}
 
Example #9
Source File: StrictEvaluationStrategyTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Verifies if only those input bindings that actually occur in the query are returned in the result. See SES-2373.
 */
@Test
public void testBindings() throws Exception {
	String query = "SELECT ?a ?b WHERE {}";
	ParsedQuery pq = QueryParserUtil.parseQuery(QueryLanguage.SPARQL, query, null);

	final ValueFactory vf = SimpleValueFactory.getInstance();
	QueryBindingSet constants = new QueryBindingSet();
	constants.addBinding("a", vf.createLiteral("foo"));
	constants.addBinding("b", vf.createLiteral("bar"));
	constants.addBinding("x", vf.createLiteral("X"));
	constants.addBinding("y", vf.createLiteral("Y"));

	CloseableIteration<BindingSet, QueryEvaluationException> result = strategy.evaluate(pq.getTupleExpr(),
			constants);
	assertNotNull(result);
	assertTrue(result.hasNext());
	BindingSet bs = result.next();
	assertTrue(bs.hasBinding("a"));
	assertTrue(bs.hasBinding("b"));
	assertFalse(bs.hasBinding("x"));
	assertFalse(bs.hasBinding("y"));
}
 
Example #10
Source File: HashJoinIterationTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testInnerJoin() throws QueryEvaluationException {
	BindingSetAssignment left = new BindingSetAssignment();
	{
		QueryBindingSet leftb = new QueryBindingSet();
		leftb.addBinding("a", vf.createLiteral("1"));
		leftb.addBinding("i", vf.createLiteral("x"));
		left.setBindingSets(Arrays.<BindingSet>asList(leftb));
	}

	BindingSetAssignment right = new BindingSetAssignment();
	{
		QueryBindingSet rightb = new QueryBindingSet();
		rightb.addBinding("b", vf.createLiteral("2"));
		rightb.addBinding("i", vf.createLiteral("x"));
		right.setBindingSets(Arrays.<BindingSet>asList(rightb));
	}

	HashJoinIteration iter = new HashJoinIteration(evaluator, left, right, EmptyBindingSet.getInstance(), false);
	BindingSet actual = iter.next();

	assertEquals("1", actual.getValue("a").stringValue());
	assertEquals("2", actual.getValue("b").stringValue());
	assertEquals("x", actual.getValue("i").stringValue());
}
 
Example #11
Source File: HashJoinIterationTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testLeftJoin() throws QueryEvaluationException {
	BindingSetAssignment left = new BindingSetAssignment();
	{
		QueryBindingSet leftb = new QueryBindingSet();
		leftb.addBinding("a", vf.createLiteral("1"));
		leftb.addBinding("i", vf.createLiteral("x"));
		left.setBindingSets(Arrays.<BindingSet>asList(leftb));
	}

	BindingSetAssignment right = new BindingSetAssignment();
	{
		QueryBindingSet rightb = new QueryBindingSet();
		rightb.addBinding("b", vf.createLiteral("2"));
		rightb.addBinding("i", vf.createLiteral("y"));
		right.setBindingSets(Arrays.<BindingSet>asList(rightb));
	}

	HashJoinIteration iter = new HashJoinIteration(evaluator, left, right, EmptyBindingSet.getInstance(), true);
	BindingSet actual = iter.next();

	assertEquals("1", actual.getValue("a").stringValue());
	assertEquals("x", actual.getValue("i").stringValue());
	assertFalse(actual.hasBinding("b"));
}
 
Example #12
Source File: AccumuloIndexSetColumnVisibilityTest.java    From rya with Apache License 2.0 6 votes vote down vote up
@Test
public void variableInstantiationTest() throws Exception {
    // Setup the object that will be tested.
    final String pcjTableName = new PcjTableNameFactory().makeTableName(ryaInstanceName, pcjId);
    final AccumuloIndexSet ais = new AccumuloIndexSet(conf, pcjTableName);

    // Setup the binding sets that will be evaluated.
    final QueryBindingSet bs = new QueryBindingSet();
    bs.addBinding("name", VF.createIRI("http://Alice"));
    final QueryBindingSet bs2 = new QueryBindingSet();
    bs2.addBinding("name", VF.createIRI("http://Bob"));

    final Set<BindingSet> bSets = Sets.newHashSet(bs, bs2);
    final CloseableIteration<BindingSet, QueryEvaluationException> results = ais.evaluate(bSets);

    final Set<BindingSet> fetchedResults = new HashSet<>();
    while (results.hasNext()) {
        final BindingSet next = results.next();
        fetchedResults.add(next);
    }

    final Set<BindingSet> expected = Sets.newHashSet(pcjBs1, pcjBs2);
    assertEquals(expected, fetchedResults);
}
 
Example #13
Source File: StatementPatternMatcher.java    From rya with Apache License 2.0 6 votes vote down vote up
/**
 * Matches a {@link Statement} against the provided {@link StatementPattern} and returns a {@link BindingSet}
 * if the statement matched the pattern.
 *
 * @param statement - The statement that will be matched against the pattern. (not null)
 * @return A {@link BinidngSet} containing the statement's values filled in for the pattern's variables if
 *   the statement's values match the pattern's constants; otherwise empty.
 */
public Optional<BindingSet> match(final Statement statement) {
    requireNonNull(statement);

    // Setup the resulting binding set that could be built from this Statement.
    final QueryBindingSet bs = new QueryBindingSet();

    if(matchesValue(pattern.getSubjectVar(), statement.getSubject(), bs) &&
            matchesValue(pattern.getPredicateVar(), statement.getPredicate(), bs) &&
            matchesValue(pattern.getObjectVar(), statement.getObject(), bs) &&
            matchesContext(pattern.getContextVar(), statement.getContext(), bs)) {
        return Optional.of(bs);
    } else {
        return Optional.empty();
    }
}
 
Example #14
Source File: StatementPatternMatcher.java    From rya with Apache License 2.0 6 votes vote down vote up
/**
 * The following table describes how a Subject, Predicate, and Object Var may be handled for a Statement and a
 * Statement Pattern:
 * <table border=1>
 *     <tr> <th>Pattern's var is constant</th> <th>Effect on resulting BS</th> </tr>
 *     <try> <td>yes</td> <td>Emit a BS if they match, no Context binding</td> </tr>
 *     <try> <td>no</td>  <td>Emit a BS with a binding for the variable</td> </tr>
 * </table>
 *
 * @param var - The statement pattern variable that is being matched. (not null)
 * @param stmtValue - The statement's value for the variable. (not null)
 * @param bs - The binding set that may be updated to include a binding for the variable. (not null)
 * @return {@code true} if he variable and the statement value match, otherwise {@code false},
 */
private boolean matchesValue(final Var var, final Value stmtValue, final QueryBindingSet bs) {
    requireNonNull(var);
    requireNonNull(stmtValue);
    requireNonNull(bs);

    // If the var is a constant, statement's value must match the var's value.
    if(var.isConstant()) {
        if(!stmtValue.equals(var.getValue())) {
            return false;
        }
    } else {
        // Otherwise it is a variable to be filled in.
        bs.addBinding(var.getName(), stmtValue);
    }

    // Either the value matched the constant or the binding set was updated.
    return true;
}
 
Example #15
Source File: StatementPatternMatcherTest.java    From rya with Apache License 2.0 6 votes vote down vote up
@Test
public void matchesContext() throws Exception {
    // Create a matcher against a pattern that matches a specific context.
    final StatementPatternMatcher matcher = new StatementPatternMatcher(getSp(
            "SELECT * WHERE {" +
                "GRAPH <urn:testGraph> {" +
                    "?s ?p ?o ." +
                "}" +
            "}"));

    // Create a statement that matches the pattern.
    final ValueFactory vf = SimpleValueFactory.getInstance();
    final Statement statement = vf.createStatement(vf.createIRI("urn:Alice"), vf.createIRI("urn:talksTo"), vf.createIRI("urn:Bob"), vf.createIRI("urn:testGraph"));

    // Create the expected resulting Binding Set.
    final QueryBindingSet expected = new QueryBindingSet();
    expected.addBinding("s", vf.createIRI("urn:Alice"));
    expected.addBinding("p", vf.createIRI("urn:talksTo"));
    expected.addBinding("o", vf.createIRI("urn:Bob"));

    // Show the expected Binding Set matches the resulting Binding Set.
    final Optional<BindingSet> bs = matcher.match(statement);
    assertEquals(expected, bs.get());
}
 
Example #16
Source File: PeriodicQueryUpdater.java    From rya with Apache License 2.0 6 votes vote down vote up
/**
 * Uses the {@link PeriodicQueryMetadata} to create a collection of binned BindingSets
 * that are added to Fluo.  Each binned BindingSet is the original BindingSet with an additional
 * Binding that contains the periodic bin id of the BindingSet.
 * @param tx - Fluo Transaction
 * @param bs - VisibilityBindingSet that will be binned
 * @param metadata - PeriodicQueryMetadata used to bin BindingSets
 * @throws Exception
 */
public void updatePeriodicBinResults(TransactionBase tx, VisibilityBindingSet bs, PeriodicQueryMetadata metadata) throws Exception {
    Set<Long> binIds = getBinEndTimes(metadata, bs);
    for(Long id: binIds) {
        //create binding set value bytes
        QueryBindingSet binnedBs = new QueryBindingSet(bs);
        binnedBs.addBinding(IncrementalUpdateConstants.PERIODIC_BIN_ID, VF.createLiteral(id));
        VisibilityBindingSet visibilityBindingSet = new VisibilityBindingSet(binnedBs, bs.getVisibility());
        Bytes periodicBsBytes = BS_SERDE.serialize(visibilityBindingSet);

        //create row
        final Bytes resultRow = makeRowKey(metadata.getNodeId(), metadata.getVariableOrder(), visibilityBindingSet);
        Column col = FluoQueryColumns.PERIODIC_QUERY_BINDING_SET;
        tx.set(resultRow, col, periodicBsBytes);
    }
}
 
Example #17
Source File: ConstructProjectionTest.java    From rya with Apache License 2.0 6 votes vote down vote up
@Test
public void testConstructProjectionProjectSubj() throws MalformedQueryException, UnsupportedEncodingException {
    String query = "select ?x where { ?x <uri:talksTo> <uri:Bob> }";
    
    SPARQLParser parser = new SPARQLParser();
    ParsedQuery pq = parser.parseQuery(query, null);
    List<StatementPattern> patterns = StatementPatternCollector.process(pq.getTupleExpr());
    ConstructProjection projection = new ConstructProjection(patterns.get(0));
    
    QueryBindingSet bs = new QueryBindingSet();
    bs.addBinding("x", VF.createIRI("uri:Joe"));
    VisibilityBindingSet vBs = new VisibilityBindingSet(bs, "FOUO");
    RyaStatement statement = projection.projectBindingSet(vBs, new HashMap<>());
    
    RyaStatement expected = new RyaStatement(new RyaIRI("uri:Joe"), new RyaIRI("uri:talksTo"), new RyaIRI("uri:Bob"));
    expected.setColumnVisibility("FOUO".getBytes("UTF-8"));
    expected.setTimestamp(statement.getTimestamp());
    
    assertEquals(expected, statement);
}
 
Example #18
Source File: EvaluationStrategyImpl.java    From semagrow with Apache License 2.0 6 votes vote down vote up
public void bindSolution(QueryBindingSet sol) throws QueryEvaluationException {
    Iterator i$ = this.aggregates.keySet().iterator();

    while(i$.hasNext()) {
        String name = (String)i$.next();

        try {
            Value ex = ((Aggregate)this.aggregates.get(name)).getValue();
            if(ex != null) {
                sol.setBinding(name, ex);
            }
        } catch (ValueExprEvaluationException var5) {
            ;
        }
    }

}
 
Example #19
Source File: AccumuloStatementMetadataNodeTest.java    From rya with Apache License 2.0 6 votes vote down vote up
/**
 * Tests if results are filtered correctly using the metadata properties. In
 * this case, the date for the ingested RyaStatement differs from the date
 * specified in the query.
 * 
 * @throws MalformedQueryException
 * @throws QueryEvaluationException
 * @throws RyaDAOException
 */
@Test
public void simpleQueryWithoutBindingSetInvalidProperty()
        throws MalformedQueryException, QueryEvaluationException, RyaDAOException {
    StatementMetadata metadata = new StatementMetadata();
    metadata.addMetadata(new RyaIRI("http://createdBy"), new RyaType("Doug"));
    metadata.addMetadata(new RyaIRI("http://createdOn"), new RyaType(XMLSchema.DATE, "2017-02-15"));

    RyaStatement statement = new RyaStatement(new RyaIRI("http://Joe"), new RyaIRI("http://worksAt"),
            new RyaType("CoffeeShop"), new RyaIRI("http://context"), "", metadata);
    dao.add(statement);

    SPARQLParser parser = new SPARQLParser();
    ParsedQuery pq = parser.parseQuery(query, null);
    List<StatementPattern> spList = StatementPatternCollector.process(pq.getTupleExpr());
    StatementMetadataNode<AccumuloRdfConfiguration> node = new StatementMetadataNode<>(spList, conf);
    CloseableIteration<BindingSet, QueryEvaluationException> iteration = node.evaluate(new QueryBindingSet());

    List<BindingSet> bsList = new ArrayList<>();
    while (iteration.hasNext()) {
        bsList.add(iteration.next());
    }
    Assert.assertEquals(0, bsList.size());
    dao.delete(statement, conf);
}
 
Example #20
Source File: AccumuloPcjSerializerTest.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void basicShortMixLiteralBsTest() throws BindingSetConversionException {
	final QueryBindingSet bs = new QueryBindingSet();
	bs.addBinding("X",VF.createLiteral("literal1"));
	bs.addBinding("Y",VF.createLiteral("5", VF.createIRI("http://www.w3.org/2001/XMLSchema#integer")));
	final VariableOrder varOrder = new VariableOrder("X","Y");

	BindingSetConverter<byte[]> converter = new AccumuloPcjSerializer();
	final byte[] byteVal = converter.convert(bs, varOrder);
	final BindingSet newBs = converter.convert(byteVal, varOrder);
	assertEquals(bs, newBs);
}
 
Example #21
Source File: MongoStatementMetadataNodeIT.java    From rya with Apache License 2.0 5 votes vote down vote up
/**
 * Tests if results are filtered correctly using the metadata properties. In
 * this case, the date for the ingested RyaStatement differs from the date
 * specified in the query.
 */
@Test
public void simpleQueryWithoutBindingSetInvalidProperty() throws Exception {
    final MongoDBRyaDAO dao = new MongoDBRyaDAO();
    try {
        dao.setConf(conf);
        dao.init();

        final StatementMetadata metadata = new StatementMetadata();
        metadata.addMetadata(new RyaIRI("http://createdBy"), new RyaType("Doug"));
        metadata.addMetadata(new RyaIRI("http://createdOn"), new RyaType(XMLSchema.DATE, "2017-02-15"));

        final RyaStatement statement = new RyaStatement(new RyaIRI("http://Joe"), new RyaIRI("http://worksAt"),
                new RyaType("CoffeeShop"), new RyaIRI("http://context"), "", metadata);
        dao.add(statement);

        final SPARQLParser parser = new SPARQLParser();
        final ParsedQuery pq = parser.parseQuery(query, null);
        final List<StatementPattern> spList = StatementPatternCollector.process(pq.getTupleExpr());
        final StatementMetadataNode<MongoDBRdfConfiguration> node = new StatementMetadataNode<>(spList, conf);
        final CloseableIteration<BindingSet, QueryEvaluationException> iteration = node.evaluate(new QueryBindingSet());

        final List<BindingSet> bsList = new ArrayList<>();
        while (iteration.hasNext()) {
            bsList.add(iteration.next());
        }
        Assert.assertEquals(0, bsList.size());
        dao.delete(statement, conf);
    } finally {
        dao.destroy();
    }
}
 
Example #22
Source File: BindingHashShardingFunctionTest.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void shardAddAndRemoveTest() {
    String nodeId = NodeType.generateNewFluoIdForType(NodeType.STATEMENT_PATTERN);
    QueryBindingSet bs = new QueryBindingSet();
    bs.addBinding("entity", VF.createIRI("urn:entity"));
    bs.addBinding("location", VF.createLiteral("location_1"));
    VisibilityBindingSet vBs = new VisibilityBindingSet(bs);
    VariableOrder varOrder = new VariableOrder("entity","location");
    Bytes row = RowKeyUtil.makeRowKey(nodeId, varOrder, vBs);
    Bytes shardedRow = BindingHashShardingFunction.addShard(nodeId, varOrder, vBs);
    Bytes shardlessRow = BindingHashShardingFunction.removeHash(Bytes.of(SP_PREFIX), shardedRow);
    Assert.assertEquals(row, shardlessRow);
}
 
Example #23
Source File: GraphToBindingSetConversionIteration.java    From CostFed with GNU Affero General Public License v3.0 5 votes vote down vote up
protected BindingSet convert(Statement st) {
	QueryBindingSet result = new QueryBindingSet();
	result.addBinding("subject", st.getSubject());
	result.addBinding("predicate", st.getPredicate());
	result.addBinding("object", st.getObject());
	if (st.getContext() != null) {
		result.addBinding("context", st.getContext());
	}

	return result;
}
 
Example #24
Source File: EvaluationStrategyImpl.java    From semagrow with Apache License 2.0 5 votes vote down vote up
public Observable<BindingSet> evaluateReactiveInternal(BindingSetAssignment expr, BindingSet bindings)
        throws QueryEvaluationException
{
    final Iterator<BindingSet> iter = expr.getBindingSets().iterator();

    final List<BindingSet> blist = new LinkedList<BindingSet>();
    Iterators.addAll(iter, blist);

    return Observable.from(blist)
            .map((b) -> {
                QueryBindingSet bb = new QueryBindingSet(bindings);
                bb.addAll(b);
                return bb;
            });
}
 
Example #25
Source File: OneOfVisitorTest.java    From rya with Apache License 2.0 5 votes vote down vote up
private static void assertBindingSet(final Iterator<BindingSet> bindingSetIter, final Iterator<Resource> expectedValues) {
    while (expectedValues.hasNext()) {
        final Resource expectedValue = expectedValues.next();
        assertTrue(bindingSetIter.hasNext());
        final BindingSet bindingSet = bindingSetIter.next();
        assertTrue(bindingSet instanceof QueryBindingSet);
        assertEquals(1, bindingSet.getBindingNames().size());
        final Binding binding = bindingSet.getBinding("s");
        assertNotNull(binding);
        final Value actualValue = binding.getValue();
        assertEquals(expectedValue, actualValue);
    }
}
 
Example #26
Source File: OneOfVisitor.java    From rya with Apache License 2.0 5 votes vote down vote up
@Override
protected void meetSP(final StatementPattern node) throws Exception {
    final Var subVar = node.getSubjectVar();
    final Var predVar = node.getPredicateVar();
    final Var objVar = node.getObjectVar();
    final Var conVar = node.getContextVar();
    if (predVar != null && objVar != null && objVar.getValue() != null && objVar.getValue() instanceof Resource && RDF.TYPE.equals(predVar.getValue()) && !EXPANDED.equals(conVar)) {
        final Resource object = (Resource) objVar.getValue();
        if (inferenceEngine.isEnumeratedType(object)) {
            final Set<BindingSet> solutions = new LinkedHashSet<>();
            final Set<Resource> enumeration = inferenceEngine.getEnumeration(object);
            for (final Resource enumType : enumeration) {
                final QueryBindingSet qbs = new QueryBindingSet();
                qbs.addBinding(subVar.getName(), enumType);
                solutions.add(qbs);
            }

            if (!solutions.isEmpty()) {
                final BindingSetAssignment enumNode = new BindingSetAssignment();
                enumNode.setBindingSets(solutions);

                node.replaceWith(enumNode);
                log.trace("Replacing node with inferred one of enumeration: " + enumNode);
            }
        }
    }
}
 
Example #27
Source File: MongoStatementMetadataNodeIT.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void simpleQueryWithoutBindingSet() throws Exception {
    final MongoDBRyaDAO dao = new MongoDBRyaDAO();
    try {
        dao.setConf(conf);
        dao.init();
        final StatementMetadata metadata = new StatementMetadata();
        metadata.addMetadata(new RyaIRI("http://createdBy"), new RyaType("Joe"));
        metadata.addMetadata(new RyaIRI("http://createdOn"), new RyaType(XMLSchema.DATE, "2017-01-04"));

        final RyaStatement statement = new RyaStatement(new RyaIRI("http://Joe"), new RyaIRI("http://worksAt"),
                new RyaType("CoffeeShop"), new RyaIRI("http://context"), "", metadata);
        dao.add(statement);

        final SPARQLParser parser = new SPARQLParser();
        final ParsedQuery pq = parser.parseQuery(query, null);
        final List<StatementPattern> spList = StatementPatternCollector.process(pq.getTupleExpr());

        final StatementMetadataNode<?> node = new StatementMetadataNode<>(spList, conf);
        final CloseableIteration<BindingSet, QueryEvaluationException> iteration = node.evaluate(new QueryBindingSet());

        final QueryBindingSet bs = new QueryBindingSet();
        bs.addBinding("x", VF.createLiteral("CoffeeShop"));
        bs.addBinding("y", VF.createLiteral("Joe"));

        final List<BindingSet> bsList = new ArrayList<>();
        while (iteration.hasNext()) {
            bsList.add(iteration.next());
        }

        Assert.assertEquals(1, bsList.size());
        Assert.assertEquals(bs, bsList.get(0));
        dao.delete(statement, conf);
    } finally {
        dao.destroy();
    }
}
 
Example #28
Source File: InsertBindingsIteration.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
protected BindingSet convert(BindingSet bIn) throws QueryEvaluationException {
	QueryBindingSet res = new QueryBindingSet(bindings.size() + bIn.size());
	res.addAll(bindings);
	res.addAll(bIn);
	return res;
}
 
Example #29
Source File: FederationEvalStrategy.java    From CostFed with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Evaluate a projection containing additional values, e.g. set from a filter expression
 * 
 * @return
 * @throws QueryEvaluationException
 */
public CloseableIteration<BindingSet, QueryEvaluationException> evaluateProjectionWithBindings(ProjectionWithBindings projection, BindingSet bindings) throws QueryEvaluationException {
	QueryBindingSet actualBindings = new QueryBindingSet(bindings);
	for (Binding b : projection.getAdditionalBindings())
		actualBindings.addBinding(b);
	return evaluate((Projection)projection, actualBindings);
}
 
Example #30
Source File: PipelineResultIteration.java    From rya with Apache License 2.0 5 votes vote down vote up
private QueryBindingSet docToBindingSet(Document result) {
    QueryBindingSet bindingSet = new QueryBindingSet(bindings);
    Document valueSet = result.get(AggregationPipelineQueryNode.VALUES, Document.class);
    Document typeSet = result.get(AggregationPipelineQueryNode.TYPES, Document.class);
    if (valueSet != null) {
        for (Map.Entry<String, Object> entry : valueSet.entrySet()) {
            String fieldName = entry.getKey();
            String valueString = entry.getValue().toString();
            String typeString = typeSet == null ? null : typeSet.getString(fieldName);
            String varName = varToOriginalName.getOrDefault(fieldName, fieldName);
            Value varValue;
            if (typeString == null || typeString.equals(XMLSchema.ANYURI.stringValue())) {
                varValue = VF.createIRI(valueString);
            }
            else {
                varValue = VF.createLiteral(valueString, VF.createIRI(typeString));
            }
            Binding existingBinding = bindingSet.getBinding(varName);
            // If this variable is not already bound, add it.
            if (existingBinding == null) {
                bindingSet.addBinding(varName, varValue);
            }
            // If it's bound to something else, the solutions are incompatible.
            else if (!existingBinding.getValue().equals(varValue)) {
                return null;
            }
        }
    }
    return bindingSet;
}