Java Code Examples for org.eclipse.rdf4j.query.algebra.ProjectionElem#getSourceName()

The following examples show how to use org.eclipse.rdf4j.query.algebra.ProjectionElem#getSourceName() . 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: SpinRenderer.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void meet(ProjectionElem node) throws RDFHandlerException {
	if (isSubQuery) {
		super.meet(node);
	} else {
		String varName = node.getSourceName();
		ValueExpr valueExpr = inlineBindings.getValueExpr(varName);
		Value value = (valueExpr instanceof ValueConstant) ? ((ValueConstant) valueExpr).getValue()
				: getVar(varName);
		String targetName = node.getTargetName();
		IRI pred;
		if ("subject".equals(targetName)) {
			pred = SP.SUBJECT_PROPERTY;
		} else if ("predicate".equals(targetName)) {
			pred = SP.PREDICATE_PROPERTY;
		} else if ("object".equals(targetName)) {
			pred = SP.OBJECT_PROPERTY;
		} else {
			throw new AssertionError("Unexpected ProjectionElem: " + node);
		}
		handler.handleStatement(valueFactory.createStatement(subject, pred, value));
	}
}
 
Example 2
Source File: SpinRenderer.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void meet(ProjectionElem node) throws RDFHandlerException {
	ValueExpr valueExpr = null;
	if (inlineBindings != null) {
		String varName = node.getSourceName();
		valueExpr = inlineBindings.getValueExpr(varName);
	}
	Resource targetVar = getVar(node.getTargetName());
	listEntry(targetVar);
	if (valueExpr != null && !(valueExpr instanceof Var)) {
		Resource currentSubj = subject;
		subject = valueFactory.createBNode();
		handler.handleStatement(valueFactory.createStatement(targetVar, SP.EXPRESSION_PROPERTY, subject));
		valueExpr.visit(new ExtensionVisitor());
		subject = currentSubj;
	}
}
 
Example 3
Source File: OrderLimitOptimizer.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void meet(Var node) {
	if (projection != null) {
		boolean projected = false;
		for (ProjectionElem e : projection.getProjectionElemList().getElements()) {
			String source = e.getSourceName();
			String target = e.getTargetName();
			if (node.getName().equals(source) && node.getName().equals(target)) {
				projected = true;
				break;
			}
		}
		if (!projected) {
			variablesProjected = false;
		}
	}
}
 
Example 4
Source File: ConstantOptimizer.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Applies generally applicable optimizations to the supplied query: variable assignments are inlined.
 */
@Override
public void optimize(TupleExpr tupleExpr, Dataset dataset, BindingSet bindings) {
	ConstantVisitor visitor = new ConstantVisitor();
	tupleExpr.visit(visitor);
	Set<String> varsBefore = visitor.varNames;

	VarNameCollector varCollector = new VarNameCollector();
	tupleExpr.visit(varCollector);
	Set<String> varsAfter = varCollector.varNames;

	if (varsAfter.size() < varsBefore.size()) {
		varsBefore.removeAll(varsAfter);
		for (ProjectionElemList projElems : visitor.projElemLists) {
			for (ProjectionElem projElem : projElems.getElements()) {
				String name = projElem.getSourceName();
				if (varsBefore.contains(name)) {
					UnaryTupleOperator proj = (UnaryTupleOperator) projElems.getParentNode();
					Extension ext = new Extension(proj.getArg());
					proj.setArg(ext);
					Var lostVar = new Var(name);
					Value value = bindings.getValue(name);
					if (value != null) {
						lostVar.setValue(value);
					}
					ext.addElement(new ExtensionElem(lostVar, name));
				}
			}
		}
	}
}
 
Example 5
Source File: ProjectionEvaluator.java    From rya with Apache License 2.0 5 votes vote down vote up
/**
 * Applies the projection to a value. If the result has a blank node whose ID is not mapped to a value in
 * {@code blankNodes}, then a random UUID will be used.
 *
 * @param bs - The value the projection will be applied to. (not null)
 * @param blankNodes - A map from node source names to the blank nodes that will be used for those names. (not null)
 * @return A new value that is the result of the projection.
 */
