org.eclipse.rdf4j.query.algebra.Compare Java Examples

The following examples show how to use org.eclipse.rdf4j.query.algebra.Compare. 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: QueryAlgebraUtil.java    From CostFed with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Construct the statement string, i.e. "s p ?o_varID FILTER ?o_N=o ". This kind of statement
 * pattern is necessary to later on identify available results.
 * 
 * @param stmt
 * @param varID
 * @param varNames
 * @param bindings
 * @return
 */
protected static TupleExpr constructStatementCheckId(StatementPattern stmt, int varID, Set<String> varNames, BindingSet bindings) {
	
	String _varID = Integer.toString(varID);
	Var subj = appendVarId(stmt.getSubjectVar(), _varID, varNames, bindings);
	Var pred = appendVarId(stmt.getPredicateVar(), _varID, varNames, bindings);
	
	Var obj = new Var("o_" + _varID);
	varNames.add("o_" + _varID);
			
	Value objValue;
	if (stmt.getObjectVar().hasValue()) {
		objValue = stmt.getObjectVar().getValue();
	} else if (bindings.hasBinding(stmt.getObjectVar().getName())){
		objValue = bindings.getBinding(stmt.getObjectVar().getName()).getValue();
	} else {
		// just to make sure that we see an error, will be deleted soon
		throw new RuntimeException("Unexpected.");
	}
	
	Compare cmp = new Compare(obj, new ValueConstant(objValue));
	cmp.setOperator(CompareOp.EQ);
	Filter filter = new Filter( new StatementPattern(subj, pred, obj), cmp);
			
	return filter;
}
 
Example #2
Source File: CompareOptimizer.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void meet(Compare compare) {
	super.meet(compare);

	if (compare.getOperator() == CompareOp.EQ) {
		ValueExpr leftArg = compare.getLeftArg();
		ValueExpr rightArg = compare.getRightArg();

		boolean leftIsVar = isVar(leftArg);
		boolean rightIsVar = isVar(rightArg);
		boolean leftIsResource = isResource(leftArg);
		boolean rightIsResource = isResource(rightArg);

		if (leftIsVar && rightIsResource || leftIsResource && rightIsVar || leftIsResource && rightIsResource) {
			SameTerm sameTerm = new SameTerm(leftArg, rightArg);
			compare.replaceWith(sameTerm);
		}
	}
}
 
Example #3
Source File: AggregationPipelineQueryNodeTest.java    From rya with Apache License 2.0 6 votes vote down vote up
@Test
public void testFilter() {
    final AggregationPipelineQueryNode base = new AggregationPipelineQueryNode(
            collection,
            new LinkedList<>(),
            Sets.newHashSet("x", "y"),
            Sets.newHashSet("x", "y", "opt"),
            HashBiMap.create());
    // Extend with a supported filter
    AggregationPipelineQueryNode node = base.clone();
    boolean success = node.filter(new Compare(new Var("x"), new Var("y"), Compare.CompareOp.EQ));
    Assert.assertTrue(success);
    Assert.assertEquals(Sets.newHashSet("x", "y", "opt"), node.getBindingNames());
    Assert.assertEquals(Sets.newHashSet("x", "y"), node.getAssuredBindingNames());
    Assert.assertEquals(3, node.getPipeline().size());
    // Extend with an unsupported filter
    node = base.clone();
    success = node.filter(new IsLiteral(new Var("opt")));
    Assert.assertFalse(success);
    Assert.assertEquals(Sets.newHashSet("x", "y", "opt"), node.getBindingNames());
    Assert.assertEquals(Sets.newHashSet("x", "y"), node.getAssuredBindingNames());
    Assert.assertEquals(0, node.getPipeline().size());
}
 
Example #4
Source File: DistanceQuerySpecBuilder.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private static Object[] getFilterAndDistance(QueryModelNode node, String compareArgVarName) {
	Object[] rv = null;
	if (node instanceof Filter) {
		Filter f = (Filter) node;
		ValueExpr condition = f.getCondition();
		if (condition instanceof Compare) {
			Compare compare = (Compare) condition;
			CompareOp op = compare.getOperator();
			ValueExpr dist = null;
			if (op == CompareOp.LT
					&& compareArgVarName.equals(DistanceQuerySpec.getVarName(compare.getLeftArg()))) {
				dist = compare.getRightArg();
			} else if (op == CompareOp.GT
					&& compareArgVarName.equals(DistanceQuerySpec.getVarName(compare.getRightArg()))) {
				dist = compare.getLeftArg();
			}
			rv = new Object[] { f, dist };
		}
	} else if (node != null) {
		rv = getFilterAndDistance(node.getParentNode(), compareArgVarName);
	}
	return rv;
}
 
