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

The following examples show how to use org.eclipse.rdf4j.query.algebra.MultiProjection. 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: SparqlToPipelineTransformVisitorTest.java    From rya with Apache License 2.0 6 votes vote down vote up
@Test
public void testMultiProjection() throws Exception {
    StatementPattern isUndergrad = new StatementPattern(new Var("x"), constant(RDF.TYPE), constant(UNDERGRAD));
    StatementPattern isCourse = new StatementPattern(new Var("course"), constant(RDF.TYPE), constant(COURSE));
    StatementPattern hasEdge = new StatementPattern(new Var("x"), new Var("p"), new Var("course"));
    ProjectionElemList courseHasRelation = new ProjectionElemList(
            new ProjectionElem("p", "relation"),
            new ProjectionElem("course"));
    ProjectionElemList studentHasRelation = new ProjectionElemList(
            new ProjectionElem("p", "relation"),
            new ProjectionElem("x", "student"));
    QueryRoot queryTree = new QueryRoot(new MultiProjection(
            new Join(new Join(isCourse, hasEdge), isUndergrad),
            Arrays.asList(courseHasRelation, studentHasRelation)));
    SparqlToPipelineTransformVisitor visitor = new SparqlToPipelineTransformVisitor(collection);
    queryTree.visit(visitor);
    Assert.assertTrue(queryTree.getArg() instanceof AggregationPipelineQueryNode);
    AggregationPipelineQueryNode pipelineNode = (AggregationPipelineQueryNode) queryTree.getArg();
    Assert.assertEquals(Sets.newHashSet("relation"), pipelineNode.getAssuredBindingNames());
    Assert.assertEquals(Sets.newHashSet("relation", "course", "student"), pipelineNode.getBindingNames());
}
 
Example #2
Source File: TopologyFactory.java    From rya with Apache License 2.0 6 votes vote down vote up
@Override
public void meet(final MultiProjection node) throws TopologyBuilderException {
    final String id = PROJECTION_PREFIX + UUID.randomUUID();
    final Optional<Side> side = getSide(node);

    final MultiProjectionProcessorSupplier supplier = new MultiProjectionProcessorSupplier(
            MultiProjectionEvaluator.make(node, bNodeIdFactory),
            result -> getResult(side, result));

    // If the arg is an Extension, then this node's grandchild is the next processing node.
    TupleExpr downstreamNode = node.getArg();
    if (downstreamNode instanceof Extension) {
        downstreamNode = ((Extension) downstreamNode).getArg();
    }

    entries.add(new ProcessorEntry(node, id, side, supplier, Lists.newArrayList(downstreamNode)));
    idMap.put(node, id);
    super.meet(node);
}
 
Example #3
Source File: SparqlFluoQueryBuilder.java    From rya with Apache License 2.0 6 votes vote down vote up
private static VariableOrder getConstructGraphVarOrder(final Reduced node) {

        //get child node
          final QueryModelNode child = node.getArg();
          Preconditions.checkArgument(child instanceof Projection || child instanceof MultiProjection);
          final UnaryTupleOperator unary = (UnaryTupleOperator) child;

          //get ProjectionElemList to build ConstructGraph
          final List<ProjectionElemList> projections = new ArrayList<>();
          if(unary instanceof Projection) {
              projections.add(((Projection) unary).getProjectionElemList());
          } else {
              projections.addAll(((MultiProjection)unary).getProjections());
          }

          return getConstructGraphVarOrder(projections);
      }
 
Example #4
Source File: MultiProjectionEvaluator.java    From rya with Apache License 2.0 6 votes vote down vote up
/**
 * Make a {@link MultiProjectionEvaluator} that processes the logic of a {@link MultiProjection}.
 *
 * @param multiProjection - Defines the projections that will be processed. (not null)
 * @param bNodeIdFactory - Creates the IDs for Blank Nodes. (not null)
 * @return A {@link MultiProjectionEvaluator} for the provided {@link MultiProjection}.
 */
