Java Code Examples for org.eclipse.rdf4j.query.algebra.Var#hasValue()

The following examples show how to use org.eclipse.rdf4j.query.algebra.Var#hasValue() . 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: FederationEvalStrategy.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Evaluate a SERVICE using vectored evaluation, taking the provided bindings as input.
 *
 * See {@link ControlledWorkerBoundJoin} and {@link FedXConfig#getEnableServiceAsBoundJoin()}
 *
 * @param service
 * @param bindings
 * @return the result iteration
 * @throws QueryEvaluationException
 */
public CloseableIteration<BindingSet, QueryEvaluationException> evaluateService(FedXService service,
		final List<BindingSet> bindings) throws QueryEvaluationException {

	Var serviceRef = service.getService().getServiceRef();
	String serviceUri;
	if (serviceRef.hasValue()) {
		serviceUri = serviceRef.getValue().stringValue();
	} else {
		return new ServiceJoinIterator(new CollectionIteration<>(bindings),
				service.getService(), EmptyBindingSet.getInstance(), this);
	}

	// use vectored evaluation
	FederatedService fs = getService(serviceUri);
	if (fs instanceof RepositoryFederatedService) {
		// set the bound join block size to 0 => leave block size up to FedX engine
		((RepositoryFederatedService) fs).setBoundJoinBlockSize(0);
	}
	return fs.evaluate(service.getService(), new CollectionIteration<>(bindings),
			service.getService().getBaseURI());
}
 
Example 2
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(Var theVar) throws Exception {
	if (theVar.isAnonymous() && !theVar.hasValue()) {
		mBuffer.append(BaseTupleExprRenderer.scrubVarName(theVar.getName().substring(1)));
	} else if (theVar.hasValue()) {
		mBuffer.append(RenderUtils.getSerqlQueryString(theVar.getValue()));
	} else {
		mBuffer.append(theVar.getName());
	}
}
 
Example 3
Source File: HalyardStatsBasedStatementPatternCardinalityCalculator.java    From Halyard with Apache License 2.0 5 votes vote down vote up
@Override
public Double getCardinality(StatementPattern sp, Collection<String> boundVars) { //get the cardinality of the Statement form VOID statistics
    final Var contextVar = sp.getContextVar();
    final IRI graphNode = contextVar == null || !contextVar.hasValue() ? HALYARD.STATS_ROOT_NODE : (IRI) contextVar.getValue();
    final long triples = getTriplesCount(graphNode, -1l);
    if (triples > 0) { //stats are present
        final double card;
        boolean sv = hasValue(sp.getSubjectVar(), boundVars);
        boolean pv = hasValue(sp.getPredicateVar(), boundVars);
        boolean ov = hasValue(sp.getObjectVar(), boundVars);
        long defaultCardinality = Math.round(Math.sqrt(triples));
        if (sv) {
            if (pv) {
                if (ov) {
                    card = 1.0;
                } else {
                    card = (double) subsetTriplesPart(graphNode, VOID_EXT.SUBJECT, sp.getSubjectVar(), defaultCardinality) * subsetTriplesPart(graphNode, VOID.PROPERTY, sp.getPredicateVar(), defaultCardinality) / triples;
                }
            } else if (ov) {
                card = (double) subsetTriplesPart(graphNode, VOID_EXT.SUBJECT, sp.getSubjectVar(), defaultCardinality) * subsetTriplesPart(graphNode, VOID_EXT.OBJECT, sp.getObjectVar(), defaultCardinality) / triples;
            } else {
                card = subsetTriplesPart(graphNode, VOID_EXT.SUBJECT, sp.getSubjectVar(), defaultCardinality);
            }
        } else if (pv) {
            if (ov) {
                card = (double) subsetTriplesPart(graphNode, VOID.PROPERTY, sp.getPredicateVar(), defaultCardinality) * subsetTriplesPart(graphNode, VOID_EXT.OBJECT, sp.getObjectVar(), defaultCardinality) / triples;
            } else {
                card = subsetTriplesPart(graphNode, VOID.PROPERTY, sp.getPredicateVar(), defaultCardinality);
            }
        } else if (ov) {
            card = subsetTriplesPart(graphNode, VOID_EXT.OBJECT, sp.getObjectVar(), defaultCardinality);
        } else {
            card = triples;
        }
        LOG.log(Level.FINE, "cardinality of {0} = {1}", new Object[]{sp.toString(), card});
        return card;
    } else { // stats are not present
        return null;
    }
}
 
Example 4
Source File: QueryAlgebraUtil.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Clone the specified variable and attach bindings, moreover change name of variable by appending "_varId" to it.
 *
 * @param var
 * @param varID
 * @param varNames
 * @param bindings
 *
 * @return the variable
 */
protected static Var appendVarId(Var var, String varID, Set<String> varNames, BindingSet bindings) {
	Var res = var.clone();
	if (!var.hasValue()) {
		if (bindings.hasBinding(var.getName())) {
			res.setValue(bindings.getValue(var.getName()));
		} else {
			String newName = var.getName() + "_" + varID;
			varNames.add(newName);
			res.setName(newName);
		}
	}
	return res;
}
 
Example 5
Source File: UpdateExprBuilder.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public TupleExpr visit(ASTDeleteClause node, Object data) throws VisitorException {
	TupleExpr result = (TupleExpr) data;

	// Collect construct triples
	GraphPattern parentGP = graphPattern;

	graphPattern = new GraphPattern();

	// inherit scope & context
	graphPattern.setStatementPatternScope(parentGP.getStatementPatternScope());
	graphPattern.setContextVar(parentGP.getContextVar());

	for (int i = 0; i < node.jjtGetNumChildren(); i++) {
		node.jjtGetChild(i).jjtAccept(this, data);
	}

	TupleExpr deleteExpr = graphPattern.buildTupleExpr();
	Map<String, Object> tripleVars = TripleRefCollector.process(where);

	// FIXME we should adapt the grammar so we can avoid doing this in
	// post-processing.
	VarCollector collector = new VarCollector();
	deleteExpr.visit(collector);
	for (Var var : collector.getCollectedVars()) {
		// skip vars that are provided by ValueExprTripleRef - added as Extentsion
		if (tripleVars.containsKey(var.getName())) {
			continue;
		}
		if (var.isAnonymous() && !var.hasValue()) {
			// blank node in delete pattern, not allowed by SPARQL spec.
			throw new VisitorException("DELETE clause may not contain blank nodes");
		}
	}

	graphPattern = parentGP;

	return deleteExpr;

}
 
Example 6
Source File: QueryMultiJoinOptimizer.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected List<Var> getConstantVars(Iterable<Var> vars) {
	List<Var> constantVars = new ArrayList<>();

	for (Var var : vars) {
		if (var.hasValue()) {
			constantVars.add(var);
		}
	}

	return constantVars;
}
 
Example 7
Source File: QueryStringUtil.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * returns true iff there is at least one free variable, i.e. there is no binding for any variable
 *
 * @param stmt
 * @param bindings
 * @return whether free vars are available
 */
public static boolean hasFreeVars(StatementPattern stmt, BindingSet bindings) {
	for (Var var : stmt.getVarList()) {
		if (!var.hasValue() && !bindings.hasBinding(var.getName())) {
			return true; // there is at least one free var
		}
	}
	return false;
}
 
Example 8
Source File: PrepareOwnedTupleExpr.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void appendFilter(StringBuilder builder, Var var) {
	if (var.hasValue() && !var.isAnonymous()) {
		builder.append("\nFILTER sameTerm(");
		appendVar(builder, var.getName());
		builder.append(", ");
		writeValue(builder, var.getValue());
		builder.append(")");
	}
}
 
Example 9
Source File: QueryAlgebraUtil.java    From CostFed with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Clone the specified variable and attach bindings, moreover change name of variable
 * by appending "_varId" to it.
 * 
 * @param sb
 * @param var
 * @param varNames
 * @param bindings
 * 
 * @return
 */
protected static Var appendVarId(Var var, String varID, Set<String> varNames, BindingSet bindings) {
	Var res = var.clone();
	if (!var.hasValue()) {
		if (bindings.hasBinding(var.getName())) {
			res.setValue( bindings.getValue(var.getName()) );
		} else {
			String newName = var.getName() + "_" + varID;
			varNames.add(newName);
			res.setName(newName);
		}			
	}
	return res;
}
 
Example 10
Source File: LuceneIndex.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
protected Iterable<? extends DocumentResult> geoRelationQuery(String relation, IRI geoProperty, Shape shape,
		Var contextVar) throws MalformedQueryException, IOException {
	SpatialOperation op = toSpatialOp(relation);
	if (op == null) {
		return null;
	}

	final String geoField = SearchFields.getPropertyField(geoProperty);
	SpatialStrategy strategy = getSpatialStrategyMapper().apply(geoField);
	Query q = strategy.makeQuery(new SpatialArgs(op, shape));
	if (contextVar != null) {
		q = addContextTerm(q, (Resource) contextVar.getValue());
	}

	TopDocs docs = search(q);
	final Set<String> fields = Sets.newHashSet(SearchFields.URI_FIELD_NAME, geoField);
	if (contextVar != null && !contextVar.hasValue()) {
		fields.add(SearchFields.CONTEXT_FIELD_NAME);
	}
	return Iterables.transform(Arrays.asList(docs.scoreDocs), new Function<ScoreDoc, DocumentResult>() {

		@Override
		public DocumentResult apply(ScoreDoc doc) {
			return new LuceneDocumentResult(doc, LuceneIndex.this, fields);
		}
	});
}
 
Example 11
Source File: IteratorFactory.java    From rya with Apache License 2.0 4 votes vote down vote up
public static Collection<IRI> getPredicateRestrictions(Var predicate) {
    if (predicate.hasValue())
        return Collections.singleton((IRI) predicate.getValue());
    return Collections.emptyList();
}
 
Example 12
Source File: HalyardStatsBasedStatementPatternCardinalityCalculator.java    From Halyard with Apache License 2.0 4 votes vote down vote up
private boolean hasValue(Var partitionVar, Collection<String> boundVars) {
    return partitionVar == null || partitionVar.hasValue() || boundVars.contains(partitionVar.getName());
}
 
Example 13
Source File: AbstractSearchIndex.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private Collection<BindingSet> generateBindingSets(DistanceQuerySpec query,
		Iterable<? extends DocumentDistance> hits) throws SailException {
	// Since one resource can be returned many times, it can lead now to
	// multiple occurrences
	// of the same binding tuple in the BINDINGS clause. This in turn leads to
	// duplicate answers in the original SPARQL query.
	// We want to avoid this, so BindingSets added to the result must be
	// unique.
	LinkedHashSet<BindingSet> bindingSets = new LinkedHashSet<>();

	Set<String> bindingNames = new HashSet<>();
	final String subjVar = query.getSubjectVar();
	if (subjVar != null) {
		bindingNames.add(subjVar);
	}
	final String geoVar = query.getGeoVar();
	if (geoVar != null) {
		bindingNames.add(geoVar);
	}
	final String distanceVar = query.getDistanceVar();
	if (distanceVar != null) {
		bindingNames.add(distanceVar);
	}
	final Var contextVar = query.getContextVar();
	if (contextVar != null && !contextVar.hasValue()) {
		bindingNames.add(contextVar.getName());
	}

	if (hits != null) {
		double maxDistance = query.getDistance();
		// for each hit ...
		for (DocumentDistance hit : hits) {
			// get the current hit
			SearchDocument doc = hit.getDocument();
			if (doc == null) {
				continue;
			}

			List<String> geometries = doc.getProperty(SearchFields.getPropertyField(query.getGeoProperty()));
			for (String geometry : geometries) {
				double distance = hit.getDistance();
				// Distance queries are generally implemented by checking
				// if indexed points intersect with a bounding disc.
				// Unfortunately, this means the results may potentially also
				// include other indexed shapes that intersect with the disc.
				// The distances assigned to these other shapes may well be
				// greater than the original bounding distance.
				// We could exclude such results by checking if the shapes are
				// points,
				// but instead we do a faster sanity check of the distance.
				// This has the potential (desirable?) side-effect of extending
				// the distance function
				// to arbitrary shapes.
				if (distance < maxDistance) {
					QueryBindingSet derivedBindings = new QueryBindingSet();
					if (subjVar != null) {
						Resource resource = getResource(doc);
						derivedBindings.addBinding(subjVar, resource);
					}
					if (contextVar != null && !contextVar.hasValue()) {
						Resource ctx = SearchFields.createContext(doc.getContext());
						if (ctx != null) {
							derivedBindings.addBinding(contextVar.getName(), ctx);
						}
					}
					if (geoVar != null) {
						derivedBindings.addBinding(geoVar, SearchFields.wktToLiteral(geometry));
					}
					if (distanceVar != null) {
						derivedBindings.addBinding(distanceVar, SearchFields.distanceToLiteral(distance));
					}

					bindingSets.add(derivedBindings);
				}
			}
		}
	}

	// we succeeded
	return new BindingSetCollection(bindingNames, bindingSets);
}
 
Example 14
Source File: StrictEvaluationStrategy.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public CloseableIteration<BindingSet, QueryEvaluationException> evaluate(Service service, BindingSet bindings)
		throws QueryEvaluationException {
	Var serviceRef = service.getServiceRef();

	String serviceUri;
	if (serviceRef.hasValue()) {
		serviceUri = serviceRef.getValue().stringValue();
	} else {
		if (bindings != null && bindings.getValue(serviceRef.getName()) != null) {
			serviceUri = bindings.getBinding(serviceRef.getName()).getValue().stringValue();
		} else {
			throw new QueryEvaluationException("SERVICE variables must be bound at evaluation time.");
		}
	}

	try {

		FederatedService fs = serviceResolver.getService(serviceUri);

		// create a copy of the free variables, and remove those for which
		// bindings are available (we can set them as constraints!)
		Set<String> freeVars = new HashSet<>(service.getServiceVars());
		freeVars.removeAll(bindings.getBindingNames());

		// Get bindings from values pre-bound into variables.
		MapBindingSet allBindings = new MapBindingSet();
		for (Binding binding : bindings) {
			allBindings.addBinding(binding.getName(), binding.getValue());
		}

		Set<Var> boundVars = getBoundVariables(service);
		for (Var boundVar : boundVars) {
			freeVars.remove(boundVar.getName());
			allBindings.addBinding(boundVar.getName(), boundVar.getValue());
		}
		bindings = allBindings;

		String baseUri = service.getBaseURI();

		// special case: no free variables => perform ASK query
		if (freeVars.isEmpty()) {
			boolean exists = fs.ask(service, bindings, baseUri);

			// check if triples are available (with inserted bindings)
			if (exists) {
				return new SingletonIteration<>(bindings);
			} else {
				return new EmptyIteration<>();
			}

		}

		// otherwise: perform a SELECT query
		return fs.select(service, freeVars, bindings,
				baseUri);

	} catch (RuntimeException e) {
		// suppress exceptions if silent
		if (service.isSilent()) {
			return new SingletonIteration<>(bindings);
		} else {
			throw e;
		}
	}

}
 
Example 15
Source File: SolrIndex.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
protected Iterable<? extends DocumentResult> geoRelationQuery(String relation, IRI geoProperty, Shape shape,
		Var contextVar) throws MalformedQueryException, IOException {
	String spatialOp = toSpatialOp(relation);
	if (spatialOp == null) {
		return null;
	}
	String wkt = toWkt(shape);
	String qstr = "\"" + spatialOp + "(" + wkt + ")\"";
	if (contextVar != null) {
		Resource ctx = (Resource) contextVar.getValue();
		String tq = termQuery(SearchFields.CONTEXT_FIELD_NAME, SearchFields.getContextID(ctx));
		if (ctx != null) {
			qstr = tq + " AND " + qstr;
		} else {
			qstr = "-" + tq + " AND " + qstr;
		}
	}
	SolrQuery q = new SolrQuery(qstr);
	q.set(CommonParams.DF, SearchFields.getPropertyField(geoProperty));
	q.addField(SearchFields.URI_FIELD_NAME);
	// ':' is part of the fl parameter syntax so we can't use the full
	// property field name
	// instead we use wildcard + local part of the property URI
	q.addField("*" + geoProperty.getLocalName());
	boolean requireContext = (contextVar != null && !contextVar.hasValue());
	if (requireContext) {
		q.addField(SearchFields.CONTEXT_FIELD_NAME);
	}

	QueryResponse response;
	try {
		response = search(q);
	} catch (SolrServerException e) {
		throw new IOException(e);
	}

	SolrDocumentList results = response.getResults();
	return Iterables.transform(results, (SolrDocument document) -> {
		SolrSearchDocument doc = new SolrSearchDocument(document);
		return new SolrDocumentResult(doc);
	});
}
 
Example 16
Source File: QueryStringUtil.java    From CostFed with GNU Affero General Public License v3.0 4 votes vote down vote up
public static String toString(Var var) {
	if (!var.hasValue())
		return "?" + var.getName();
	return getValueString(var.getValue());
}
 
Example 17
Source File: QueryAlgebraUtil.java    From CostFed with GNU Affero General Public License v3.0 3 votes vote down vote up
/**
 * Return the {@link Value} of the variable which is either taken from
 * the variable itself (bound) or from the bindingsset (unbound).
 * 
 * @param var
 * @param bindings
 * 			the bindings, must not be null, use {@link EmptyBindingSet} instead
 * 
 * @return
 * 		the value or null
 */
public static Value getVarValue(Var var, BindingSet bindings) {
	if (var == null) {
		return null;
	} else if (var.hasValue()) {
		return var.getValue();
	} else {
		return bindings.getValue(var.getName());
	}
}
 
Example 18
Source File: QueryStringUtil.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 3 votes vote down vote up
/**
 * Append the variable to the provided StringBuilder.
 *
 * Cases: 1) unbound: check provided bindingset for possible match a) match found: append matching value b) no
 * match: append ?varName and add to varNames 2) bound: append value
 *
 * @param sb
 * @param var
 * @param varNames
 * @param bindings
 *
 * @return the stringbuilder
 */
protected static StringBuilder appendVar(StringBuilder sb, Var var, Set<String> varNames, BindingSet bindings) {
	if (!var.hasValue()) {
		if (bindings.hasBinding(var.getName())) {
			return appendValue(sb, bindings.getValue(var.getName()));
		}
		varNames.add(var.getName());
		return sb.append("?").append(var.getName());
	} else {
		return appendValue(sb, var.getValue());
	}
}
 
Example 19
Source File: QueryStringUtil.java    From CostFed with GNU Affero General Public License v3.0 3 votes vote down vote up
/**
 * Append the variable to the provided StringBuilder, however change name of variable
 * by appending "_varId" to it.
 * 
 * Cases:
 *  1) unbound: check provided bindingset for possible match 
 *   a) match found: append matching value
 *   b) no match: append ?varName_varId and add to varNames
 *  2) bound: append value
 *  
 * @param sb
 * @param var
 * @param varNames
 * @param bindings
 * 
 * @return
 * 		the complemented string builder
 */
protected static StringBuilder appendVarId(StringBuilder sb, Var var, String varID, Set<String> varNames, BindingSet bindings) {
	if (!var.hasValue()) {
		if (bindings.hasBinding(var.getName()))
			return appendValue(sb, bindings.getValue(var.getName()));
		String newName = var.getName() + "_" + varID;
		varNames.add(newName);
		return sb.append("?").append(newName);
	}
	else
		return appendValue(sb, var.getValue());
}
 
Example 20
Source File: QueryStringUtil.java    From CostFed with GNU Affero General Public License v3.0 3 votes vote down vote up
/**
 * Append the variable to the provided StringBuilder.
 * 
 * Cases:
 *  1) unbound: check provided bindingset for possible match 
 *   a) match found: append matching value
 *   b) no match: append ?varName and add to varNames
 *  2) bound: append value
 *  
 * @param sb
 * @param var
 * @param varNames
 * @param bindings
 * 
 * @return
 * 		the stringbuilder
 */
protected static StringBuilder appendVar(StringBuilder sb, Var var, Set<String> varNames, BindingSet bindings) {
	if (!var.hasValue()) {
		if (bindings.hasBinding(var.getName()))
			return appendValue(sb, bindings.getValue(var.getName()));
		varNames.add(var.getName());
		return sb.append("?").append(var.getName());
	}
	else
		return appendValue(sb, var.getValue());
}