Example #5
Source File: ExtendedEvaluationStrategy.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public Value evaluate(Compare node, BindingSet bindings)
		throws ValueExprEvaluationException, QueryEvaluationException {
	Value leftVal = evaluate(node.getLeftArg(), bindings);
	Value rightVal = evaluate(node.getRightArg(), bindings);

	// return result of non-strict comparisson.
	return BooleanLiteral.valueOf(QueryEvaluationUtil.compare(leftVal, rightVal, node.getOperator(), false));
}
 
Example #6
Source File: QueryModelBuilder.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public Compare visit(ASTCompare node, Object data) throws VisitorException {
	ValueExpr leftArg = (ValueExpr) node.getLeftOperand().jjtAccept(this, null);
	ValueExpr rightArg = (ValueExpr) node.getRightOperand().jjtAccept(this, null);
	CompareOp operator = node.getOperator().getValue();

	return new Compare(leftArg, rightArg, operator);
}
 
Example #7
Source File: SerqlValueExprRenderer.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * @inheritDoc
 */
@Override
public void meet(Compare theOp) throws Exception {
	mBuffer.append("(");
	theOp.getLeftArg().visit(this);
	mBuffer.append(" ").append(theOp.getOperator().getSymbol()).append(" ");
	theOp.getRightArg().visit(this);
	mBuffer.append(")");
}
 
Example #8
Source File: SparqlValueExprRenderer.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * @inheritDoc
 */
@Override
public void meet(Compare theOp) throws Exception {
	mBuffer.append("(");
	theOp.getLeftArg().visit(this);
	mBuffer.append(" ").append(theOp.getOperator().getSymbol()).append(" ");
	theOp.getRightArg().visit(this);
	mBuffer.append(")");
}
 
Example #9
Source File: TupleExprsTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void isFilterExistsFunctionOnNormalNot() {
	Filter expr = new Filter();
	expr.setArg(new StatementPattern());
	expr.setCondition(new Not(new Compare(new Var("x", f.createBNode()), new Var("y", f.createBNode()))));

	assertThat(isFilterExistsFunction(expr)).isFalse();
}
 
Example #10
Source File: TupleExprsTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void isFilterExistsFunctionOnNormalFilter() {
	Filter expr = new Filter();
	expr.setArg(new StatementPattern());
	expr.setCondition(new Compare(new Var("x", f.createBNode()), new Var("y", f.createBNode())));

	assertThat(isFilterExistsFunction(expr)).isFalse();
}
 
Example #11
Source File: HalyardValueExprEvaluation.java    From Halyard with Apache License 2.0 5 votes vote down vote up
/**
 * Evaluate a {@link ListMemberOperator}
 * @param node the node to evaluate
 * @param bindings the set of named value bindings
 * @return
 * @throws ValueExprEvaluationException
 * @throws QueryEvaluationException
 */
private Value evaluate(ListMemberOperator node, BindingSet bindings) throws ValueExprEvaluationException, QueryEvaluationException {
    List<ValueExpr> args = node.getArguments();
    Value leftValue = evaluate(args.get(0), bindings);
    boolean result = false;
    ValueExprEvaluationException typeError = null;
    for (int i = 1; i < args.size(); i++) {
        ValueExpr arg = args.get(i);
        try {
            Value rightValue = evaluate(arg, bindings);
            result = leftValue == null && rightValue == null;
            if (!result) {
                result = QueryEvaluationUtil.compare(leftValue, rightValue, Compare.CompareOp.EQ);
            }
            if (result) {
                break;
            }
        } catch (ValueExprEvaluationException caught) {
            typeError = caught;
        }
    }
    if (typeError != null && !result) {
        // cf. SPARQL spec a type error is thrown if the value is not in the
        // list and one of the list members caused a type error in the
        // comparison.
        throw typeError;
    }
    return BooleanLiteral.valueOf(result);
}
 
