org.apache.tinkerpop.gremlin.process.traversal.step.map.VertexStep Java Examples

The following examples show how to use org.apache.tinkerpop.gremlin.process.traversal.step.map.VertexStep. 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: TopologyStrategy.java    From sqlg with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void apply(Traversal.Admin<?, ?> traversal) {
    Preconditions.checkState(!(this.sqlgSchema && this.globalUniqueIndex), "sqlgSchema and globalUnique are mutually exclusive. Both can not be true.");
    if (!TraversalHelper.getStepsOfAssignableClass(GraphStep.class, traversal).isEmpty() || !TraversalHelper.getStepsOfAssignableClass(VertexStep.class, traversal).isEmpty()) {
        if (this.sqlgSchema) {
            TraversalHelper.insertAfterStep(
                    new HasStep(traversal, new HasContainer(TOPOLOGY_SELECTION_SQLG_SCHEMA, P.eq(this.sqlgSchema))),
                    traversal.getStartStep(),
                    traversal
            );
        }
        if (this.globalUniqueIndex) {
            TraversalHelper.insertAfterStep(
                    new HasStep(traversal, new HasContainer(TOPOLOGY_SELECTION_GLOBAL_UNIQUE_INDEX, P.eq(this.globalUniqueIndex))),
                    traversal.getStartStep(),
                    traversal
            );
        }
    }

}
 
Example #2
Source File: TraversalHelper.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
public static boolean isLocalProperties(final Traversal.Admin<?, ?> traversal) {
    for (final Step step : traversal.getSteps()) {
        if (step instanceof RepeatStep) {
            for (final Traversal.Admin<?, ?> global : ((RepeatStep<?>) step).getGlobalChildren()) {
                if (TraversalHelper.hasStepOfAssignableClass(VertexStep.class, global))
                    return false;
            }
        } else if (step instanceof VertexStep) {
            return false;
        } else if (step instanceof EdgeVertexStep) {
            return false;
        } else if (step instanceof TraversalParent) {
            for (final Traversal.Admin<?, ?> local : ((TraversalParent) step).getLocalChildren()) {
                if (!TraversalHelper.isLocalProperties(local))
                    return false;
            }
        }
    }
    return true;
}
 
Example #3
Source File: HugeVertexStepStrategy.java    From hugegraph with Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public void apply(final Traversal.Admin<?, ?> traversal) {
    TraversalUtil.convAllHasSteps(traversal);

    List<VertexStep> steps = TraversalHelper.getStepsOfClass(
                             VertexStep.class, traversal);
    for (VertexStep originStep : steps) {
        HugeVertexStep<?> newStep = new HugeVertexStep<>(originStep);
        TraversalHelper.replaceStep(originStep, newStep, traversal);

        TraversalUtil.extractHasContainer(newStep, traversal);

        // TODO: support order-by optimize
        // TraversalUtil.extractOrder(newStep, traversal);

        TraversalUtil.extractRange(newStep, traversal, true);

        TraversalUtil.extractCount(newStep, traversal);
    }
}
 
Example #4
Source File: SubgraphStrategy.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
private static final char processesPropertyType(Step step) {
    while (!(step instanceof EmptyStep)) {
        if (step instanceof FilterStep || step instanceof SideEffectStep)
            step = step.getPreviousStep();
        else if (step instanceof GraphStep && ((GraphStep) step).returnsVertex())
            return 'v';
        else if (step instanceof EdgeVertexStep)
            return 'v';
        else if (step instanceof VertexStep)
            return ((VertexStep) step).returnsVertex() ? 'v' : 'p';
        else if (step instanceof PropertyMapStep || step instanceof PropertiesStep)
            return 'p';
        else
            return 'x';
    }
    return 'x';
}
 
