Java Code Examples for org.eclipse.rdf4j.query.algebra.Filter#getCondition()

The following examples show how to use org.eclipse.rdf4j.query.algebra.Filter#getCondition() . 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: 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 2
Source File: DisjunctiveConstraintOptimizer.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void meet(Filter filter) {
	if (filter.getCondition() instanceof Or && containsSameTerm(filter.getCondition())) {
		Or orNode = (Or) filter.getCondition();
		TupleExpr filterArg = filter.getArg();

		ValueExpr leftConstraint = orNode.getLeftArg();
		ValueExpr rightConstraint = orNode.getRightArg();

		// remove filter
		filter.replaceWith(filterArg);

		// Push UNION down below other filters to avoid cloning them
		TupleExpr node = findNotFilter(filterArg);

		Filter leftFilter = new Filter(node.clone(), leftConstraint);
		Filter rightFilter = new Filter(node.clone(), rightConstraint);
		Union union = new Union(leftFilter, rightFilter);
		node.replaceWith(union);

		filter.getParentNode().visit(this);
	} else {
		super.meet(filter);
	}
}
 
Example 3
Source File: QueryModelNormalizer.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void meet(Filter node) {
	super.meet(node);

	TupleExpr arg = node.getArg();
	ValueExpr condition = node.getCondition();

	if (arg instanceof EmptySet) {
		// see #meetUnaryTupleOperator
	} else if (condition instanceof ValueConstant) {
		boolean conditionValue;
		try {
			conditionValue = QueryEvaluationUtil.getEffectiveBooleanValue(((ValueConstant) condition).getValue());
		} catch (ValueExprEvaluationException e) {
			conditionValue = false;
		}

		if (conditionValue == false) {
			// Constraint is always false
			node.replaceWith(new EmptySet());
		} else {
			node.replaceWith(arg);
		}
	}
}
 
Example 4
Source File: FilterRangeVisitor.java    From rya with Apache License 2.0 6 votes vote down vote up
@Override
public void meet(final Filter node) throws Exception {
    super.meet(node);

    final ValueExpr arg = node.getCondition();
    if (arg instanceof FunctionCall) {
        final FunctionCall fc = (FunctionCall) arg;
        if (RANGE.stringValue().equals(fc.getURI())) {
            //range(?var, start, end)
            final List<ValueExpr> valueExprs = fc.getArgs();
            if (valueExprs.size() != 3) {
                throw new QueryEvaluationException("org.apache:range must have 3 parameters: variable, start, end");
            }
            final Var var = (Var) valueExprs.get(0);
            final ValueConstant startVc = (ValueConstant) valueExprs.get(1);
            final ValueConstant endVc = (ValueConstant) valueExprs.get(2);
            final Value start = startVc.getValue();
            final Value end = endVc.getValue();
            rangeValues.put(var, new RangeValue(start, end));
            node.setCondition(new ValueConstant(BooleanLiteral.TRUE));
        }
    }
}
 
Example 5
Source File: SeparateFilterJoinsVisitor.java    From rya with Apache License 2.0 6 votes vote down vote up
@Override
public void meet(final Filter node) throws Exception {
    super.meet(node);

    final ValueExpr condition = node.getCondition();
    final TupleExpr arg = node.getArg();
    if (!(arg instanceof Join)) {
        return;
    }

    final Join join = (Join) arg;
    final TupleExpr leftArg = join.getLeftArg();
    final TupleExpr rightArg = join.getRightArg();

    if (leftArg instanceof StatementPattern && rightArg instanceof StatementPattern) {
        final Filter left = new Filter(leftArg, condition);
        final Filter right = new Filter(rightArg, condition);
        node.replaceWith(new Join(left, right));
    }

}
 