Example #12
Source File: RegexAsStringFunctionOptimizer.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void equalsCandidate(Regex node, String regex) {
	final String potential = regex.substring(1, regex.length() - 1);
	if (plain(potential)) {
		ValueConstant vc = new ValueConstant(vf.createLiteral(potential));
		node.replaceWith(new Compare(node.getArg(), vc, Compare.CompareOp.EQ));
	}
}
 
Example #13
Source File: StrictEvaluationStrategy.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public Value evaluate(Compare node, BindingSet bindings)
		throws QueryEvaluationException {
	Value leftVal = evaluate(node.getLeftArg(), bindings);
	Value rightVal = evaluate(node.getRightArg(), bindings);

	return BooleanLiteral.valueOf(QueryEvaluationUtil.compare(leftVal, rightVal, node.getOperator()));
}
 
Example #14
Source File: SPARQLValueExprRenderer.java    From semagrow with Apache License 2.0 5 votes vote down vote up
/**
 * @inheritDoc
 */
@Override
public void meet(Compare theOp)
        throws Exception
{
    mBuffer.append("(");
    theOp.getLeftArg().visit(this);
    mBuffer.append(" ").append(theOp.getOperator().getSymbol()).append(" ");
    theOp.getRightArg().visit(this);
    mBuffer.append(")");
}
 
Example #15
Source File: FilterUtils.java    From CostFed with GNU Affero General Public License v3.0 5 votes vote down vote up
protected static void append(ValueExpr expr, StringBuilder sb) throws FilterConversionException {
	if (expr instanceof Compare) {
		append((Compare)expr, sb);
	} else if (expr instanceof Var) {
		append((Var)expr, sb);
	} else if (expr instanceof ValueConstant) {
		append((ValueConstant)expr, sb);
	} else if (expr instanceof Regex) {
	    append((Regex)expr, sb);
	} else {
		// TODO add more!
		throw new FilterConversionException("Expression type not supported, fallback to sesame evaluation: " + expr.getClass().getCanonicalName());
	}
}
 
Example #16
Source File: FilterUtils.java    From CostFed with GNU Affero General Public License v3.0 5 votes vote down vote up
protected static void append(Compare cmp, StringBuilder sb) throws FilterConversionException {

		sb.append("( ");
		append(cmp.getLeftArg(), sb);
		sb.append(" ").append(cmp.getOperator().getSymbol()).append(" ");
		append(cmp.getRightArg(), sb);
		sb.append(" )");
	}
 
Example #17
Source File: FilterOptimizer.java    From CostFed with GNU Affero General Public License v3.0 5 votes vote down vote up
private void handleFilter(FilterTuple filterTuple, FilterExpr expr) {
	
	/*
	 * CompareEQ expressions are inserted as bindings if possible
	 * 
	 * if the filtertuple contains all vars of the filterexpr, we
	 * can evaluate the filter expr safely on the filterTuple
	 * 
	 * if there is no intersection of variables, the filter is 
	 * irrelevant for this expr
	 * 
	 * if there is some intersection, we cannot remove the filter
	 * and have to keep it in the query plan for postfiltering
	 */
	int intersected = 0;
	for (String filterVar : expr.getVars()) {
		if (filterTuple.getFreeVars().contains(filterVar))
			intersected++;
	}
	
	// filter expression is irrelevant
	if (intersected==0)
		return;
	
	// push eq comparison into stmt as bindings
	if (expr.isCompareEq()) {
		
		if (handleCompare(filterTuple, (Compare)expr.getExpression()))
			return;
	}
	
	// filter contains all variables => push filter
	if (intersected==expr.getVars().size())
		filterTuple.addFilterExpr(expr);
	
	// filter is still needed for post filtering
	else {
		canRemove=false;
	}
}
 
Example #18
Source File: QueryAlgebraUtil.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Construct the statement string, i.e. "s p ?o_varID FILTER ?o_N=o ". This kind of statement pattern is necessary
 * to later on identify available results.
 *
 * @param stmt
 * @param varID
 * @param varNames
 * @param bindings
 * @return the expression
 */