public VisibilityBindingSet project(final VisibilityBindingSet bs, final Map<String, BNode> blankNodes) {
    requireNonNull(bs);
    requireNonNull(blankNodes);

    // Apply the projection elements against the original binding set.
    final MapBindingSet result = new MapBindingSet();
    for (final ProjectionElem elem : projectionElems.getElements()) {
        final String sourceName = elem.getSourceName();

        Value value = null;

        // If the binding set already has the source name, then use the target name.
        if (bs.hasBinding(sourceName)) {
            value = bs.getValue(elem.getSourceName());
        }

        // If the source name represents a constant value, then use the constant.
        else if(constantSources.containsKey(sourceName)) {
            value = constantSources.get(sourceName);
        }

        // If the source name represents an anonymous value, then create a Blank Node.
        else if(anonymousSources.contains(sourceName)) {
            if(blankNodes.containsKey(sourceName)) {
                value = blankNodes.get(sourceName);
            } else {
                value = VF.createBNode( UUID.randomUUID().toString() );
            }
        }

        // Only add the value if there is one. There may not be one if a binding is optional.
        if(value != null) {
            result.addBinding(elem.getTargetName(), value);
        }
    }

    return new VisibilityBindingSet(result, bs.getVisibility());
}
 
Example 6
Source File: SparqlFluoQueryBuilder.java    From rya with Apache License 2.0 5 votes vote down vote up
private static VariableOrder getConstructGraphVarOrder(List<ProjectionElemList> projections) {
    final Set<String> varOrders = new HashSet<>();

    for(final ProjectionElemList elems: projections) {
        for(final ProjectionElem elem: elems.getElements()) {
            final String name = elem.getSourceName();
            if (!VarNameUtils.isConstant(name) && !VarNameUtils.isAnonymous(name)) {
                varOrders.add(name);
            }
        }
    }

    return new VariableOrder(varOrders);
}
 
Example 7
Source File: QueryVariableNormalizer.java    From rya with Apache License 2.0 5 votes vote down vote up
@Override
public void meet(ProjectionElemList node) {
    List<ProjectionElem> proj = node.getElements();
    for (ProjectionElem s : proj) {
        if (varChanges.containsKey(s.getSourceName())) {
            String name = s.getSourceName();
            s.setSourceName(varChanges.get(name));
            s.setTargetName(varChanges.get(name));
           
        }
    }

}
 
Example 8
Source File: ConstructConsequentVisitor.java    From rya with Apache License 2.0 5 votes vote down vote up
private void recordConsequent(ProjectionElemList variables, List<ExtensionElem> extensionElements) {
    Map<String, Value> bindings = new ConcurrentHashMap<>();
    Map<String, Value> values = new ConcurrentHashMap<>();
    Set<String> queryBnodes = new HashSet<>();
    Set<String> projectedBnodes = new HashSet<>();
    for (ExtensionElem ee : extensionElements) {
        if (ee.getExpr() instanceof ValueConstant) {
            bindings.put(ee.getName(), ((ValueConstant) ee.getExpr()).getValue());
        }
        else if (ee.getExpr() instanceof BNodeGenerator) {
            queryBnodes.add(ee.getName());
        }
    }
    for (ProjectionElem var : variables.getElements()) {
        String sourceName = var.getSourceName();
        String targetName = var.getTargetName();
        Value constValue = bindings.get(sourceName);
        if (constValue != null) {
            values.put(targetName, constValue);
        }
        else if (queryBnodes.contains(sourceName)) {
            projectedBnodes.add(targetName);
        }
    }
    Var subjVar = new Var(SUBJECT_VAR_NAME, values.get(SUBJECT_VAR_NAME));
    Var predVar = new Var(PREDICATE_VAR_NAME, values.get(PREDICATE_VAR_NAME));
    Var objVar = new Var(OBJECT_VAR_NAME, values.get(OBJECT_VAR_NAME));
    subjVar.setAnonymous(projectedBnodes.contains(SUBJECT_VAR_NAME));
    predVar.setAnonymous(projectedBnodes.contains(PREDICATE_VAR_NAME));
    objVar.setAnonymous(projectedBnodes.contains(OBJECT_VAR_NAME));
    StatementPattern sp = new StatementPattern(subjVar, predVar, objVar);
    consequentStatementPatterns.add(sp);
}
 