Example #5
Source File: HBaseVertexStepStrategy.java    From hgraphdb with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void apply(final Traversal.Admin<?, ?> traversal) {
    for (final VertexStep originalVertexStep : TraversalHelper.getStepsOfClass(VertexStep.class, traversal)) {
        final HBaseVertexStep<?> hbaseVertexStep = new HBaseVertexStep<>(originalVertexStep);
        TraversalHelper.replaceStep(originalVertexStep, hbaseVertexStep, traversal);
        Step<?, ?> currentStep = hbaseVertexStep.getNextStep();
        while (currentStep instanceof HasStep || currentStep instanceof NoOpBarrierStep) {
            if (currentStep instanceof HasStep) {
                for (final HasContainer hasContainer : ((HasContainerHolder) currentStep).getHasContainers()) {
                    hbaseVertexStep.addHasContainer(hasContainer);
                }
                TraversalHelper.copyLabels(currentStep, currentStep.getPreviousStep(), false);
                traversal.removeStep(currentStep);
            }
            currentStep = currentStep.getNextStep();
        }
    }
}
 
Example #6
Source File: SubgraphStrategyTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldNotRetainMarkers() {
    final SubgraphStrategy strategy = SubgraphStrategy.build().vertices(__.<Vertex>out().hasLabel("person")).create();
    final Traversal.Admin<?, ?> t = out().inE().asAdmin();
    t.setStrategies(t.getStrategies().clone().addStrategies(strategy, StandardVerificationStrategy.instance()));
    t.applyStrategies();
    assertEquals(t.getSteps().get(0).getClass(), VertexStep.class);
    assertEquals(t.getSteps().get(1).getClass(), TraversalFilterStep.class);
    assertEquals(AndStep.class, ((TraversalFilterStep<?>) t.getSteps().get(1)).getLocalChildren().get(0).getStartStep().getClass());
    assertEquals(0, ((TraversalFilterStep<?>) t.getSteps().get(1)).getLocalChildren().get(0).getStartStep().getLabels().size());
    assertEquals(t.getSteps().get(2).getClass(), EdgeVertexStep.class);
    assertEquals(t.getSteps().get(3).getClass(), TraversalFilterStep.class);
    assertEquals(VertexStep.class, ((TraversalFilterStep<?>) t.getSteps().get(3)).getLocalChildren().get(0).getStartStep().getClass());
    assertEquals(0, ((TraversalFilterStep<?>) t.getSteps().get(3)).getLocalChildren().get(0).getStartStep().getLabels().size());
    TraversalHelper.getStepsOfAssignableClassRecursively(Step.class, t).forEach(step -> assertTrue(step.getLabels().isEmpty()));
}
 
Example #7
Source File: SparkSingleIterationStrategy.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Override
public void apply(final Traversal.Admin<?, ?> traversal) {
    final Graph graph = traversal.getGraph().orElse(EmptyGraph.instance()); // best guess at what the graph will be as its dynamically determined
    for (final TraversalVertexProgramStep step : TraversalHelper.getStepsOfClass(TraversalVertexProgramStep.class, traversal)) {
        final Traversal.Admin<?, ?> computerTraversal = step.generateProgram(graph, EmptyMemory.instance()).getTraversal().get().clone();
        if (!computerTraversal.isLocked())
            computerTraversal.applyStrategies();
        ///
        boolean doesMessagePass = TraversalHelper.hasStepOfAssignableClassRecursively(Scope.global, MULTI_ITERATION_CLASSES, computerTraversal);
        if (!doesMessagePass) {
            for (final VertexStep vertexStep : TraversalHelper.getStepsOfAssignableClassRecursively(Scope.global, VertexStep.class, computerTraversal)) {
                if (vertexStep.returnsVertex() || !vertexStep.getDirection().equals(Direction.OUT)) { // in-edges require message pass in OLAP
                    doesMessagePass = true;
                    break;
                }
            }
        }
        if (!doesMessagePass &&
                !MessagePassingReductionStrategy.endsWithElement(computerTraversal.getEndStep()) &&
                !(computerTraversal.getTraverserRequirements().contains(TraverserRequirement.LABELED_PATH) || // TODO: remove this when dynamic detachment is available in 3.3.0
                        computerTraversal.getTraverserRequirements().contains(TraverserRequirement.PATH))) {  // TODO: remove this when dynamic detachment is available in 3.3.0
            step.setComputer(step.getComputer()
                    // if no message passing, don't partition the loaded graph
                    .configure(Constants.GREMLIN_SPARK_SKIP_PARTITIONER, true)
                    // if no message passing, don't cache the loaded graph
                    .configure(Constants.GREMLIN_SPARK_SKIP_GRAPH_CACHE, true));
        }
    }
}
 