public static MultiProjectionEvaluator make(final MultiProjection multiProjection, final BNodeIdFactory bNodeIdFactory) {
    requireNonNull(multiProjection);

    // Figure out if there are extensions.
    final TupleExpr arg = multiProjection.getArg();
    final Optional<Extension> extension = (arg instanceof Extension) ? Optional.of((Extension)arg): Optional.empty();

    // If there are, iterate through them and find any blank node source names.
    final Set<String> blankNodeSourceNames = new HashSet<>();
    if(extension.isPresent()) {
        for(final ExtensionElem elem : extension.get().getElements()) {
            if(elem.getExpr() instanceof BNodeGenerator) {
                blankNodeSourceNames.add( elem.getName() );
            }
        }
    }

    // Create a ProjectionEvaluator for each projection that is part of the multi.
    final Set<ProjectionEvaluator> projections = new HashSet<>();
    for(final ProjectionElemList projectionElemList : multiProjection.getProjections()) {
        projections.add( new ProjectionEvaluator(projectionElemList, extension) );
    }

    return new MultiProjectionEvaluator(projections, blankNodeSourceNames, bNodeIdFactory);
}
 
Example #5
Source File: MultiProjectionIterator.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public MultiProjectionIterator(MultiProjection multiProjection,
		CloseableIteration<BindingSet, QueryEvaluationException> iter, BindingSet bindings) {
	this.projections = multiProjection.getProjections();
	this.iter = iter;
	this.parentBindings = bindings;
	this.previousBindings = new BindingSet[projections.size()];

	// initialize out-of-range to enforce a fetch of the first result upon
	// first use
	nextProjectionIdx = -1;
}
 
Example #6
Source File: HalyardTupleExprEvaluation.java    From Halyard with Apache License 2.0 5 votes vote down vote up
/**
 * Switch logic for evaluation of any instance of a {@link UnaryTupleOperator} query model node
 * @param parent
 * @param expr
 * @param bindings
 */
private void evaluateUnaryTupleOperator(BindingSetPipe parent, UnaryTupleOperator expr, BindingSet bindings) {
    if (expr instanceof Projection) {
        evaluateProjection(parent, (Projection) expr, bindings);
    } else if (expr instanceof MultiProjection) {
        evaluateMultiProjection(parent, (MultiProjection) expr, bindings);
    } else if (expr instanceof Filter) {
        evaluateFilter(parent, (Filter) expr, bindings);
    } else if (expr instanceof Service) {
        evaluateService(parent, (Service) expr, bindings);
    } else if (expr instanceof Slice) {
        evaluateSlice(parent, (Slice) expr, bindings);
    } else if (expr instanceof Extension) {
        evaluateExtension(parent, (Extension) expr, bindings);
    } else if (expr instanceof Distinct) {
        evaluateDistinct(parent, (Distinct) expr, bindings);
    } else if (expr instanceof Reduced) {
        evaluateReduced(parent, (Reduced) expr, bindings);
    } else if (expr instanceof Group) {
        evaluateGroup(parent, (Group) expr, bindings);
    } else if (expr instanceof Order) {
        evaluateOrder(parent, (Order) expr, bindings);
    } else if (expr instanceof QueryRoot) {
        parentStrategy.sharedValueOfNow = null;
        evaluateTupleExpr(parent, ((QueryRoot) expr).getArg(), bindings);
    } else if (expr instanceof DescribeOperator) {
        evaluateDescribeOperator(parent, (DescribeOperator) expr, bindings);
    } else if (expr == null) {
        parent.handleException(new IllegalArgumentException("expr must not be null"));
    } else {
        parent.handleException(new QueryEvaluationException("Unknown unary tuple operator type: " + expr.getClass()));
    }
}
 
Example #7
Source File: SparqlToPipelineTransformVisitor.java    From rya with Apache License 2.0 5 votes vote down vote up
@Override
public void meet(MultiProjection projectionNode) throws Exception {
    projectionNode.visitChildren(this);
    if (projectionNode.getArg() instanceof AggregationPipelineQueryNode && projectionNode.getParentNode() != null) {
        AggregationPipelineQueryNode pipelineNode = (AggregationPipelineQueryNode) projectionNode.getArg();
        if (pipelineNode.project(projectionNode.getProjections())) {
            projectionNode.replaceWith(pipelineNode);
        }
    }
}
 
Example #8
Source File: SpinRenderer.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void meet(MultiProjection node) throws RDFHandlerException {
	ExtensionContext oldInlineBindings = meetExtension(node.getArg());
	ListContext ctx = startTemplateList();
	isMultiProjection = true;
	for (ProjectionElemList proj : node.getProjections()) {
		proj.visit(this);
	}
	endTemplateList(ctx);
	isMultiProjection = false;
	visitWhere(node.getArg());
	inlineBindings = oldInlineBindings;
}
 
