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

The following examples show how to use org.apache.tinkerpop.gremlin.process.traversal.step.map.EdgeVertexStep. 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: 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 #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: 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 #4
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 #5
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 #6
Source File: ExplainTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
@LoadGraphWith(MODERN)
@IgnoreEngine(TraversalEngine.Type.COMPUTER)
public void g_V_outE_identity_inV_explain() {
    final TraversalExplanation explanation = get_g_V_outE_identity_inV_explain();
    if (explanation.getStrategyTraversals().stream().map(Pair::getValue0).filter(s -> s instanceof IdentityRemovalStrategy || s instanceof IncidentToAdjacentStrategy).count() == 2) {
        printTraversalForm(explanation.getOriginalTraversal());
        boolean beforeIncident = true;
        boolean beforeIdentity = true;
        for (final Pair<TraversalStrategy, Traversal.Admin<?, ?>> pair : explanation.getStrategyTraversals()) {
            if (pair.getValue0().getClass().equals(IncidentToAdjacentStrategy.class))
                beforeIncident = false;
            if (pair.getValue0().getClass().equals(IdentityRemovalStrategy.class))
                beforeIdentity = false;

            if (beforeIdentity)
                assertEquals(1, TraversalHelper.getStepsOfClass(IdentityStep.class, pair.getValue1()).size());

            if (beforeIncident)
                assertEquals(1, TraversalHelper.getStepsOfClass(EdgeVertexStep.class, pair.getValue1()).size());

            if (!beforeIdentity)
                assertEquals(0, TraversalHelper.getStepsOfClass(IdentityStep.class, pair.getValue1()).size());

            if (!beforeIncident)
                assertEquals(0, TraversalHelper.getStepsOfClass(EdgeVertexStep.class, pair.getValue1()).size());
        }
        assertFalse(beforeIncident);
    }
}
 
Example #7
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 #8
Source File: JanusGraphLocalQueryOptimizerStrategy.java    From grakn with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * If this step is followed by a subsequent has step then the properties will need to be
 * known when that has step is executed. The batch property pre-fetching optimisation
 * loads those properties into the vertex cache with a multiQuery preventing the need to
 * go back to the storage back-end for each vertex to fetch the properties.
 *
 * @param traversal         The traversal containing the step
 * @param vertexStep        The step to potentially apply the optimisation to
 * @param nextStep          The next step in the traversal
 * @param txVertexCacheSize The size of the vertex cache
 */
private void applyBatchPropertyPrefetching(Admin<?, ?> traversal, JanusGraphVertexStep vertexStep, Step nextStep, int txVertexCacheSize) {
    if (Vertex.class.isAssignableFrom(vertexStep.getReturnClass())) {
        if (HasStepFolder.foldableHasContainerNoLimit(vertexStep)) {
            vertexStep.setBatchPropertyPrefetching(true);
            vertexStep.setTxVertexCacheSize(txVertexCacheSize);
        }
    } else if (nextStep instanceof EdgeVertexStep) {
        EdgeVertexStep edgeVertexStep = (EdgeVertexStep) nextStep;
        if (HasStepFolder.foldableHasContainerNoLimit(edgeVertexStep)) {
            JanusGraphEdgeVertexStep estep = new JanusGraphEdgeVertexStep(edgeVertexStep, txVertexCacheSize);
            TraversalHelper.replaceStep(nextStep, estep, traversal);
        }
    }
}
 