Example 9
Source File: AggregationPipelineQueryNode.java    From rya with Apache License 2.0 votes vote down vote up
/**
 * Add a SPARQL projection or multi-projection operation to the pipeline.
 * The number of documents produced by the pipeline after this operation
 * will be the number of documents entering this stage (the number of
 * intermediate results) multiplied by the number of
 * {@link ProjectionElemList}s supplied here. Empty projections are
 * unsupported; if one or more projections given binds zero variables, then
 * the pipeline will be unchanged and the method will return false.
 * @param projections One or more projections, i.e. mappings from the result
 *  at this stage of the query into a set of variables.
 * @return true if the projection(s) were added to the pipeline.
 */
public boolean project(final Iterable<ProjectionElemList> projections) {
    if (projections == null || !projections.iterator().hasNext()) {
        return false;
    }
    final List<Bson> projectOpts = new LinkedList<>();
    final Set<String> bindingNamesUnion = new HashSet<>();
    Set<String> bindingNamesIntersection = null;
    for (final ProjectionElemList projection : projections) {
        if (projection.getElements().isEmpty()) {
            // Empty projections are unsupported -- fail when seen
            return false;
        }
        final Document valueDoc = new Document();
        final Document hashDoc = new Document();
        final Document typeDoc = new Document();
        final Set<String> projectionBindingNames = new HashSet<>();
        for (final ProjectionElem elem : projection.getElements()) {
            String to = elem.getTargetName();
            // If the 'to' name is invalid, replace it internally
            if (!isValidFieldName(to)) {
                to = replace(to);
            }
            String from = elem.getSourceName();
            // If the 'from' name is invalid, use the internal substitute
            if (varToOriginalName.containsValue(from)) {
                from = varToOriginalName.inverse().get(from);
            }
            projectionBindingNames.add(to);
            if (to.equals(from)) {
                valueDoc.append(to, 1);
                hashDoc.append(to, 1);
                typeDoc.append(to, 1);
            }
            else {
                valueDoc.append(to, valueFieldExpr(from));
                hashDoc.append(to, hashFieldExpr(from));
                typeDoc.append(to, typeFieldExpr(from));
            }
        }
        bindingNamesUnion.addAll(projectionBindingNames);
        if (bindingNamesIntersection == null) {
            bindingNamesIntersection = new HashSet<>(projectionBindingNames);
        }
        else {
            bindingNamesIntersection.retainAll(projectionBindingNames);
        }
        projectOpts.add(new Document()
                .append(VALUES, valueDoc)
                .append(HASHES, hashDoc)
                .append(TYPES, typeDoc)
                .append(LEVEL, "$" + LEVEL)
                .append(TIMESTAMP, "$" + TIMESTAMP));
    }
    if (projectOpts.size() == 1) {
        pipeline.add(Aggregates.project(projectOpts.get(0)));
    }
    else {
        final String listKey = "PROJECTIONS";
        final Bson projectIndividual = Projections.fields(
                Projections.computed(VALUES, "$" + listKey + "." + VALUES),
                Projections.computed(HASHES, "$" + listKey + "." + HASHES),
                Projections.computed(TYPES, "$" + listKey + "." + TYPES),
                Projections.include(LEVEL),
                Projections.include(TIMESTAMP));
        pipeline.add(Aggregates.project(Projections.computed(listKey, projectOpts)));
        pipeline.add(Aggregates.unwind("$" + listKey));
        pipeline.add(Aggregates.project(projectIndividual));
    }
    assuredBindingNames.clear();
    bindingNames.clear();
    assuredBindingNames.addAll(bindingNamesIntersection);
    bindingNames.addAll(bindingNamesUnion);
    return true;
}