protected static TupleExpr constructStatementCheckId(StatementPattern stmt, int varID, Set<String> varNames,
		BindingSet bindings) {

	String _varID = Integer.toString(varID);
	Var subj = appendVarId(stmt.getSubjectVar(), _varID, varNames, bindings);
	Var pred = appendVarId(stmt.getPredicateVar(), _varID, varNames, bindings);

	Var obj = new Var("o_" + _varID);
	varNames.add("o_" + _varID);

	Value objValue;
	if (stmt.getObjectVar().hasValue()) {
		objValue = stmt.getObjectVar().getValue();
	} else if (bindings.hasBinding(stmt.getObjectVar().getName())) {
		objValue = bindings.getBinding(stmt.getObjectVar().getName()).getValue();
	} else {
		// just to make sure that we see an error, will be deleted soon
		throw new RuntimeException("Unexpected.");
	}

	Compare cmp = new Compare(obj, new ValueConstant(objValue));
	cmp.setOperator(CompareOp.EQ);
	Filter filter = new Filter(new StatementPattern(subj, pred, obj), cmp);

	return filter;
}
 
Example #19
Source File: FilterUtils.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected static void append(ValueExpr expr, StringBuilder sb) throws FilterConversionException {

		if (expr instanceof Compare) {
			append((Compare) expr, sb);
		} else if (expr instanceof Var) {
			append((Var) expr, sb);
		} else if (expr instanceof ValueConstant) {
			append((ValueConstant) expr, sb);
		} else {
			// TODO add more!
			throw new FilterConversionException("Expression type not supported, fallback to sesame evaluation: "
					+ expr.getClass().getCanonicalName());
		}

	}
 
Example #20
Source File: FilterUtils.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected static void append(Compare cmp, StringBuilder sb) throws FilterConversionException {

		sb.append("( ");
		append(cmp.getLeftArg(), sb);
		sb.append(" ").append(cmp.getOperator().getSymbol()).append(" ");
		append(cmp.getRightArg(), sb);
		sb.append(" )");
	}
 
Example #21
Source File: SpinRenderer.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void meet(Compare node) throws RDFHandlerException {
	Resource currentSubj = subject;
	flushPendingStatement();
	handler.handleStatement(valueFactory.createStatement(subject, RDF.TYPE, toValue(node.getOperator())));
	predicate = SP.ARG1_PROPERTY;
	node.getLeftArg().visit(this);
	predicate = SP.ARG2_PROPERTY;
	node.getRightArg().visit(this);
	subject = currentSubj;
	predicate = null;
}
 
Example #22
Source File: FilterExpr.java    From CostFed with GNU Affero General Public License v3.0 4 votes vote down vote up
public boolean isCompareEq() {
	return expr instanceof Compare && ((Compare)expr).getOperator()==CompareOp.EQ;
}
 
Example #23
Source File: InnerJoinPredicate.java    From semagrow with Apache License 2.0 4 votes vote down vote up
public ValueExpr asExpr() {
    return new Compare(getFrom(), getTo(), Compare.CompareOp.EQ);
}
 
Example #24
Source File: LeftJoinPredicate.java    From semagrow with Apache License 2.0 4 votes vote down vote up
public ValueExpr asExpr() {
    return new Compare(getFrom(), getTo(), Compare.CompareOp.EQ);
}
 
Example #25
Source File: HalyardValueExprEvaluation.java    From Halyard with Apache License 2.0 4 votes vote down vote up
/**
 * Determines which evaluate method to call based on the type of {@link ValueExpr}
 * @param expr the expression to evaluate
 * @param bindings the set of named value bindings the set of named value bindings
 * @return the {@link Value} resulting from the evaluation
 * @throws ValueExprEvaluationException
 * @throws QueryEvaluationException
 */