Example #9
Source File: ProjectionIterator.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private final boolean determineOuterProjection() {
	QueryModelNode ancestor = projection;
	while (ancestor.getParentNode() != null) {
		ancestor = ancestor.getParentNode();
		if (ancestor instanceof Projection || ancestor instanceof MultiProjection) {
			return false;
		}
	}
	return true;
}
 
Example #10
Source File: MultiProjectionEvaluatorTest.java    From rya with Apache License 2.0 5 votes vote down vote up
/**
 * Get the first {@link MultiProjection} node from a SPARQL query.
 *
 * @param sparql - The query that contains a single Projection node.
 * @return The first {@link MultiProjection} that is encountered.
 * @throws Exception The query could not be parsed.
 */
public static @Nullable MultiProjection getMultiProjection(final String sparql) throws Exception {
    requireNonNull(sparql);

    final AtomicReference<MultiProjection> multiProjection = new AtomicReference<>();
    final ParsedQuery parsed = new SPARQLParser().parseQuery(sparql, null);
    parsed.getTupleExpr().visit(new AbstractQueryModelVisitor<Exception>() {
        @Override
        public void meet(final MultiProjection node) throws Exception {
            multiProjection.set(node);
        }
    });

    return multiProjection.get();
}
 
Example #11
Source File: RdfTestUtil.java    From rya with Apache License 2.0 5 votes vote down vote up
/**
 * Get the first {@link MultiProjection} node from a SPARQL query.
 *
 * @param sparql - The query that contains a single Projection node.
 * @return The first {@link MultiProjection} that is encountered.
 * @throws Exception The query could not be parsed.
 */
public static @Nullable MultiProjection getMultiProjection(final String sparql) throws Exception {
    requireNonNull(sparql);

    final AtomicReference<MultiProjection> multiProjection = new AtomicReference<>();
    final ParsedQuery parsed = new SPARQLParser().parseQuery(sparql, null);
    parsed.getTupleExpr().visit(new AbstractQueryModelVisitor<Exception>() {
        @Override
        public void meet(final MultiProjection node) throws Exception {
            multiProjection.set(node);
        }
    });

    return multiProjection.get();
}
 
Example #12
Source File: StrictEvaluationStrategy.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public CloseableIteration<BindingSet, QueryEvaluationException> evaluate(MultiProjection multiProjection,
		BindingSet bindings) throws QueryEvaluationException {
	CloseableIteration<BindingSet, QueryEvaluationException> result;
	result = this.evaluate(multiProjection.getArg(), bindings);
	result = new MultiProjectionIterator(multiProjection, result, bindings);
	return result;
}
 
Example #13
Source File: ConstructConsequentVisitor.java    From rya with Apache License 2.0 5 votes vote down vote up
@Override
public void meet(MultiProjection projection) {
    List<ExtensionElem> bindings;
    if (projection.getArg() instanceof Extension) {
        bindings = ((Extension) projection.getArg()).getElements();
    }
    else {
        bindings = Arrays.asList();
    }
    for (ProjectionElemList template : projection.getProjections()) {
        recordConsequent(template, bindings);
    }
}
 
Example #14
Source File: ConstructConsequentVisitorTest.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void testMultiProjection() {
    Extension extension = new Extension(new SingletonSet(),
            new ExtensionElem(new ValueConstant(RDF.TYPE), "rdftype"),
            new ExtensionElem(new ValueConstant(OWL.OBJECTPROPERTY), "owlprop"),
            new ExtensionElem(new ValueConstant(OWL.EQUIVALENTCLASS), "owleqcls"),
            new ExtensionElem(new ValueConstant(OWL.CLASS), "owlclass"));
    MultiProjection projection = new MultiProjection(extension, Arrays.asList(
            new ProjectionElemList(
                    new ProjectionElem("cls", "subject"),
                    new ProjectionElem("rdftype", "predicate"),
                    new ProjectionElem("owlclass", "object")),
            new ProjectionElemList(
                    new ProjectionElem("prop", "subject"),
                    new ProjectionElem("rdftype", "predicate"),
                    new ProjectionElem("owlprop", "object")),
            new ProjectionElemList(
                    new ProjectionElem("owleqcls", "predicate"),
                    new ProjectionElem("cls", "object"))));
    ConstructConsequentVisitor visitor = new ConstructConsequentVisitor();
    projection.visit(visitor);
    Set<StatementPattern> expected = Sets.newHashSet(
            new StatementPattern(s(null), p(RDF.TYPE), o(OWL.CLASS)),
            new StatementPattern(s(null), p(RDF.TYPE), o(OWL.OBJECTPROPERTY)),
            new StatementPattern(s(null), p(OWL.EQUIVALENTCLASS), o(null)));
    Assert.assertEquals(expected, visitor.getConsequents());
}
 
