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

The following examples show how to use org.eclipse.rdf4j.query.algebra.Var. 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: ServiceJoinIterator.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
protected void handleBindings() throws Exception {
	Var serviceRef = service.getServiceRef();

	String serviceUri;
	if (serviceRef.hasValue()) {
		serviceUri = serviceRef.getValue().stringValue();
	} else {
		// case 2: the service ref is not defined beforehand
		// => use a fallback to the naive evaluation.
		// exceptions occurring here must NOT be silenced!
		while (!isClosed() && leftIter.hasNext()) {
			addResult(strategy.evaluate(service, leftIter.next()));
		}
		return;
	}

	// use vectored evaluation
	FederatedService fs = strategy.getService(serviceUri);
	addResult(fs.evaluate(service, leftIter, service.getBaseURI()));
}
 
Example #2
Source File: TupleExprBuilder.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private List<StatementPattern> replaceSameTermVars(List<StatementPattern> statementPatterns,
		Set<SameTerm> sameTermConstraints) {
	if (sameTermConstraints != null) {
		for (SameTerm st : sameTermConstraints) {
			Var left = (Var) st.getLeftArg();
			Var right = (Var) st.getRightArg();
			for (StatementPattern sp : statementPatterns) {
				Var subj = sp.getSubjectVar();
				Var obj = sp.getObjectVar();

				if (subj.equals(left) || subj.equals(right)) {
					if (obj.equals(left) || obj.equals(right)) {
						sp.setObjectVar(subj);
					}
				}
			}
		}
	}
	return statementPatterns;
}
 
Example #3
Source File: AntecedentVisitorTest.java    From rya with Apache License 2.0 6 votes vote down vote up
@Test
public void testSelectQuery() throws Exception {
    String text = "PREFIX foaf: <" + FOAF.NAMESPACE + ">\n"
            + "SELECT * WHERE {\n"
            + "  ?x a foaf:Person .\n"
            + "  ?y a foaf:Person .\n"
            + "  ?x foaf:knows ?y .\n"
            + "}";
    ParsedQuery query = new SPARQLParser().parseQuery(text, null);
    AntecedentVisitor visitor = new AntecedentVisitor();
    query.getTupleExpr().visit(visitor);
    Set<StatementPattern> expected = Sets.newHashSet(
            new StatementPattern(new Var("x"), c(RDF.TYPE), c(FOAF.PERSON)),
            new StatementPattern(new Var("y"), c(RDF.TYPE), c(FOAF.PERSON)),
            new StatementPattern(new Var("x"), c(FOAF.KNOWS), new Var("y")));
    Assert.assertEquals(expected, visitor.getAntecedents());
}
 
Example #4
Source File: SomeValuesFromVisitorTest.java    From rya with Apache License 2.0 6 votes vote down vote up
@Test
public void testSomeValuesFromDisabled() throws Exception {
    // Disable someValuesOf inference
    final AccumuloRdfConfiguration disabledConf = conf.clone();
    disabledConf.setInferSomeValuesFrom(false);
    // Configure a mock instance engine with an ontology:
    final InferenceEngine inferenceEngine = mock(InferenceEngine.class);
    Map<Resource, Set<IRI>> personSVF = new HashMap<>();
    personSVF.put(gradCourse, Sets.newHashSet(takesCourse));
    personSVF.put(course, Sets.newHashSet(takesCourse));
    personSVF.put(department, Sets.newHashSet(headOf));
    personSVF.put(organization, Sets.newHashSet(worksFor, headOf));
    when(inferenceEngine.getSomeValuesFromByRestrictionType(person)).thenReturn(personSVF);
    // Query for a specific type visit -- should not change
    StatementPattern originalSP = new StatementPattern(new Var("s"), new Var("p", RDF.TYPE), new Var("o", person));
    final Projection originalQuery = new Projection(originalSP, new ProjectionElemList(new ProjectionElem("s", "subject")));
    final Projection modifiedQuery = originalQuery.clone();
    modifiedQuery.visit(new SomeValuesFromVisitor(disabledConf, inferenceEngine));
    Assert.assertEquals(originalQuery, modifiedQuery);
}
 
Example #5
Source File: SimilarVarJoinOptimizer.java    From rya with Apache License 2.0 6 votes vote down vote up
protected List<TupleExpr> getExprsWithSameVars(List<TupleExpr> expressions, TupleExpr last) {
    if(last == null)
        return expressions;
    List<TupleExpr> retExprs = new ArrayList<TupleExpr>();
    for(TupleExpr tupleExpr : expressions) {
        List<Var> statementPatternVars = getStatementPatternVars(tupleExpr);
        List<Var> lastVars = getStatementPatternVars(last);
        statementPatternVars.retainAll(lastVars);
        if(statementPatternVars.size() > 0) {
            retExprs.add(tupleExpr);
        }
    }
    if(retExprs.size() == 0) {
        return expressions;
    }
    return retExprs;
}
 