Value evaluate(ValueExpr expr, BindingSet bindings) throws ValueExprEvaluationException, QueryEvaluationException {
    if (expr instanceof Var) {
        return evaluate((Var) expr, bindings);
    } else if (expr instanceof ValueConstant) {
        return evaluate((ValueConstant) expr, bindings);
    } else if (expr instanceof BNodeGenerator) {
        return evaluate((BNodeGenerator) expr, bindings);
    } else if (expr instanceof Bound) {
        return evaluate((Bound) expr, bindings);
    } else if (expr instanceof Str) {
        return evaluate((Str) expr, bindings);
    } else if (expr instanceof Label) {
        return evaluate((Label) expr, bindings);
    } else if (expr instanceof Lang) {
        return evaluate((Lang) expr, bindings);
    } else if (expr instanceof LangMatches) {
        return evaluate((LangMatches) expr, bindings);
    } else if (expr instanceof Datatype) {
        return evaluate((Datatype) expr, bindings);
    } else if (expr instanceof Namespace) {
        return evaluate((Namespace) expr, bindings);
    } else if (expr instanceof LocalName) {
        return evaluate((LocalName) expr, bindings);
    } else if (expr instanceof IsResource) {
        return evaluate((IsResource) expr, bindings);
    } else if (expr instanceof IsURI) {
        return evaluate((IsURI) expr, bindings);
    } else if (expr instanceof IsBNode) {
        return evaluate((IsBNode) expr, bindings);
    } else if (expr instanceof IsLiteral) {
        return evaluate((IsLiteral) expr, bindings);
    } else if (expr instanceof IsNumeric) {
        return evaluate((IsNumeric) expr, bindings);
    } else if (expr instanceof IRIFunction) {
        return evaluate((IRIFunction) expr, bindings);
    } else if (expr instanceof Regex) {
        return evaluate((Regex) expr, bindings);
    } else if (expr instanceof Coalesce) {
        return evaluate((Coalesce) expr, bindings);
    } else if (expr instanceof Like) {
        return evaluate((Like) expr, bindings);
    } else if (expr instanceof FunctionCall) {
        return evaluate((FunctionCall) expr, bindings);
    } else if (expr instanceof And) {
        return evaluate((And) expr, bindings);
    } else if (expr instanceof Or) {
        return evaluate((Or) expr, bindings);
    } else if (expr instanceof Not) {
        return evaluate((Not) expr, bindings);
    } else if (expr instanceof SameTerm) {
        return evaluate((SameTerm) expr, bindings);
    } else if (expr instanceof Compare) {
        return evaluate((Compare) expr, bindings);
    } else if (expr instanceof MathExpr) {
        return evaluate((MathExpr) expr, bindings);
    } else if (expr instanceof In) {
        return evaluate((In) expr, bindings);
    } else if (expr instanceof CompareAny) {
        return evaluate((CompareAny) expr, bindings);
    } else if (expr instanceof CompareAll) {
        return evaluate((CompareAll) expr, bindings);
    } else if (expr instanceof Exists) {
        return evaluate((Exists) expr, bindings);
    } else if (expr instanceof If) {
        return evaluate((If) expr, bindings);
    } else if (expr instanceof ListMemberOperator) {
        return evaluate((ListMemberOperator) expr, bindings);
    } else if (expr == null) {
        throw new IllegalArgumentException("expr must not be null");
    } else {
        throw new QueryEvaluationException("Unsupported value expr type: " + expr.getClass());
    }
}
 
Example #26
Source File: TupleExprBuilder.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public Compare visit(ASTCompare node, Object data) throws VisitorException {
	ValueExpr leftArg = (ValueExpr) node.jjtGetChild(0).jjtAccept(this, null);
	ValueExpr rightArg = (ValueExpr) node.jjtGetChild(1).jjtAccept(this, null);
	return new Compare(leftArg, rightArg, node.getOperator());
}
 
Example #27
Source File: ValueExprFactory.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private static Compare compare(ValueExpr theLeft, ValueExpr theRight, Compare.CompareOp theOp) {
	return new Compare(theLeft, theRight, theOp);
}
 
Example #28
Source File: ValueExprFactory.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private static Compare compare(String theVar, String theValue, Compare.CompareOp theOp) {
	return compare(new Var(theVar), new Var(theValue), theOp);
}
 
Example #29
Source File: ValueExprFactory.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private static Compare compare(String theVar, Value theValue, Compare.CompareOp theOp) {
	return compare(new Var(theVar), new ValueConstant(theValue), theOp);
}
 
Example #30
Source File: ValueExprFactory.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public static Compare ge(String theVar, Value theValue) {
	return compare(theVar, theValue, Compare.CompareOp.GE);
}