Example #8
Source File: SchemaTableTree.java    From sqlg with MIT License 5 votes vote down vote up
SchemaTableTree addChild(
        SchemaTable schemaTable,
        Direction direction,
        Class<? extends Element> elementClass,
        ReplacedStep<?, ?> replacedStep,
        Set<String> labels) {

    Preconditions.checkState(replacedStep.getStep() instanceof VertexStep, "addChild can only be called for a VertexStep, found %s", replacedStep.getStep().getClass().getSimpleName());
    //Do not emit the edge schema table for a vertex step.
    boolean emit;
    if (elementClass.isAssignableFrom(Vertex.class)) {
        emit = schemaTable.isVertexTable() && replacedStep.isEmit();
    } else if (elementClass.isAssignableFrom(Edge.class)) {
        emit = schemaTable.isEdgeTable() && replacedStep.isEmit();
    } else {
        throw new IllegalStateException(String.format("BUG: Expected %s, instead found %s", "Edge or Vertex", elementClass.getSimpleName()));
    }

    return addChild(
            schemaTable,
            direction,
            elementClass,
            replacedStep.getHasContainers(),
            replacedStep.getAndOrHasContainers(),
            replacedStep.getSqlgComparatorHolder(),
            replacedStep.getSqlgComparatorHolder().getComparators(),
            replacedStep.getSqlgRangeHolder(),
            replacedStep.getRestrictedProperties(),
            replacedStep.getDepth(),
            false,
            emit,
            replacedStep.isUntilFirst(),
            replacedStep.isLeftJoin(),
            replacedStep.isDrop(),
            labels);
}
 
Example #9
Source File: SubgraphStrategyTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldAddBothFiltersAfterVertex() {
    final SubgraphStrategy strategy = SubgraphStrategy.build().edges(__.identity()).vertices(__.identity()).create();
    final Traversal t = __.inE();
    strategy.apply(t.asAdmin());
    final VertexStep vertexStep = (VertexStep) t.asAdmin().getStartStep();
    assertEquals(TraversalFilterStep.class, vertexStep.getNextStep().getClass());
    final TraversalFilterStep h = (TraversalFilterStep) t.asAdmin().getEndStep();
    assertEquals(1, h.getLocalChildren().size());
    assertThat(((DefaultGraphTraversal) h.getLocalChildren().get(0)).getEndStep(), CoreMatchers.instanceOf(TraversalFilterStep.class));
}
 
Example #10
Source File: SubgraphStrategyTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldAddFilterAfterEdge() {
    final SubgraphStrategy strategy = SubgraphStrategy.build().edges(__.identity()).create();
    final Traversal t = __.inE();
    strategy.apply(t.asAdmin());
    final VertexStep vertexStep = (VertexStep) t.asAdmin().getStartStep();
    assertEquals(TraversalFilterStep.class, vertexStep.getNextStep().getClass());
    final TraversalFilterStep h = (TraversalFilterStep) t.asAdmin().getEndStep();
    assertEquals(1, h.getLocalChildren().size());
    assertThat(((DefaultGraphTraversal) h.getLocalChildren().get(0)).getEndStep(), CoreMatchers.instanceOf(IdentityStep.class));
}
 
Example #11
Source File: TraversalHelperTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldSetPreviousStepToEmptyStep() {
    final Traversal.Admin<?, ?> traversal = __.V().out().asAdmin();
    //transform the traversal to __.V().not(out())
    //the VertexStep's previousStep should be the EmptyStep
    Optional<VertexStep> vertexStepOpt = TraversalHelper.getFirstStepOfAssignableClass(VertexStep.class, traversal);
    assertTrue(vertexStepOpt.isPresent());
    Traversal.Admin<?,?> inner = __.start().asAdmin();
    inner.addStep(0, vertexStepOpt.get());
    TraversalHelper.replaceStep(vertexStepOpt.get(), new NotStep<>(__.identity().asAdmin(), inner), traversal);
    List<VertexStep> vertexSteps = TraversalHelper.getStepsOfAssignableClassRecursively(VertexStep.class, traversal);
    assertEquals(1, vertexSteps.size());
    VertexStep vertexStep = vertexSteps.get(0);
    assertTrue("Expected the previousStep to be an EmptyStep, found instead " + vertexStep.getPreviousStep().toString(),vertexStep.getPreviousStep() == EmptyStep.instance());
}
 