Example #6
Source File: MemorySailStore.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public synchronized void observe(Resource subj, IRI pred, Value obj, Resource... contexts)
		throws SailException {
	if (observations == null) {
		observations = new HashSet<>();
	}
	if (contexts == null) {
		observations.add(new StatementPattern(new Var("s", subj), new Var("p", pred), new Var("o", obj),
				new Var("g", null)));
	} else if (contexts.length == 0) {
		observations.add(new StatementPattern(new Var("s", subj), new Var("p", pred), new Var("o", obj)));
	} else {
		for (Resource ctx : contexts) {
			observations.add(new StatementPattern(new Var("s", subj), new Var("p", pred), new Var("o", obj),
					new Var("g", ctx)));
		}
	}
}
 
Example #7
Source File: SailSourceBranch.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void prepare(Changeset change, SailSink sink) throws SailException {
	Set<StatementPattern> observations = change.getObservations();
	if (observations != null) {
		for (StatementPattern p : observations) {
			Resource subj = (Resource) p.getSubjectVar().getValue();
			IRI pred = (IRI) p.getPredicateVar().getValue();
			Value obj = p.getObjectVar().getValue();
			Var ctxVar = p.getContextVar();
			if (ctxVar == null) {
				sink.observe(subj, pred, obj);
			} else {
				sink.observe(subj, pred, obj, (Resource) ctxVar.getValue());
			}
		}
	}
}
 
Example #8
Source File: Changeset.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public synchronized void observe(Resource subj, IRI pred, Value obj, Resource... contexts)
		throws SailConflictException {
	if (observations == null) {
		observations = new HashSet<>();
	}
	if (contexts == null) {
		observations.add(new StatementPattern(new Var("s", subj), new Var("p", pred), new Var("o", obj),
				new Var("g", null)));
	} else if (contexts.length == 0) {
		observations.add(new StatementPattern(new Var("s", subj), new Var("p", pred), new Var("o", obj)));
	} else {
		for (Resource ctx : contexts) {
			observations.add(new StatementPattern(new Var("s", subj), new Var("p", pred), new Var("o", obj),
					new Var("g", ctx)));
		}
	}
}
 
Example #9
Source File: Changeset.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void prepare() throws SailException {
	if (prepend != null && observations != null) {
		for (StatementPattern p : observations) {
			Resource subj = (Resource) p.getSubjectVar().getValue();
			IRI pred = (IRI) p.getPredicateVar().getValue();
			Value obj = p.getObjectVar().getValue();
			Var ctxVar = p.getContextVar();
			Resource[] contexts;
			if (ctxVar == null) {
				contexts = new Resource[0];
			} else {
				contexts = new Resource[] { (Resource) ctxVar.getValue() };
			}
			for (Changeset changeset : prepend) {
				if (changeset.hasApproved(subj, pred, obj, contexts)
						|| (changeset.hasDeprecated(subj, pred, obj, contexts))) {
					throw new SailConflictException("Observed State has Changed");
				}
			}
		}
	}
}
 
Example #10
Source File: EvaluationStrategyWithRDFStarTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Before
public void setUp() throws Exception {
	// prepare data
	triples.clear();
	triples.add(vf.createTriple(vf.createIRI("urn:a"), vf.createIRI("urn:p"), vf.createIRI("urn:b")));
	triples.add(vf.createTriple(vf.createIRI("urn:a"), vf.createIRI("urn:q"), vf.createIRI("urn:b:1")));
	triples.add(vf.createTriple(vf.createIRI("urn:a:1"), vf.createIRI("urn:p"), vf.createIRI("urn:b")));
	triples.add(vf.createTriple(vf.createIRI("urn:a:2"), vf.createIRI("urn:q"), vf.createIRI("urn:c")));

	baseSource = new CommonBaseSource();

	tripleRefNode = new TripleRef();
	tripleRefNode.setSubjectVar(new Var("s"));
	tripleRefNode.setPredicateVar(new Var("p"));
	tripleRefNode.setObjectVar(new Var("o"));
	tripleRefNode.setExprVar(new Var("extern"));

	strategy = new StrictEvaluationStrategy(createSource(), null);
}
 