Example #15
Source File: StrictEvaluationStrategy.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public CloseableIteration<BindingSet, QueryEvaluationException> evaluate(UnaryTupleOperator expr,
		BindingSet bindings) throws QueryEvaluationException {
	if (expr instanceof Projection) {
		return evaluate((Projection) expr, bindings);
	} else if (expr instanceof MultiProjection) {
		return evaluate((MultiProjection) expr, bindings);
	} else if (expr instanceof Filter) {
		return evaluate((Filter) expr, bindings);
	} else if (expr instanceof Service) {
		return evaluate((Service) expr, bindings);
	} else if (expr instanceof Slice) {
		return evaluate((Slice) expr, bindings);
	} else if (expr instanceof Extension) {
		return evaluate((Extension) expr, bindings);
	} else if (expr instanceof Distinct) {
		return evaluate((Distinct) expr, bindings);
	} else if (expr instanceof Reduced) {
		return evaluate((Reduced) expr, bindings);
	} else if (expr instanceof Group) {
		return evaluate((Group) expr, bindings);
	} else if (expr instanceof Order) {
		return evaluate((Order) expr, bindings);
	} else if (expr instanceof QueryRoot) {
		// new query, reset shared return value for successive calls of
		// NOW()
		this.sharedValueOfNow = null;
		return evaluate(expr.getArg(), bindings);
	} else if (expr instanceof DescribeOperator) {
		return evaluate((DescribeOperator) expr, bindings);
	} else if (expr == null) {
		throw new IllegalArgumentException("expr must not be null");
	} else {
		throw new QueryEvaluationException("Unknown unary tuple operator type: " + expr.getClass());
	}
}
 
Example #16
Source File: AbstractQueryModelVisitor.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public void meet(MultiProjection node) throws X {
	meetUnaryTupleOperator(node);
}
 
Example #17
Source File: SparqlFluoQueryBuilder.java    From rya with Apache License 2.0 4 votes vote down vote up
@Override
public void meet(final Reduced node) {
    //create id, initialize ConstructQueryMetadata builder, register ConstructQueryMetadata
    //builder with FluoQueryBuilder, and add metadata that we currently have
    final String constructId = nodeIds.getOrMakeId(node);

    ConstructQueryMetadata.Builder constructBuilder = fluoQueryBuilder.getConstructQueryBuilder().orNull();
    if(constructBuilder == null) {
        constructBuilder = ConstructQueryMetadata.builder();
        constructBuilder.setNodeId(constructId);
        fluoQueryBuilder.setConstructQueryMetadata(constructBuilder);
    }

    //get child node
    QueryModelNode child = node.getArg();
    Preconditions.checkArgument(child instanceof Projection || child instanceof MultiProjection);
    final UnaryTupleOperator unary = (UnaryTupleOperator) child;

    //get ProjectionElemList to build ConstructGraph
    final List<ProjectionElemList> projections = new ArrayList<>();
    if(unary instanceof Projection) {
        projections.add(((Projection) unary).getProjectionElemList());
    } else {
        projections.addAll(((MultiProjection)unary).getProjections());
    }

    //get ExtensionElems to build ConstructGraph
    final QueryModelNode grandChild = unary.getArg();
    Preconditions.checkArgument(grandChild instanceof Extension);
    final Extension extension = (Extension) grandChild;
    final List<ExtensionElem> extensionElems = extension.getElements();
    final ConstructGraph graph = getConstructGraph(projections, extensionElems);
    constructBuilder.setConstructGraph(graph);

    //set child to the next node we care about in Fluo
    //if Extension's arg is a Group node, then it is an Aggregation, so set child to Extension
    //otherwise set child to Extension's child (only care about Extensions if they are Aggregations)
    if(extension.getArg() instanceof Group) {
        child = extension;
    } else {
        child = extension.getArg();
    }

    //Set the child node in the ConstructQueryMetadataBuilder
    final String childNodeId = nodeIds.getOrMakeId(child);
    constructBuilder.setChildNodeId(childNodeId);

    // Update the child node's metadata.
    final Set<String> childVars = getVars((TupleExpr)child);
    final VariableOrder childVarOrder = new VariableOrder(childVars);
    setChildMetadata(fluoQueryBuilder, childNodeId, childVarOrder, constructId);

    //fast forward visitor to next node we care about
    child.visit(this);
}