Example #12
Source File: VertexProgramHelper.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
public static <S, E> Traversal.Admin<S, E> reverse(final Traversal.Admin<S, E> traversal) {
    for (final Step step : traversal.getSteps()) {
        if (step instanceof VertexStep)
            ((VertexStep) step).reverseDirection();
        if (step instanceof EdgeVertexStep)
            ((EdgeVertexStep) step).reverseDirection();
    }
    return traversal;
}
 
Example #13
Source File: MessagePassingReductionStrategy.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
public static final boolean endsWithElement(Step<?, ?> currentStep) {
    while (!(currentStep instanceof EmptyStep)) {
        if (currentStep instanceof VertexStep) // only inE, in, and out send messages
            return (((VertexStep) currentStep).returnsVertex() || !((VertexStep) currentStep).getDirection().equals(Direction.OUT));
        else if (currentStep instanceof EdgeVertexStep) // TODO: add GraphStep but only if its mid-traversal V()/E()
            return true;
        else if (currentStep instanceof TraversalFlatMapStep || currentStep instanceof TraversalMapStep || currentStep instanceof LocalStep)
            return endsWithElement(((TraversalParent) currentStep).getLocalChildren().get(0).getEndStep());
        else if (!(currentStep instanceof FilterStep || currentStep instanceof SideEffectStep || currentStep instanceof IdentityStep || currentStep instanceof Barrier))
            return false;
        currentStep = currentStep.getPreviousStep();
    }
    return false;
}
 
Example #14
Source File: EdgeLabelVerificationStrategy.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Override
void verify(final Traversal.Admin<?, ?> traversal) throws VerificationException {
    for (final Step<?, ?> step : traversal.getSteps()) {
        if (step instanceof VertexStep && ((VertexStep) step).getEdgeLabels().length == 0) {
            final String msg = String.format(
                    "The provided traversal contains a vertex step without any specified edge label: %s\nAlways " +
                            "specify edge labels which restrict traversal paths ensuring optimal performance.", step);
            throw new VerificationException(msg, traversal);
        }
    }
}
 
Example #15
Source File: ReplacedStep.java    From sqlg with MIT License 5 votes vote down vote up
private Set<SchemaTableTree> appendPath(SchemaTableTree schemaTableTree) {
    if (this.step instanceof VertexStep) {
        return appendPathForVertexStep(schemaTableTree);
    } else if (this.step instanceof EdgeVertexStep) {
        return appendPathForEdgeVertexStep(schemaTableTree);
    } else if (this.step instanceof EdgeOtherVertexStep) {
        return appendPathForEdgeOtherVertexStep(schemaTableTree);
    } else {
        throw new IllegalStateException("Only VertexStep, EdgeVertexStep and EdgeOtherVertexStep are handled! Found " + this.step.getClass().getName());
    }
}
 
Example #16
Source File: VertexStrategy.java    From sqlg with MIT License 5 votes vote down vote up
/**
 * EdgeOtherVertexStep can not be optimized as the direction information is lost.
 *
 * @param stepIterator The steps to iterate. Unused for the VertexStrategy
 * @param step         The current step.
 * @param pathCount    The path count.
 * @return true if the optimization can continue else false.
 */
@SuppressWarnings("unchecked")
@Override
protected boolean doFirst(ListIterator<Step<?, ?>> stepIterator, Step<?, ?> step, MutableInt pathCount) {
    if (step instanceof SelectOneStep) {
        if (stepIterator.hasNext()) {
            stepIterator.next();
            return true;
        } else {
            return false;
        }
    }
    if (!(step instanceof VertexStep ||
            step instanceof EdgeVertexStep ||
            step instanceof ChooseStep ||
            step instanceof OptionalStep)) {
        return false;
    }
    if (step instanceof OptionalStep) {
        if (unoptimizableOptionalStep((OptionalStep<?>) step)) {
            return false;
        }
    }
    if (step instanceof ChooseStep) {
        if (unoptimizableChooseStep((ChooseStep<?, ?, ?>) step)) {
            return false;
        }
    }
    this.sqlgStep = constructSqlgStep(step);
    TraversalHelper.insertBeforeStep(this.sqlgStep, step, this.traversal);
    return true;
}
 