Example #11
Source File: HalyardEvaluationStatistics.java    From Halyard with Apache License 2.0 6 votes vote down vote up
@Override
protected double getCardinality(StatementPattern sp) {
    //always preffer HALYARD.SEARCH_TYPE object literals to move such statements higher in the joins tree
    Var objectVar = sp.getObjectVar();
    if (objectVar.hasValue() && (objectVar.getValue() instanceof Literal) && HALYARD.SEARCH_TYPE.equals(((Literal) objectVar.getValue()).getDatatype())) {
        return 0.0001;
    }
    Double card = spcalc == null ? null : spcalc.getCardinality(sp, boundVars);
    if (card == null) { //fallback to default cardinality calculation
        card = (hasValue(sp.getSubjectVar(), boundVars) ? 1.0 : 10.0) * (hasValue(sp.getPredicateVar(), boundVars) ? 1.0 : 10.0) * (hasValue(sp.getObjectVar(), boundVars) ? 1.0 : 10.0) * (hasValue(sp.getContextVar(), boundVars) ? 1.0 : 10.0);
    }
    for (Var v : sp.getVarList()) {
        //decrease cardinality for each priority variable present
        if (v != null && priorityVariables.contains(v.getName())) card /= 1000000.0;
    }
    return card;
}
 
Example #12
Source File: SparqlTripleSource.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public boolean hasStatements(Resource subj,
		IRI pred, Value obj, QueryInfo queryInfo, Resource... contexts)
		throws RepositoryException {

	if (!useASKQueries) {
		StatementPattern st = new StatementPattern(new Var("s", subj), new Var("p", pred), new Var("o", obj));
		Dataset dataset = FedXUtil.toDataset(contexts);
		try {
			return hasStatements(st, EmptyBindingSet.getInstance(), queryInfo, dataset);
		} catch (Exception e) {
			throw new RepositoryException(e);
		}
	}
	return super.hasStatements(subj, pred, obj, queryInfo, contexts);
}
 
Example #13
Source File: GeoParseUtils.java    From rya with Apache License 2.0 6 votes vote down vote up
/**
 * Extracts the arguments used in a {@link FunctionCall}.
 * @param matchName - The variable name to match to arguments used in the {@link FunctionCall}.
 * @param call - The {@link FunctionCall} to match against.
 * @return - The {@link Value}s matched.
 */
public static Object[] extractArguments(final String matchName, final FunctionCall call) {
    final Object[] args = new Object[call.getArgs().size() - 1];
    int argI = 0;
    for (int i = 0; i != call.getArgs().size(); ++i) {
        final ValueExpr arg = call.getArgs().get(i);
        if (argI == i && arg instanceof Var && matchName.equals(((Var)arg).getName())) {
            continue;
        }
        if (arg instanceof ValueConstant) {
            args[argI] = ((ValueConstant)arg).getValue();
        } else if (arg instanceof Var && ((Var)arg).hasValue()) {
            args[argI] = ((Var)arg).getValue();
        } else {
            args[argI] = arg;
        }
        ++argI;
    }
    return args;
}
 
Example #14
Source File: AntecedentVisitorTest.java    From rya with Apache License 2.0 6 votes vote down vote up
@Test
public void testConstructQuery() throws Exception {
    String text = "PREFIX foaf: <" + FOAF.NAMESPACE + ">\n"
            + "CONSTRUCT {\n"
            + "  ?y foaf:knows ?x .\n"
            + "  ?y <urn:knows> ?x .\n"
            + "  ?x <urn:knows> ?y .\n"
            + "} WHERE {\n"
            + "  ?x a foaf:Person .\n"
            + "  ?y a foaf:Person .\n"
            + "  ?x foaf:knows ?y .\n"
            + "}";
    ParsedQuery query = new SPARQLParser().parseQuery(text, null);
    AntecedentVisitor visitor = new AntecedentVisitor();
    query.getTupleExpr().visit(visitor);
    Set<StatementPattern> expected = Sets.newHashSet(
            new StatementPattern(new Var("x"), c(RDF.TYPE), c(FOAF.PERSON)),
            new StatementPattern(new Var("y"), c(RDF.TYPE), c(FOAF.PERSON)),
            new StatementPattern(new Var("x"), c(FOAF.KNOWS), new Var("y")));
    Assert.assertEquals(expected, visitor.getAntecedents());
}
 