Example 6
Source File: PeriodicQueryUtil.java    From rya with Apache License 2.0 6 votes vote down vote up
public void meet(Filter node) {
    if (node.getCondition() instanceof FunctionCall) {
        try {
            Optional<PeriodicQueryNode> optNode = getPeriodicQueryNode((FunctionCall) node.getCondition(), node.getArg());
            if (optNode.isPresent()) {
                if (count > 0) {
                    throw new IllegalArgumentException("Query cannot contain more than one PeriodicQueryNode");
                }
                periodicNode = optNode.get();
                node.replaceWith(periodicNode);
                count++;
                periodicNode.visit(this);
            } else {
                super.meet(node);
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    } else {
        super.meet(node);
    }
}
 
Example 7
Source File: QueryRuleset.java    From rya with Apache License 2.0 6 votes vote down vote up
@Override
public void meet(final Filter node) throws QueryRulesetException {
    final ValueExpr condition = node.getCondition();
    // If the condition is a function call, and we don't know about the function, don't try to test for it.
    if (condition instanceof FunctionCall) {
        final String uri = ((FunctionCall) condition).getURI();
        if (FunctionRegistry.getInstance().get(uri) == null) {
            // Just extract statement patterns from the child as if there were no filter.
            node.getArg().visit(this);
        }
    }
    // Otherwise, assume we can test for it: extract rules from below this node, and add the condition to each one.
    else {
        final RulesetVisitor childVisitor = new RulesetVisitor();
        node.getArg().visit(childVisitor);
        for (final CopyRule rule : childVisitor.rules) {
            rule.addCondition(condition);
            rules.add(rule);
        }
        superclasses.addAll(childVisitor.superclasses);
        superproperties.addAll(childVisitor.superproperties);
    }
}
 
Example 8
Source File: GeoRelationQuerySpecBuilder.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static Filter getFilter(QueryModelNode node, String varName) {
	Filter filter = null;
	if (node instanceof Filter) {
		Filter f = (Filter) node;
		ValueExpr condition = f.getCondition();
		if (varName.equals(getVarName(condition))) {
			filter = f;
		}
	} else if (node != null) {
		filter = getFilter(node.getParentNode(), varName);
	}
	return filter;
}
 
Example 9
Source File: TupleExprs.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Verifies if the supplied expression is a FILTER (NOT) EXISTS operation
 *
 * @param expr a tuple expression
 * @return true if the supplied expression is a FILTER (NOT) EXISTS operation, false otherwise.
 */
public static boolean isFilterExistsFunction(TupleExpr expr) {
	if (expr instanceof Filter) {
		Filter filter = (Filter) expr;
		if (filter.getCondition() instanceof Exists) {
			return true;
		} else if (filter.getCondition() instanceof Not) {
			Not n = (Not) filter.getCondition();
			return (n.getArg() instanceof Exists);
		}
	}
	return false;
}
 
Example 10
Source File: SparqlTupleExprRenderer.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * @inheritDoc
 */
@Override
public void meet(final Filter theFilter) throws Exception {
	ctxOpen(theFilter);

	if (theFilter.getArg() != null) {
		theFilter.getArg().visit(this);
	}

	// try and reverse engineer the original scoping intent of the query
	final boolean aNeedsNewScope = theFilter.getParentNode() != null
			&& (theFilter.getParentNode() instanceof Join || theFilter.getParentNode() instanceof LeftJoin);

	String aFilter = renderValueExpr(theFilter.getCondition());
	if (theFilter.getCondition() instanceof ValueConstant || theFilter.getCondition() instanceof Var) {
		// means the filter is something like "filter (true)" or "filter (?v)"
		// so we'll need to wrap it in parens since they can't live
		// in the query w/o them, but we can't always wrap them in parens in
		// the normal renderer

		aFilter = "(" + aFilter + ")";
	}

	mJoinBuffer.append(indent());

	// if (aNeedsNewScope) {
	// mJoinBuffer.append("{ ");
	// }

	mJoinBuffer.append("filter ").append(aFilter).append(".");

	// if (aNeedsNewScope) {
	// mJoinBuffer.append("}.");
	// }

	mJoinBuffer.append("\n");

	ctxClose(theFilter);
}
 
Example 11
Source File: FilterResultUpdater.java    From rya with Apache License 2.0 5 votes vote down vote up
/**
 * Updates the results of a Filter node when one of its child has added a
 * new Binding Set to its results.
 *
 * @param tx - The transaction all Fluo queries will use. (not null)
 * @param childBindingSet - A binding set that the query's child node has emitted. (not null)
 * @param filterMetadata - The metadata of the Filter whose results will be updated. (not null)
 * @throws Exception Something caused the update to fail.
 */
public void updateFilterResults(
        final TransactionBase tx,
        final VisibilityBindingSet childBindingSet,
        final FilterMetadata filterMetadata) throws Exception {
    checkNotNull(tx);
    checkNotNull(childBindingSet);
    checkNotNull(filterMetadata);

    log.trace("Transaction ID: {}\nFilter Node ID: {}\nBinding Set:\n{}\n", tx.getStartTimestamp(), filterMetadata.getNodeId(), childBindingSet);

    // Parse the original query and find the Filter that represents filterId.
    final String sparql = filterMetadata.getFilterSparql();
    final Filter filter = FilterSerializer.deserialize(sparql);

    // Evaluate whether the child BindingSet satisfies the filter's condition.
    final ValueExpr condition = filter.getCondition();
    if (isTrue(condition, childBindingSet)) {

        // Create the Row Key for the emitted binding set. It does not contain visibilities.
        final VariableOrder filterVarOrder = filterMetadata.getVariableOrder();
        final Bytes resultRow = makeRowKey(filterMetadata.getNodeId(), filterVarOrder, childBindingSet);

        // Serialize and emit BindingSet
        final Bytes nodeValueBytes = BS_SERDE.serialize(childBindingSet);
        log.trace("Transaction ID: {}\nNew Binding Set: {}\n", tx.getStartTimestamp(), childBindingSet);

        tx.set(resultRow, FluoQueryColumns.FILTER_BINDING_SET, nodeValueBytes);
    }
}
 
Example 12
Source File: FilterOptimizer.java    From CostFed with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void meet(Filter filter)  {
	
	if (filter.getArg() instanceof EmptyResult) {
		log.debug("Argument of filter expression does not yield results at the provided sources, replacing Filter node.");
		filter.replaceWith(filter.getArg());
		return;
	}
				
	/*
	 * TODO idea:
	 * if we have a FILTER such as ?s='a' OR ?s='b' OR ?s='c' handle this appropriately
	 */
	
	ValueExpr valueExpr = filter.getCondition();
	
	/*
	 * TODO transform condition into some normal form, e.g. CNF
	 */
	
	// determine conjunctive expressions
	List<ValueExpr> conjunctiveExpressions = new ArrayList<ValueExpr>();
	getConjunctiveExpressions(valueExpr, conjunctiveExpressions);
			
	FilterExprInsertVisitor filterExprVst = new FilterExprInsertVisitor();
	List<ValueExpr> remainingExpr = new ArrayList<ValueExpr>(conjunctiveExpressions.size());
	
	for (ValueExpr cond : conjunctiveExpressions) {
		
		/*
		 * Determine if this filter is applicable for optimization.
		 * Currently only leaf expressions are applicable, i.e.
		 * not combined expressions.
		 */
		if (isCompatibleExpr(cond)) {
						
			HashSet<String> exprVars = new VarFinder().findVars(cond);
			FilterExpr filterExpr = new FilterExpr(cond, exprVars);
			
			filterExprVst.initialize(filterExpr);
			filter.getArg().visit(filterExprVst);
			
			// if the filter expr. is handled in the stmt we do not have to keep it
			if (filterExprVst.canRemove())
				continue;
			
			remainingExpr.add(filterExpr.getExpression());
			
		} else {
			remainingExpr.add(cond);
		}
		
	}
	
	if (remainingExpr.size()==0) {
		filter.replaceWith(filter.getArg()); 	// remove the filter			
	}
	
	else if (remainingExpr.size()==1) {
		filter.setCondition(remainingExpr.get(0));		// just apply the remaining condition
	}
	
	else {
		
		// construct conjunctive value expr
		And root = new And();	
		root.setLeftArg(remainingExpr.get(0));
		And tmp = root;
		for (int i=1; i<remainingExpr.size()-1; i++) {
			And _a = new And();
			_a.setLeftArg(remainingExpr.get(i));
			tmp.setRightArg(_a);
			tmp = _a;				
		}
		tmp.setRightArg(remainingExpr.get(remainingExpr.size()-1));
		
		filter.setCondition(root);
	}
	
}
 
Example 13
Source File: FilterOptimizer.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public void meet(Filter filter) {

	if (filter.getArg() instanceof EmptyResult) {
		log.debug(
				"Argument of filter expression does not yield results at the provided sources, replacing Filter node.");
		filter.replaceWith(filter.getArg());
		return;
	}

	/*
	 * TODO idea: if we have a FILTER such as ?s='a' OR ?s='b' OR ?s='c' handle this appropriately
	 */

	ValueExpr valueExpr = filter.getCondition();

	/*
	 * TODO transform condition into some normal form, e.g. CNF
	 */

	// determine conjunctive expressions
	List<ValueExpr> conjunctiveExpressions = new ArrayList<>();
	getConjunctiveExpressions(valueExpr, conjunctiveExpressions);

	FilterExprInsertVisitor filterExprVst = new FilterExprInsertVisitor();
	List<ValueExpr> remainingExpr = new ArrayList<>(conjunctiveExpressions.size());

	for (ValueExpr cond : conjunctiveExpressions) {

		/*
		 * Determine if this filter is applicable for optimization. Currently only leaf expressions are applicable,
		 * i.e. not combined expressions.
		 */
		if (isCompatibleExpr(cond)) {

			HashSet<String> exprVars = new VarFinder().findVars(cond);
			FilterExpr filterExpr = new FilterExpr(cond, exprVars);

			filterExprVst.initialize(filterExpr);
			filter.getArg().visit(filterExprVst);

			// if the filter expr. is handled in the stmt we do not have to keep it
			if (filterExprVst.canRemove()) {
				continue;
			}

			remainingExpr.add(filterExpr.getExpression());

		} else {
			remainingExpr.add(cond);
		}

	}

	if (remainingExpr.isEmpty()) {
		filter.replaceWith(filter.getArg()); // remove the filter
	} else if (remainingExpr.size() == 1) {
		filter.setCondition(remainingExpr.get(0)); // just apply the remaining condition
	} else {

		// construct conjunctive value expr
		And root = new And();
		root.setLeftArg(remainingExpr.get(0));
		And tmp = root;
		for (int i = 1; i < remainingExpr.size() - 1; i++) {
			And _a = new And();
			_a.setLeftArg(remainingExpr.get(i));
			tmp.setRightArg(_a);
			tmp = _a;
		}
		tmp.setRightArg(remainingExpr.get(remainingExpr.size() - 1));

		filter.setCondition(root);
	}

}
 
Example 14
Source File: SameTermFilterOptimizer.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public void meet(Filter filter) {
	super.meet(filter);

	if (filter.getCondition() instanceof SameTerm) {
		// SameTerm applies to the filter's argument
		SameTerm sameTerm = (SameTerm) filter.getCondition();
		TupleExpr filterArg = filter.getArg();

		ValueExpr leftArg = sameTerm.getLeftArg();
		ValueExpr rightArg = sameTerm.getRightArg();

		// Verify that vars are (potentially) bound by filterArg
		Set<String> bindingNames = filterArg.getBindingNames();
		if (isUnboundVar(leftArg, bindingNames) || isUnboundVar(rightArg, bindingNames)) {
			// One or both var(s) are unbound, this expression will never
			// return any results
			filter.replaceWith(new EmptySet());
			return;
		}

		Set<String> assuredBindingNames = filterArg.getAssuredBindingNames();
		if (isUnboundVar(leftArg, assuredBindingNames) || isUnboundVar(rightArg, assuredBindingNames)) {
			// One or both var(s) are potentially unbound, inlining could
			// invalidate the result e.g. in case of left joins
			return;
		}

		if (leftArg instanceof Var || rightArg instanceof Var) {
			if (filterArg instanceof ArbitraryLengthPath && leftArg instanceof Var && rightArg instanceof Var) {
				final ArbitraryLengthPath alp = (ArbitraryLengthPath) filterArg;
				final List<Var> sameTermArgs = Arrays.asList((Var) leftArg, (Var) rightArg);

				if (sameTermArgs.contains(alp.getSubjectVar()) && sameTermArgs.contains(alp.getObjectVar())) {
					// SameTerm provides a deferred mapping to allow arbitrary-length property path to produce
					// cyclic paths. See SES-1685.
					// we can not inline.
					return;
				}
			}

			BindingSetAssignmentCollector collector = new BindingSetAssignmentCollector();
			filterArg.visit(collector);

			for (BindingSetAssignment bsa : collector.getBindingSetAssignments()) {
				// check if the VALUES clause / bindingsetassignment contains
				// one of the arguments of the sameTerm.
				// if so, we can not inline.
				Set<String> names = bsa.getAssuredBindingNames();
				if (leftArg instanceof Var) {
					if (names.contains(((Var) leftArg).getName())) {
						return;
					}
				}
				if (rightArg instanceof Var) {
					if (names.contains(((Var) rightArg).getName())) {
						return;
					}
				}
			}
		}

		Value leftValue = getValue(leftArg);
		Value rightValue = getValue(rightArg);

		if (leftValue != null && rightValue != null) {
			// ConstantOptimizer should have taken care of this
		} else if (leftValue != null && rightArg instanceof Var) {
			bindVar((Var) rightArg, leftValue, filter);
		} else if (rightValue != null && leftArg instanceof Var) {
			bindVar((Var) leftArg, rightValue, filter);
		} else if (leftArg instanceof Var && rightArg instanceof Var) {
			// Two unbound variables, rename rightArg to leftArg
			renameVar((Var) rightArg, (Var) leftArg, filter);
		}
	}
}
 
Example 15
Source File: SPARQLTupleExprRenderer.java    From semagrow with Apache License 2.0 4 votes vote down vote up
/**
 * @inheritDoc
 */
@Override
public void meet(final Filter theFilter)
        throws Exception
{
    ctxOpen(theFilter);

    if (theFilter.getArg() != null) {
        theFilter.getArg().visit(this);
    }

    // try and reverse engineer the original scoping intent of the query
    final boolean aNeedsNewScope = theFilter.getParentNode() != null
            && (theFilter.getParentNode() instanceof Join || theFilter.getParentNode() instanceof LeftJoin);

    String aFilter = renderValueExpr(theFilter.getCondition());
    if (theFilter.getCondition() instanceof ValueConstant || theFilter.getCondition() instanceof Var) {
        // means the filter is something like "filter (true)" or "filter (?v)"
        // so we'll need to wrap it in parens since they can't live
        // in the query w/o them, but we can't always wrap them in parens in
        // the normal renderer

        aFilter = "(" + aFilter + ")";
    }

    mJoinBuffer.append(indent());

    // if (aNeedsNewScope) {
    // mJoinBuffer.append("{ ");
    // }

    mJoinBuffer.append("filter ").append(aFilter).append(".");

    // if (aNeedsNewScope) {
    // mJoinBuffer.append("}.");
    // }

    mJoinBuffer.append("\n");

    ctxClose(theFilter);
}
 
Example 16
Source File: FilterEvaluator.java    From rya with Apache License 2.0 2 votes vote down vote up
/**
 * Make a {@link FilterEvaluator} that processes the logic of a {@link Filter}.
 *
 * @param filter - Defines the Filter that will be processed. (not null)
 * @return The {@link FilterEvaluator} for the provided {@link Filter}.
 */
public static FilterEvaluator make(final Filter filter) {
    requireNonNull(filter);
    final ValueExpr condition = filter.getCondition();
    return new FilterEvaluator(condition);
}