Example #17
Source File: IncidentToAdjacentStrategy.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
/**
 * Optimizes the given edge-emitting step and the vertex-emitting step by replacing them with a single
 * vertex-emitting step.
 *
 * @param traversal the traversal that holds the given steps
 * @param step1     the edge-emitting step to replace
 * @param step2     the vertex-emitting step to replace
 */
private static void optimizeSteps(final Traversal.Admin traversal, final VertexStep step1, final Step step2) {
    final Step newStep = new VertexStep(traversal, Vertex.class, step1.getDirection(), step1.getEdgeLabels());
    for (final String label : (Iterable<String>) step2.getLabels()) {
        newStep.addLabel(label);
    }
    TraversalHelper.replaceStep(step1, newStep, traversal);
    traversal.removeStep(step2);
}
 
Example #18
Source File: IncidentToAdjacentStrategy.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Override
public void apply(final Traversal.Admin<?, ?> traversal) {
    // using a hidden label marker to denote whether the traversal should not be processed by this strategy
    if ((traversal.isRoot() || traversal.getParent() instanceof VertexProgramStep) &&
            TraversalHelper.hasStepOfAssignableClassRecursively(INVALIDATING_STEP_CLASSES, traversal))
        TraversalHelper.applyTraversalRecursively(t -> t.getStartStep().addLabel(MARKER), traversal);
    if (traversal.getStartStep().getLabels().contains(MARKER)) {
        traversal.getStartStep().removeLabel(MARKER);
        return;
    }
    ////////////////////////////////////////////////////////////////////////////
    final Collection<Pair<VertexStep, Step>> stepsToReplace = new ArrayList<>();
    Step prev = null;
    for (final Step curr : traversal.getSteps()) {
        if (curr instanceof TraversalParent) {
            ((TraversalParent) curr).getLocalChildren().forEach(this::apply);
            ((TraversalParent) curr).getGlobalChildren().forEach(this::apply);
        }
        if (isOptimizable(prev, curr)) {
            stepsToReplace.add(Pair.with((VertexStep) prev, curr));
        }
        prev = curr;
    }
    if (!stepsToReplace.isEmpty()) {
        for (final Pair<VertexStep, Step> pair : stepsToReplace) {
            optimizeSteps(traversal, pair.getValue0(), pair.getValue1());
        }
    }
}
 
Example #19
Source File: HugeVertexStep.java    From hugegraph with Apache License 2.0 5 votes vote down vote up
public HugeVertexStep(final VertexStep<E> originVertexStep) {
    super(originVertexStep.getTraversal(),
          originVertexStep.getReturnClass(),
          originVertexStep.getDirection(),
          originVertexStep.getEdgeLabels());
    originVertexStep.getLabels().forEach(this::addLabel);
}
 
Example #20
Source File: JanusGraphTraversalUtil.java    From grakn with GNU Affero General Public License v3.0 5 votes vote down vote up
private static void getMultiQueryCompatibleStepsFromChildTraversal(Traversal.Admin<?, ?> childTraversal, Step parentStep, Set<Step> multiQueryCompatibleSteps) {
    Step firstStep = childTraversal.getStartStep();
    while (firstStep instanceof StartStep || firstStep instanceof SideEffectStep) {
        // Want the next step if this is a side effect
        firstStep = firstStep.getNextStep();
    }
    if (firstStep.getClass().isAssignableFrom(VertexStep.class)) {
        multiQueryCompatibleSteps.add(parentStep);
    }
}
 
Example #21
Source File: IncidentToAdjacentStrategy.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
/**
 * Checks whether a given step is optimizable or not.
 *
 * @param step1 an edge-emitting step
 * @param step2 a vertex-emitting step
 * @return <code>true</code> if step1 is not labeled and emits edges and step2 emits vertices,
 * otherwise <code>false</code>
 */
private static boolean isOptimizable(final Step step1, final Step step2) {
    if (step1 instanceof VertexStep && ((VertexStep) step1).returnsEdge() && step1.getLabels().isEmpty()) {
        final Direction step1Dir = ((VertexStep) step1).getDirection();
        if (step1Dir.equals(Direction.BOTH)) {
            return step2 instanceof EdgeOtherVertexStep;
        }
        return step2 instanceof EdgeOtherVertexStep || (step2 instanceof EdgeVertexStep &&
                ((EdgeVertexStep) step2).getDirection().equals(step1Dir.opposite()));
    }
    return false;
}
 