Example #15
Source File: SameTermFilterOptimizer.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void renameVar(Var oldVar, Var newVar, Filter filter) {
	filter.getArg().visit(new VarRenamer(oldVar, newVar));

	// TODO: skip this step if old variable name is not used
	// Replace SameTerm-filter with an Extension, the old variable name
	// might still be relevant to nodes higher in the tree
	Extension extension = new Extension(filter.getArg());
	extension.addElement(new ExtensionElem(new Var(newVar.getName()), oldVar.getName()));
	filter.replaceWith(extension);
}
 
Example #16
Source File: QueryModelBuilder.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public Var visit(ASTEdge node, Object data) throws VisitorException {
	ValueExpr arg = (ValueExpr) node.getValueExpr().jjtAccept(this, null);

	if (arg instanceof Var) {
		return (Var) arg;
	} else if (arg instanceof ValueConstant) {
		ValueConstant vc = (ValueConstant) arg;
		return createConstantVar(vc.getValue());
	} else {
		throw new IllegalArgumentException("Unexpected edge argument type: " + arg.getClass());
	}
}
 
Example #17
Source File: DistanceQuerySpec.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public DistanceQuerySpec(Literal from, IRI units, double dist, String distVar, IRI geoProperty, String geoVar,
		String subjectVar, Var contextVar) {
	this.from = from;
	this.units = units;
	this.distance = dist;
	this.distanceVar = distVar;
	this.geoProperty = geoProperty;
	this.geoVar = geoVar;
	this.subjectVar = subjectVar;
	this.contextVar = contextVar;
	this.distanceFunction = null;
	this.distanceExpr = null;
	this.filter = null;
}
 
Example #18
Source File: GroupIteratorTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testSumNotZero() throws QueryEvaluationException {
	Group group = new Group(NONEMPTY_ASSIGNMENT);
	group.addGroupElement(new GroupElem("sum", new Sum(new Var("a"))));
	GroupIterator gi = new GroupIterator(evaluator, group, EmptyBindingSet.getInstance());

	assertThat(gi.next().getBinding("sum").getValue()).isEqualTo(vf.createLiteral("45", XMLSchema.INTEGER));
}
 
Example #19
Source File: HalyardValueExprEvaluation.java    From Halyard with Apache License 2.0 5 votes vote down vote up
/**
 * Evaluate a {@link Var} query model node.
 * @param var
 * @param bindings the set of named value bindings
 * @return the result of {@link Var#getValue()} from either {@code var}, or if {@code null}, from the {@ bindings}
 * @throws ValueExprEvaluationException
 * @throws QueryEvaluationException
 */
private Value evaluate(Var var, BindingSet bindings) throws ValueExprEvaluationException, QueryEvaluationException {
    Value value = var.getValue();
    if (value == null) {
        value = bindings.getValue(var.getName());
    }
    if (value == null) {
        throw new ValueExprEvaluationException();
    }
    return value;
}
 
Example #20
Source File: SparqlTupleExprRenderer.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void ctxOpen(TupleExpr theExpr) {
	Var aContext = mContexts.get(theExpr);

	if (aContext != null) {
		mJoinBuffer.append(indent()).append("GRAPH ");
		if (aContext.hasValue()) {
			mJoinBuffer.append(RenderUtils.getSPARQLQueryString(aContext.getValue()));
		} else {
			mJoinBuffer.append("?").append(aContext.getName());
		}
		mJoinBuffer.append(" {\n");
		mIndent += 2;
	}
}
 
Example #21
Source File: GeoTemporalIndexSetProvider.java    From rya with Apache License 2.0 5 votes vote down vote up
private List<EventQueryNode> createNodes() {
    final List<EventQueryNode> nodes = new ArrayList<>();
    for(final Var subj : patternMap.keySet()) {
        final EventQueryNode node = getGeoTemporalNode(subj);
        if(node != null) {
            nodes.add(node);
        }
    }
    return nodes;
}
 
Example #22
Source File: QueryMultiJoinOptimizer.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected double getTupleExprCost(TupleExpr tupleExpr, Map<TupleExpr, Double> cardinalityMap,
		Map<TupleExpr, List<Var>> varsMap, Map<Var, Integer> varFreqMap, Set<String> boundVars) {
	double cost = cardinalityMap.get(tupleExpr);

	List<Var> vars = varsMap.get(tupleExpr);

	// Compensate for variables that are bound earlier in the evaluation
	List<Var> unboundVars = getUnboundVars(vars);
	List<Var> constantVars = getConstantVars(vars);
	int nonConstantCount = vars.size() - constantVars.size();
	if (nonConstantCount > 0) {
		double exp = (double) unboundVars.size() / nonConstantCount;
		cost = Math.pow(cost, exp);
	}

	if (unboundVars.isEmpty()) {
		// Prefer patterns with more bound vars
		if (nonConstantCount > 0) {
			cost /= nonConstantCount;
		}
	} else {
		// Prefer patterns that bind variables from other tuple expressions
		int foreignVarFreq = getForeignVarFreq(unboundVars, varFreqMap);
		if (foreignVarFreq > 0) {
			cost /= foreignVarFreq;
		}
	}

	// Prefer patterns that bind more variables
	// List<Var> distinctUnboundVars = getUnboundVars(new
	// HashSet<Var>(vars));
	// if (distinctUnboundVars.size() >= 2) {
	// cardinality /= distinctUnboundVars.size();
	// }

	return cost;
}
 