Example #9
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 #10
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 #11
Source File: SubgraphStrategyTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldAddFilterAfterVertex() {
    final SubgraphStrategy strategy = SubgraphStrategy.build().vertices(__.identity()).create();
    final Traversal t = __.inV();
    strategy.apply(t.asAdmin());
    final EdgeVertexStep edgeVertexStep = (EdgeVertexStep) t.asAdmin().getStartStep();
    assertEquals(TraversalFilterStep.class, edgeVertexStep.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 #12
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 #13
Source File: ReplacedStep.java    From sqlg with MIT License 4 votes vote down vote up
public boolean isEdgeVertexStep() {
    return this.step instanceof EdgeVertexStep;
}
 
Example #14
Source File: ReplacedStep.java    From sqlg with MIT License 4 votes vote down vote up
private Set<SchemaTableTree> appendPathForEdgeVertexStep(SchemaTableTree schemaTableTree) {
    EdgeVertexStep edgeVertexStep = (EdgeVertexStep) this.step;
    return calculatePathFromEdgeToVertex(schemaTableTree, schemaTableTree.getSchemaTable(), edgeVertexStep.getDirection());
}
 
Example #15
Source File: JanusGraphEdgeVertexStep.java    From grakn with GNU Affero General Public License v3.0 4 votes vote down vote up
public JanusGraphEdgeVertexStep(EdgeVertexStep originalStep, int txVertexCacheSize) {
    super(originalStep.getTraversal(), originalStep.getDirection());
    originalStep.getLabels().forEach(this::addLabel);
    this.txVertexCacheSize = txVertexCacheSize;
}
 
Example #16
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 #17
Source File: GraphTraversal.java    From tinkerpop with Apache License 2.0 2 votes vote down vote up
/**
 * Map the {@link Edge} to its incident vertices.
 *
 * @return the traversal with an appended {@link EdgeVertexStep}.
 * @see <a href="http://tinkerpop.apache.org/docs/${project.version}/reference/#vertex-steps" target="_blank">Reference Documentation - Vertex Step</a>
 * @since 3.0.0-incubating
 */
public default GraphTraversal<S, Vertex> bothV() {
    this.asAdmin().getBytecode().addStep(Symbols.bothV);
    return this.asAdmin().addStep(new EdgeVertexStep(this.asAdmin(), Direction.BOTH));
}
 
Example #18
Source File: GraphTraversal.java    From tinkerpop with Apache License 2.0 2 votes vote down vote up
/**
 * Map the {@link Edge} to its outgoing/tail incident {@link Vertex}.
 *
 * @return the traversal with an appended {@link EdgeVertexStep}.
 * @see <a href="http://tinkerpop.apache.org/docs/${project.version}/reference/#vertex-steps" target="_blank">Reference Documentation - Vertex Step</a>
 * @since 3.0.0-incubating
 */
public default GraphTraversal<S, Vertex> outV() {
    this.asAdmin().getBytecode().addStep(Symbols.outV);
    return this.asAdmin().addStep(new EdgeVertexStep(this.asAdmin(), Direction.OUT));
}
 
Example #19
Source File: GraphTraversal.java    From tinkerpop with Apache License 2.0 2 votes vote down vote up
/**
 * Map the {@link Edge} to its incoming/head incident {@link Vertex}.
 *
 * @return the traversal with an appended {@link EdgeVertexStep}.
 * @see <a href="http://tinkerpop.apache.org/docs/${project.version}/reference/#vertex-steps" target="_blank">Reference Documentation - Vertex Step</a>
 * @since 3.0.0-incubating
 */
public default GraphTraversal<S, Vertex> inV() {
    this.asAdmin().getBytecode().addStep(Symbols.inV);
    return this.asAdmin().addStep(new EdgeVertexStep(this.asAdmin(), Direction.IN));
}
 
Example #20
Source File: GraphTraversal.java    From tinkerpop with Apache License 2.0 2 votes vote down vote up
/**
 * Map the {@link Edge} to its incident vertices given the direction.
 *
 * @param direction the direction to traverser from the current edge
 * @return the traversal with an appended {@link EdgeVertexStep}.
 * @see <a href="http://tinkerpop.apache.org/docs/${project.version}/reference/#vertex-steps" target="_blank">Reference Documentation - Vertex Step</a>
 * @since 3.0.0-incubating
 */
public default GraphTraversal<S, Vertex> toV(final Direction direction) {
    this.asAdmin().getBytecode().addStep(Symbols.toV, direction);
    return this.asAdmin().addStep(new EdgeVertexStep(this.asAdmin(), direction));
}