Example #22
Source File: TinkerMessenger.java    From tinkergraph-gremlin with Apache License 2.0 4 votes vote down vote up
private static Direction getDirection(final Traversal.Admin<Vertex, Edge> incidentTraversal) {
    final VertexStep step = TraversalHelper.getLastStepOfAssignableClass(VertexStep.class, incidentTraversal).get();
    return step.getDirection();
}
 
Example #23
Source File: ReplacedStep.java    From sqlg with MIT License 4 votes vote down vote up
public boolean isVertexStep() {
    return this.step instanceof VertexStep;
}
 
Example #24
Source File: LazyBarrierStrategy.java    From tinkerpop with Apache License 2.0 4 votes vote down vote up
@Override
public void apply(final Traversal.Admin<?, ?> traversal) {
    // drop() is a problem for bulked edge/meta properties because of Property equality changes in TINKERPOP-2318
    // which made it so that a Property is equal if the key/value is equal. as a result, they bulk together which
    // is fine for almost all cases except when you wish to drop the property.
    if (TraversalHelper.onGraphComputer(traversal) ||
            traversal.getTraverserRequirements().contains(TraverserRequirement.PATH) ||
            TraversalHelper.hasStepOfAssignableClass(DropStep.class, traversal))
        return;

    boolean foundFlatMap = false;
    boolean labeledPath = false;
    for (int i = 0; i < traversal.getSteps().size(); i++) {
        final Step<?, ?> step = traversal.getSteps().get(i);

        if (step instanceof PathProcessor) {
            final Set<String> keepLabels = ((PathProcessor) step).getKeepLabels();
            if (null != keepLabels && keepLabels.isEmpty()) // if no more path data, then start barrier'ing again
                labeledPath = false;
        }
        if (step instanceof FlatMapStep &&
                !(step instanceof VertexStep && ((VertexStep) step).returnsEdge()) ||
                (step instanceof GraphStep &&
                        (i > 0 || ((GraphStep) step).getIds().length >= BIG_START_SIZE ||
                                (((GraphStep) step).getIds().length == 0 && !(step.getNextStep() instanceof HasStep))))) {

            // NoneStep, EmptyStep signify the end of the traversal where no barriers are really going to be
            // helpful after that. ProfileSideEffectStep means the traversal had profile() called on it and if
            // we don't account for that a barrier will inject at the end of the traversal where it wouldn't
            // be otherwise. LazyBarrierStrategy executes before the finalization strategy of ProfileStrategy
            // so additionally injected ProfileSideEffectStep instances should not have effect here.
            if (foundFlatMap && !labeledPath &&
                    !(step.getNextStep() instanceof Barrier) &&
                    !(step.getNextStep() instanceof NoneStep) &&
                    !(step.getNextStep() instanceof EmptyStep) &&
                    !(step.getNextStep() instanceof ProfileSideEffectStep)) {
                final Step noOpBarrierStep = new NoOpBarrierStep<>(traversal, MAX_BARRIER_SIZE);
                TraversalHelper.copyLabels(step, noOpBarrierStep, true);
                TraversalHelper.insertAfterStep(noOpBarrierStep, step, traversal);
            } else
                foundFlatMap = true;
        }
        if (!step.getLabels().isEmpty())
            labeledPath = true;

    }
}
 
Example #25
Source File: JanusGraphVertexStep.java    From grakn with GNU Affero General Public License v3.0 4 votes vote down vote up
public JanusGraphVertexStep(VertexStep<E> originalStep) {
    super(originalStep.getTraversal(), originalStep.getReturnClass(), originalStep.getDirection(), originalStep.getEdgeLabels());
    originalStep.getLabels().forEach(this::addLabel);
    this.hasContainers = new ArrayList<>();
    this.limit = Query.NO_LIMIT;
}
 