Example #23
Source File: FilterOptimizer.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void meet(Var var) {
	if (var.getValue() == null) {
		vars.add(var.getName());
	}
	super.meet(var);
}
 
Example #24
Source File: StatementMetadataExternalSetProvider.java    From rya with Apache License 2.0 5 votes vote down vote up
private Set<StatementPattern> removeInvalidProperties(Collection<StatementPattern> patterns) {

        Set<StatementPattern> finalPatterns = new HashSet<>();
        
        for (StatementPattern pattern : patterns) {
            Var var = pattern.getPredicateVar();
            if (var.getValue() != null && var.getValue() instanceof IRI) {
                RyaIRI uri = RdfToRyaConversions.convertIRI((IRI) var.getValue());
                if(expectedURI.contains(uri) || metadataProperties.contains(uri)) {
                    finalPatterns.add(pattern);
                }
            }
        }
        return finalPatterns;
    }
 
Example #25
Source File: ConstructorBuilder.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Gets the set of variables that are relevant for the constructor. This method accumulates all subject, predicate
 * and object variables from the supplied statement patterns, but ignores any context variables.
 */
private Set<Var> getConstructVars(Collection<StatementPattern> statementPatterns) {
	Set<Var> vars = new LinkedHashSet<>(statementPatterns.size() * 2);

	for (StatementPattern sp : statementPatterns) {
		vars.add(sp.getSubjectVar());
		vars.add(sp.getPredicateVar());
		vars.add(sp.getObjectVar());
	}

	return vars;
}
 
Example #26
Source File: SimilarVarJoinOptimizer.java    From rya with Apache License 2.0 5 votes vote down vote up
protected List<Var> getStatementPatternVars(TupleExpr tupleExpr) {
    if(tupleExpr == null)
        return null;
    List<StatementPattern> stPatterns = StatementPatternCollector.process(tupleExpr);
    List<Var> varList = new ArrayList<Var>(stPatterns.size() * 4);
    for (StatementPattern sp : stPatterns) {
        sp.getVars(varList);
    }
    return varList;
}
 
Example #27
Source File: HalyardStatementPatternEvaluation.java    From Halyard with Apache License 2.0 5 votes vote down vote up
protected boolean isUnbound(Var var, BindingSet bindings) {
    if (var == null) {
        return false;
    } else {
        return bindings.hasBinding(var.getName()) && bindings.getValue(var.getName()) == null;
    }
}
 
Example #28
Source File: PathIteration.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected boolean isUnbound(Var var, BindingSet bindings) {
	if (var == null) {
		return false;
	} else {
		return bindings.hasBinding(var.getName()) && bindings.getValue(var.getName()) == null;
	}
}
 
Example #29
Source File: FilterFunctionOptimizer.java    From rya with Apache License 2.0 5 votes vote down vote up
@Override
public void meet(final FunctionCall call) {
    final IRI fnUri = VF.createIRI(call.getURI());
    final Var resultVar = IndexingFunctionRegistry.getResultVarFromFunctionCall(fnUri, call.getArgs());
    if (resultVar != null && resultVar.getName().equals(matchVar)) {
        addFilter(VF.createIRI(call.getURI()), extractArguments(matchVar, call));
        if (call.getParentNode() instanceof Filter || call.getParentNode() instanceof And || call.getParentNode() instanceof LeftJoin) {
            call.replaceWith(new ValueConstant(VF.createLiteral(true)));
        } else {
            throw new IllegalArgumentException("Query error: Found " + call + " as part of an expression that is too complex");
        }
    }
}
 
Example #30
Source File: StatementMetadataNode.java    From rya with Apache License 2.0 5 votes vote down vote up
private Set<String> getVariableNames() {
    final Set<String> vars = new HashSet<>();
    for (final StatementPattern pattern : patterns) {
        for (final Var var : pattern.getVarList()) {
            if (var.getValue() == null) {
                vars.add(var.getName());
            }
        }
    }
    return vars;
}