Example #26
Source File: MessagePassingReductionStrategy.java    From tinkerpop with Apache License 2.0 4 votes vote down vote up
@Override
public void apply(final Traversal.Admin<?, ?> traversal) {
    // only process the first traversal step in an OLAP chain
    TraversalHelper.getFirstStepOfAssignableClass(TraversalVertexProgramStep.class, traversal).ifPresent(step -> {
        final Graph graph = traversal.getGraph().orElse(EmptyGraph.instance()); // best guess at what the graph will be as its dynamically determined
        final Traversal.Admin<?, ?> compiledComputerTraversal = step.generateProgram(graph, EmptyMemory.instance()).getTraversal().get().clone();
        if (!compiledComputerTraversal.isLocked())
            compiledComputerTraversal.applyStrategies();
        if (!TraversalHelper.hasStepOfAssignableClassRecursively(Arrays.asList(LocalStep.class, LambdaHolder.class), compiledComputerTraversal) && // don't do anything with lambdas or locals as this leads to unknown adjacencies
                !compiledComputerTraversal.getTraverserRequirements().contains(TraverserRequirement.PATH) &&            // when dynamic detachment is provided in 3.3.0, remove this (TODO)
                !compiledComputerTraversal.getTraverserRequirements().contains(TraverserRequirement.LABELED_PATH) &&    // when dynamic detachment is provided in 3.3.0, remove this (TODO)
                !(TraversalHelper.getStepsOfAssignableClass(TraversalParent.class, compiledComputerTraversal).          // this is a strict precaution that could be loosed with deeper logic on barriers in global children
                        stream().
                        filter(parent -> !parent.getGlobalChildren().isEmpty()).findAny().isPresent())) {
            final Traversal.Admin<?, ?> computerTraversal = step.computerTraversal.get().clone();
            // apply the strategies up to this point
            final List<TraversalStrategy<?>> strategies = step.getTraversal().getStrategies().toList();
            final int indexOfStrategy = strategies.indexOf(MessagePassingReductionStrategy.instance());
            if (indexOfStrategy > 0)
                TraversalHelper.applySingleLevelStrategies(step.getTraversal(), computerTraversal, strategies.get(indexOfStrategy - 1).getClass());
            if (computerTraversal.getSteps().size() > 1 &&
                    !(computerTraversal.getStartStep().getNextStep() instanceof Barrier) &&
                    TraversalHelper.hasStepOfAssignableClassRecursively(Arrays.asList(VertexStep.class, EdgeVertexStep.class), computerTraversal) &&
                    TraversalHelper.isLocalStarGraph(computerTraversal)) {
                Step barrier = (Step) TraversalHelper.getFirstStepOfAssignableClass(Barrier.class, computerTraversal).orElse(null);

                // if the barrier isn't present gotta check for uncapped profile() which can happen if you do
                // profile("metrics") - see below for more worries
                if (null == barrier) {
                    final ProfileSideEffectStep pses = TraversalHelper.getFirstStepOfAssignableClass(ProfileSideEffectStep.class, computerTraversal).orElse(null);
                    if (pses != null)
                        barrier = pses.getPreviousStep();
                }

                // if the barrier is a profile() then we'll mess stuff up if we wrap that in a local() as in:
                //    local(..., ProfileSideEffectStep)
                // which won't compute right on OLAP (or anything??). By stepping back we cut things off at
                // just before the ProfileSideEffectStep to go inside the local() so that ProfileSideEffectStep
                // shows up just after it
                //
                // why does this strategy need to know so much about profile!?!
                if (barrier != null && barrier.getPreviousStep() instanceof ProfileSideEffectStep)
                    barrier = barrier.getPreviousStep().getPreviousStep();

                if (MessagePassingReductionStrategy.insertElementId(barrier)) // out().count() -> out().id().count()
                    TraversalHelper.insertBeforeStep(new IdStep(computerTraversal), barrier, computerTraversal);
                if (!(MessagePassingReductionStrategy.endsWithElement(null == barrier ? computerTraversal.getEndStep() : barrier))) {
                    Traversal.Admin newChildTraversal = new DefaultGraphTraversal<>();
                    TraversalHelper.removeToTraversal(computerTraversal.getStartStep() instanceof GraphStep ?
                            computerTraversal.getStartStep().getNextStep() :
                            (Step) computerTraversal.getStartStep(), null == barrier ?
                            EmptyStep.instance() :
                            barrier, newChildTraversal);
                    newChildTraversal = newChildTraversal.getSteps().size() > 1 ? (Traversal.Admin) __.local(newChildTraversal) : newChildTraversal;
                    if (null == barrier)
                        TraversalHelper.insertTraversal(0, newChildTraversal, computerTraversal);
                    else
                        TraversalHelper.insertTraversal(barrier.getPreviousStep(), newChildTraversal, computerTraversal);
                }
            }
            step.setComputerTraversal(computerTraversal);
        }
    });
}
 
Example #27
Source File: SparkMessenger.java    From tinkerpop with Apache License 2.0 4 votes vote down vote up
private static Direction getOppositeDirection(final Traversal.Admin<Vertex, Edge> incidentTraversal) {
    final VertexStep step = TraversalHelper.getLastStepOfAssignableClass(VertexStep.class, incidentTraversal).get();
    return step.getDirection().opposite();
}
 
Example #28
Source File: AdjacentVertexFilterOptimizerStrategy.java    From grakn with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void apply(Traversal.Admin<?, ?> traversal) {

    TraversalHelper.getStepsOfClass(TraversalFilterStep.class, traversal).forEach(originalStep -> {
        // Check if this filter traversal matches the pattern: _.inV/outV/otherV.is(x)
        Traversal.Admin<?, ?> filterTraversal = (Traversal.Admin<?, ?>) originalStep.getLocalChildren().get(0);
        List<Step> steps = filterTraversal.getSteps();
        if (steps.size() == 2 &&
                (steps.get(0) instanceof EdgeVertexStep || steps.get(0) instanceof EdgeOtherVertexStep) &&
                (steps.get(1) instanceof IsStep)) {
            //Get the direction in which we filter on the adjacent vertex (or null if not a valid adjacency filter)
            Direction direction = null;
            if (steps.get(0) instanceof EdgeVertexStep) {
                EdgeVertexStep evs = (EdgeVertexStep) steps.get(0);
                if (evs.getDirection() != Direction.BOTH) direction = evs.getDirection();
            } else {
                direction = Direction.BOTH;
            }
            P predicate = ((IsStep) steps.get(1)).getPredicate();
            //Check that we have a valid direction and a valid vertex filter predicate
            if (direction != null && predicate.getBiPredicate() == Compare.eq && predicate.getValue() instanceof Vertex) {
                Vertex vertex = (Vertex) predicate.getValue();

                //Now, check that this step is preceded by VertexStep that returns edges
                Step<?, ?> currentStep = originalStep.getPreviousStep();
                while (currentStep != EmptyStep.instance()) {
                    if (!(currentStep instanceof HasStep) && !(currentStep instanceof IdentityStep)) {
                        break;
                    } //We can jump over other steps as we move backward
                    currentStep = currentStep.getPreviousStep();
                }
                if (currentStep instanceof VertexStep) {
                    VertexStep vertexStep = (VertexStep) currentStep;
                    if (vertexStep.returnsEdge()
                            && (direction == Direction.BOTH || direction.equals(vertexStep.getDirection().opposite()))) {
                        //Now replace the step with a has condition
                        TraversalHelper.replaceStep(originalStep,
                            new HasStep(traversal, new HasContainer(ImplicitKey.ADJACENT_ID.name(), P.eq(vertex))),
                            traversal);
                    }
                }

            }
        }

    });

}
 
Example #29
Source File: TinkerMessenger.java    From tinkerpop with Apache License 2.0 4 votes vote down vote up
private static Direction getDirection(final Traversal.Admin<Vertex, Edge> incidentTraversal) {
    final VertexStep step = TraversalHelper.getLastStepOfAssignableClass(VertexStep.class, incidentTraversal).get();
    return step.getDirection();
}
 
Example #30
Source File: TitanVertexStep.java    From titan1withtp3.1 with Apache License 2.0 4 votes vote down vote up
public TitanVertexStep(VertexStep<E> originalStep) {
    super(originalStep.getTraversal(), originalStep.getReturnClass(), originalStep.getDirection(), originalStep.getEdgeLabels());
    originalStep.getLabels().forEach(this::addLabel);
    this.hasContainers = new ArrayList<>();
    this.limit = Query.NO_LIMIT;
}