org.apache.tinkerpop.gremlin.process.traversal.step.TraversalParent Java Examples

The following examples show how to use org.apache.tinkerpop.gremlin.process.traversal.step.TraversalParent. 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: TinkerGraphCountStrategy.java    From tinkergraph-gremlin with Apache License 2.0 6 votes vote down vote up
@Override
public void apply(final Traversal.Admin<?, ?> traversal) {
    if (!(traversal.getParent() instanceof EmptyStep) || TraversalHelper.onGraphComputer(traversal))
        return;
    final List<Step> steps = traversal.getSteps();
    if (steps.size() < 2 ||
            !(steps.get(0) instanceof GraphStep) ||
            0 != ((GraphStep) steps.get(0)).getIds().length ||
            !(steps.get(steps.size() - 1) instanceof CountGlobalStep))
        return;
    for (int i = 1; i < steps.size() - 1; i++) {
        final Step current = steps.get(i);
        if (!(//current instanceof MapStep ||  // MapSteps will not necessarily emit an element as demonstrated in https://issues.apache.org/jira/browse/TINKERPOP-1958
                current instanceof IdentityStep ||
                current instanceof NoOpBarrierStep ||
                current instanceof CollectingBarrierStep) ||
                (current instanceof TraversalParent &&
                        TraversalHelper.anyStepRecursively(s -> (s instanceof SideEffectStep || s instanceof AggregateStep), (TraversalParent) current)))
            return;
    }
    final Class<? extends Element> elementClass = ((GraphStep<?, ?>) steps.get(0)).getReturnClass();
    TraversalHelper.removeAllSteps(traversal);
    traversal.addStep(new TinkerCountGlobalStep<>(traversal, elementClass));
}
 
Example #2
Source File: TinkerGraphCountStrategy.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Override
public void apply(final Traversal.Admin<?, ?> traversal) {
    if (!(traversal.isRoot()) || TraversalHelper.onGraphComputer(traversal))
        return;
    final List<Step> steps = traversal.getSteps();
    if (steps.size() < 2 ||
            !(steps.get(0) instanceof GraphStep) ||
            0 != ((GraphStep) steps.get(0)).getIds().length ||
            !(steps.get(steps.size() - 1) instanceof CountGlobalStep))
        return;
    for (int i = 1; i < steps.size() - 1; i++) {
        final Step current = steps.get(i);
        if (!(//current instanceof MapStep ||  // MapSteps will not necessarily emit an element as demonstrated in https://issues.apache.org/jira/browse/TINKERPOP-1958
                current instanceof IdentityStep ||
                current instanceof NoOpBarrierStep ||
                current instanceof CollectingBarrierStep) ||
                (current instanceof TraversalParent &&
                        TraversalHelper.anyStepRecursively(s -> (s instanceof SideEffectStep || s instanceof AggregateGlobalStep), (TraversalParent) current)))
            return;
    }
    final Class<? extends Element> elementClass = ((GraphStep<?, ?>) steps.get(0)).getReturnClass();
    TraversalHelper.removeAllSteps(traversal);
    traversal.addStep(new TinkerCountGlobalStep<>(traversal, elementClass));
}
 
Example #3
Source File: AbstractGremlinTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
private static void verifyUniqueStepIds(final Traversal.Admin<?, ?> traversal, final int depth, final Set<String> ids) {
    for (final Step step : traversal.asAdmin().getSteps()) {
        /*for (int i = 0; i < depth; i++) System.out.print("\t");
        System.out.println(step.getId() + " --> " + step);*/
        if (!ids.add(step.getId())) {
            fail("The following step id already exists: " + step.getId() + "---" + step);
        }
        if (step instanceof TraversalParent) {
            for (final Traversal.Admin<?, ?> globalTraversal : ((TraversalParent) step).getGlobalChildren()) {
                verifyUniqueStepIds(globalTraversal, depth + 1, ids);
            }
            for (final Traversal.Admin<?, ?> localTraversal : ((TraversalParent) step).getLocalChildren()) {
                verifyUniqueStepIds(localTraversal, depth + 1, ids);
            }
        }
    }
}
 
Example #4
Source File: PathRetractionStrategyTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
private List<Object> getKeepLabels(final Traversal.Admin<?, ?> traversal) {
    List<Object> keepLabels = new ArrayList<>();
    for (Step step : traversal.getSteps()) {
        if (step instanceof PathProcessor) {
            final Set<String> keepers = ((PathProcessor) step).getKeepLabels();
            if (keepers != null)
                keepLabels.add(keepers);
        }
        if (step instanceof TraversalParent) {
            final TraversalParent parent = (TraversalParent) step;
            final List<Traversal.Admin<?, ?>> children = new ArrayList<>();
            children.addAll(parent.getGlobalChildren());
            children.addAll(parent.getLocalChildren());
            for (final Traversal.Admin<?, ?> child : children) {
                final List<Object> childLabels = getKeepLabels(child);
                if (childLabels.size() > 0) {
                    keepLabels.add(childLabels);
                }
            }
        }
    }
    return keepLabels;
}
 
Example #5
Source File: TraversalHelperTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldIdentifyGlobalChildren() {
    final Traversal.Admin<?, ?> globalChild = __.select("a", "b").by("name").asAdmin();
    TraversalParent parent = new RepeatStep<>(new DefaultTraversal());
    ((RepeatStep) parent).setRepeatTraversal(globalChild);
    assertTrue(TraversalHelper.isGlobalChild(globalChild));
    ///
    new UnionStep<>(new DefaultTraversal(), globalChild);
    assertTrue(TraversalHelper.isGlobalChild(globalChild));
    ///
    new TraversalVertexProgramStep(new DefaultTraversal<>(), globalChild);
    assertTrue(TraversalHelper.isGlobalChild(globalChild));
    ///
    final Traversal.Admin<?, ?> remoteRemoteChild = __.repeat(globalChild).asAdmin();
    new UnionStep<>(new DefaultTraversal(), remoteRemoteChild);
    assertTrue(TraversalHelper.isGlobalChild(globalChild));
}
 
Example #6
Source File: DefaultTraversalTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
private void recursiveTestTraversals(final Traversal.Admin<?, ?> traversal, final TraversalSideEffects sideEffects, final Set aValue, final int bValue) {
    assertTrue(traversal.getSideEffects() == sideEffects);
    assertEquals(sideEffects.keys().size(), traversal.getSideEffects().keys().size());
    assertEquals(bValue, traversal.getSideEffects().<Integer>get("b").intValue());
    assertEquals(aValue.size(), traversal.getSideEffects().<Set>get("a").size());
    assertFalse(aValue.stream().filter(k -> !traversal.getSideEffects().<Set>get("a").contains(k)).findAny().isPresent());
    assertFalse(traversal.getSideEffects().exists("c"));
    for (final Step<?, ?> step : traversal.getSteps()) {
        assertTrue(step.getTraversal().getSideEffects() == sideEffects);
        assertEquals(sideEffects.keys().size(), step.getTraversal().getSideEffects().keys().size());
        assertEquals(bValue, step.getTraversal().getSideEffects().<Integer>get("b").intValue());
        assertEquals(aValue.size(), step.getTraversal().getSideEffects().<Set>get("a").size());
        assertFalse(aValue.stream().filter(k -> !step.getTraversal().getSideEffects().<Set>get("a").contains(k)).findAny().isPresent());
        assertFalse(step.getTraversal().getSideEffects().exists("c"));
        if (step instanceof TraversalParent) {
            ((TraversalParent) step).getGlobalChildren().forEach(t -> this.recursiveTestTraversals(t, sideEffects, aValue, bValue));
            ((TraversalParent) step).getLocalChildren().forEach(t -> this.recursiveTestTraversals(t, sideEffects, aValue, bValue));
        }
    }
}
 
Example #7
Source File: FilterRankingStrategy.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
private static boolean usesLabels(final Step<?, ?> step, final Set<String> labels) {
    if (step instanceof LambdaHolder)
        return true;
    if (step instanceof Scoping) {
        final Set<String> scopes = ((Scoping) step).getScopeKeys();
        for (final String label : labels) {
            if (scopes.contains(label))
                return true;
        }
    }
    if (step instanceof TraversalParent) {
        if (TraversalHelper.anyStepRecursively(s -> usesLabels(s, labels), (TraversalParent) step))
            return true;
    }
    return false;
}
 
Example #8
Source File: AdjacentToIncidentStrategy.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Override
public void apply(final Traversal.Admin<?, ?> traversal) {
    final List<Step> steps = traversal.getSteps();
    final int size = steps.size() - 1;
    Step prev = null;
    for (int i = 0; i <= size; i++) {
        final Step curr = steps.get(i);
        if (i == size && isOptimizable(curr)) {
            final TraversalParent parent = curr.getTraversal().getParent();
            if (parent instanceof NotStep || parent instanceof TraversalFilterStep || parent instanceof WhereTraversalStep || parent instanceof ConnectiveStep) {
                optimizeStep(traversal, curr);
            }
        } else if (isOptimizable(prev)) {
            if (curr instanceof CountGlobalStep) {
                optimizeStep(traversal, prev);
            }
        }
        if (!(curr instanceof RangeGlobalStep)) {
            prev = curr;
        }
    }
}
 
Example #9
Source File: ByModulatorOptimizationStrategy.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Override
public void apply(final Traversal.Admin<?, ?> traversal) {
    final Step step = traversal.getParent().asStep();
    if (step instanceof ByModulating && step instanceof TraversalParent) {
        final TraversalParent byModulatingStep = (TraversalParent) step;
        if (step instanceof Grouping) {
            final Grouping grouping = (Grouping) step;
            optimizeByModulatingTraversal(byModulatingStep, grouping.getKeyTraversal());

            // the value by() needs different handling because by(Traversal) only equals by(String) or by(T)
            // if the traversal does a fold().
            final Traversal.Admin<?, ?> currentValueTraversal = grouping.getValueTraversal();
            final List<Step> stepsInCurrentValueTraversal = currentValueTraversal.getSteps();
            if (stepsInCurrentValueTraversal.size() == 1 && stepsInCurrentValueTraversal.get(0) instanceof IdentityStep)
                optimizeForStep(byModulatingStep, currentValueTraversal, stepsInCurrentValueTraversal.get(0));
            else if (stepsInCurrentValueTraversal.size() == 2 && stepsInCurrentValueTraversal.get(1) instanceof FoldStep)
                optimizeForStep(byModulatingStep, currentValueTraversal, stepsInCurrentValueTraversal.get(0));

        } else {
            for (final Traversal.Admin<?, ?> byModulatingTraversal : byModulatingStep.getLocalChildren()) {
                optimizeByModulatingTraversal(byModulatingStep, byModulatingTraversal);
            }
        }
    }
}
 
Example #10
Source File: ByModulatorOptimizationStrategy.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
private void optimizeForStep(final TraversalParent step, final Traversal.Admin<?, ?> traversal, final Step singleStep) {
    if (singleStep instanceof PropertiesStep) {
        final PropertiesStep ps = (PropertiesStep) singleStep;
        if (ps.getReturnType().equals(PropertyType.VALUE) && ps.getPropertyKeys().length == 1) {
            step.replaceLocalChild(traversal, new ValueTraversal<>(ps.getPropertyKeys()[0]));
        }
    } else if (singleStep instanceof IdStep) {
        step.replaceLocalChild(traversal, new TokenTraversal<>(T.id));
    } else if (singleStep instanceof LabelStep) {
        step.replaceLocalChild(traversal, new TokenTraversal<>(T.label));
    } else if (singleStep instanceof PropertyKeyStep) {
        step.replaceLocalChild(traversal, new TokenTraversal<>(T.key));
    } else if (singleStep instanceof PropertyValueStep) {
        step.replaceLocalChild(traversal, new TokenTraversal<>(T.value));
    } else if (singleStep instanceof IdentityStep) {
        step.replaceLocalChild(traversal, new IdentityTraversal<>());
    }
}
 
Example #11
Source File: TraversalHelper.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
public static boolean hasLabels(final Traversal.Admin<?, ?> traversal) {
    for (final Step<?, ?> step : traversal.getSteps()) {
        for (final String label : step.getLabels()) {
            if (!Graph.Hidden.isHidden(label))
                return true;
        }
        if (step instanceof TraversalParent) {
            for (final Traversal.Admin<?, ?> local : ((TraversalParent) step).getLocalChildren()) {
                if (TraversalHelper.hasLabels(local))
                    return true;
            }
            for (final Traversal.Admin<?, ?> global : ((TraversalParent) step).getGlobalChildren()) {
                if (TraversalHelper.hasLabels(global))
                    return true;
            }
        }
    }
    return false;
}
 
Example #12
Source File: TraversalHelper.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
/**
 * Apply the provider {@link Consumer} function to the provided {@link Traversal} and all of its children.
 *
 * @param consumer  the function to apply to the each traversal in the tree
 * @param traversal the root traversal to start application
 */
public static void applyTraversalRecursively(final Consumer<Traversal.Admin<?, ?>> consumer, final Traversal.Admin<?, ?> traversal) {
    consumer.accept(traversal);

    // we get accused of concurrentmodification if we try a for(Iterable)
    final List<Step> steps = traversal.getSteps();
    for (int ix = 0; ix < steps.size(); ix++) {
        final Step step = steps.get(ix);
        if (step instanceof TraversalParent) {
            for (final Traversal.Admin<?, ?> local : ((TraversalParent) step).getLocalChildren()) {
                applyTraversalRecursively(consumer, local);
            }
            for (final Traversal.Admin<?, ?> global : ((TraversalParent) step).getGlobalChildren()) {
                applyTraversalRecursively(consumer, global);
            }
        }
    }
}
 
Example #13
Source File: TraversalHelper.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
/**
 * Determine if the traversal has any of the supplied steps of an assignable class in the current {@link Traversal}
 * and its {@link Scope} child traversals.
 *
 * @param scope       whether to check global or local children (null for both).
 * @param stepClasses the step classes to look for
 * @param traversal   the traversal in which to look for the given step classes
 * @return <code>true</code> if any step in the given traversal (and its child traversals) is an instance of a class
 * provided in <code>stepClasses</code>, otherwise <code>false</code>.
 */
public static boolean hasStepOfAssignableClassRecursively(final Scope scope, final Collection<Class> stepClasses, final Traversal.Admin<?, ?> traversal) {
    if (stepClasses.size() == 1)
        return hasStepOfAssignableClassRecursively(stepClasses.iterator().next(), traversal);
    for (final Step<?, ?> step : traversal.getSteps()) {
        if (IteratorUtils.anyMatch(stepClasses.iterator(), stepClass -> stepClass.isAssignableFrom(step.getClass()))) {
            return true;
        }
        if (step instanceof TraversalParent) {
            if (null == scope || Scope.local.equals(scope)) {
                for (final Traversal.Admin<?, ?> localChild : ((TraversalParent) step).getLocalChildren()) {
                    if (hasStepOfAssignableClassRecursively(stepClasses, localChild)) return true;
                }
            }
            if (null == scope || Scope.global.equals(scope)) {
                for (final Traversal.Admin<?, ?> globalChild : ((TraversalParent) step).getGlobalChildren()) {
                    if (hasStepOfAssignableClassRecursively(stepClasses, globalChild)) return true;
                }
            }
        }
    }
    return false;
}
 
Example #14
Source File: TraversalHelper.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
/**
 * Determine if the traversal has a step of an assignable class in the current {@link Traversal} and its
 * {@link Scope} child traversals.
 *
 * @param scope     the child traversal scope to check
 * @param stepClass the step class to look for
 * @param traversal the traversal in which to look for the given step class
 * @return <code>true</code> if any step in the given traversal (and its child traversals) is an instance of the
 * given <code>stepClass</code>, otherwise <code>false</code>.
 */
public static boolean hasStepOfAssignableClassRecursively(final Scope scope, final Class stepClass, final Traversal.Admin<?, ?> traversal) {
    for (final Step<?, ?> step : traversal.getSteps()) {
        if (stepClass.isAssignableFrom(step.getClass())) {
            return true;
        }
        if (step instanceof TraversalParent) {
            if (null == scope || Scope.local.equals(scope)) {
                for (final Traversal.Admin<?, ?> localChild : ((TraversalParent) step).getLocalChildren()) {
                    if (hasStepOfAssignableClassRecursively(stepClass, localChild)) return true;
                }
            }
            if (null == scope || Scope.global.equals(scope)) {
                for (final Traversal.Admin<?, ?> globalChild : ((TraversalParent) step).getGlobalChildren()) {
                    if (hasStepOfAssignableClassRecursively(stepClass, globalChild)) return true;
                }
            }
        }
    }
    return false;
}
 
Example #15
Source File: TraversalHelper.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
public static <S> List<S> getStepsOfAssignableClassRecursively(final Scope scope, final Class<S> stepClass, final Traversal.Admin<?, ?> traversal) {
    final List<S> list = new ArrayList<>();
    for (final Step<?, ?> step : traversal.getSteps()) {
        if (stepClass.isAssignableFrom(step.getClass()))
            list.add((S) step);
        if (step instanceof TraversalParent) {
            if (null == scope || Scope.local.equals(scope)) {
                for (final Traversal.Admin<?, ?> localChild : ((TraversalParent) step).getLocalChildren()) {
                    list.addAll(TraversalHelper.getStepsOfAssignableClassRecursively(stepClass, localChild));
                }
            }
            if (null == scope || Scope.global.equals(scope)) {
                for (final Traversal.Admin<?, ?> globalChild : ((TraversalParent) step).getGlobalChildren()) {
                    list.addAll(TraversalHelper.getStepsOfAssignableClassRecursively(stepClass, globalChild));
                }
            }
        }
    }
    return list;
}
 
Example #16
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 #17
Source File: JanusGraphTraversalUtil.java    From grakn with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * This method searches the traversal for traversal parents which are multiQuery compatible.
 * Being multiQuery compatible is not solely determined by the class of the parent step, it
 * must also have a vertex step as the first step in one of its local or global children.
 *
 * @param traversal The traversal in which to search for multiQuery compatible steps
 * @return A list of traversal parents which were multiQuery compatible
 */
public static List<Step> getMultiQueryCompatibleSteps(Traversal.Admin<?, ?> traversal) {
    final Set<Step> multiQueryCompatibleSteps = new HashSet<>();
    for (Step step : traversal.getSteps()) {
        if (isMultiQueryCompatibleStep(step)) {
            Step parentStep = step;
            ((TraversalParent) parentStep).getGlobalChildren().forEach(childTraversal -> getMultiQueryCompatibleStepsFromChildTraversal(childTraversal, parentStep, multiQueryCompatibleSteps));
            ((TraversalParent) parentStep).getLocalChildren().forEach(childTraversal -> getMultiQueryCompatibleStepsFromChildTraversal(childTraversal, parentStep, multiQueryCompatibleSteps));

            if (parentStep instanceof RepeatStep && multiQueryCompatibleSteps.contains(parentStep)) {
                RepeatStep repeatStep = (RepeatStep) parentStep;
                List<RepeatEndStep> repeatEndSteps = TraversalHelper.getStepsOfClass(RepeatEndStep.class, repeatStep.getRepeatTraversal());
                if (repeatEndSteps.size() == 1) {
                    // Want the RepeatEndStep so the start of one iteration can feed into the next
                    multiQueryCompatibleSteps.remove(parentStep);
                    multiQueryCompatibleSteps.add(repeatEndSteps.get(0));
                }
            }
        }
    }
    return Lists.newArrayList(multiQueryCompatibleSteps);
}
 
Example #18
Source File: TraversalHelper.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
/**
 * Determine if any step in {@link Traversal} or its children match the step given the provided {@link Predicate}.
 *
 * @param predicate the match function
 * @param traversal the traversal to perform the action on
 * @return {@code true} if there is a match and {@code false} otherwise
 */
public static boolean anyStepRecursively(final Predicate<Step> predicate, final Traversal.Admin<?, ?> traversal) {
    for (final Step<?, ?> step : traversal.getSteps()) {
        if (predicate.test(step)) {
            return true;
        }

        if (step instanceof TraversalParent && anyStepRecursively(predicate, ((TraversalParent) step))) {
            return true;
        }
    }
    return false;
}
 
Example #19
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 #20
Source File: ParametersTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldIntegrateTraversals() {
    final TraversalParent mock = mock(TraversalParent.class);
    final Parameters parameters = new Parameters();

    // the mock can return nothing of consequence as the return isn't used in this case. we just need to
    // validate that the method gets called as a result of calls to set/integrateTraversals()
    when(mock.integrateChild(__.outE("knows").asAdmin())).thenReturn(null);

    parameters.set(mock, "a", "axe", "a", "ant", "b", "bat", "b", "ball", "c", "cat", "t", __.outE("knows"));

    verify(mock).integrateChild(__.outE("knows").asAdmin());
}
 
Example #21
Source File: StepPositionTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
private void testEachTraversal(final Traversal.Admin<?, ?> traversal) {
    for (final Step step : traversal.getSteps()) {
        assertTrue(StepPosition.isStepId(step.getId()));
        if (step instanceof SideEffectCapable) {
            assertFalse(StepPosition.isStepId(((SideEffectCapable) step).getSideEffectKey()));
        }
        if (step instanceof Scoping) {
            ((Scoping) step).getScopeKeys().forEach(key -> assertFalse(StepPosition.isStepId(key)));
        }
        if (step instanceof TraversalParent) {
            ((TraversalParent) step).getLocalChildren().forEach(this::testEachTraversal);
            ((TraversalParent) step).getGlobalChildren().forEach(this::testEachTraversal);
        }
    }
}
 
Example #22
Source File: AbstractLambdaTraversal.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Override
public void setParent(final TraversalParent step) {
    if (null != this.bypassTraversal) {
        this.bypassTraversal.setParent(step);
        step.integrateChild(this.bypassTraversal);
    }
}
 
Example #23
Source File: PathProcessorStrategyTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
public void doTest() {
    final Traversal.Admin<?, ?> rootTraversal = new DefaultGraphTraversal<>();
    final TraversalParent parent = new TraversalVertexProgramStep(rootTraversal, this.original.asAdmin());
    rootTraversal.addStep(parent.asStep());
    this.original.asAdmin().setParent(parent); // trick it into OLAP
    final TraversalStrategies strategies = new DefaultTraversalStrategies();
    strategies.addStrategies(PathProcessorStrategy.instance());
    for (final TraversalStrategy strategy : this.otherStrategies) {
        strategies.addStrategies(strategy);
    }
    this.original.asAdmin().setStrategies(strategies);
    this.original.asAdmin().applyStrategies();
    assertEquals(this.optimized, this.original);
}
 
Example #24
Source File: FilterRankingStrategy.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
private static int getMaxStepRank(final TraversalParent parent, final int startRank) {
    int maxStepRank = startRank;
    // no filter steps are global parents (yet)
    for (final Traversal.Admin<?, ?> traversal : parent.getLocalChildren()) {
        for (final Step<?, ?> step : traversal.getSteps()) {
            final int stepRank = getStepRank(step);
            if (stepRank > maxStepRank)
                maxStepRank = stepRank;
        }
    }
    return maxStepRank;
}
 
Example #25
Source File: FilterRankingStrategy.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
/**
 * Ranks the given step. Steps with lower ranks can be moved in front of steps with higher ranks. 0 means that
 * the step has no rank and thus is not exchangeable with its neighbors.
 *
 * @param step the step to get a ranking for
 * @return The rank of the given step.
 */
private static int getStepRank(final Step step) {
    final int rank;
    if (!(step instanceof FilterStep || step instanceof OrderGlobalStep))
        return 0;
    else if (step instanceof IsStep || step instanceof ClassFilterStep)
        rank = 1;
    else if (step instanceof HasStep)
        rank = 2;
    else if (step instanceof WherePredicateStep && ((WherePredicateStep) step).getLocalChildren().isEmpty())
        rank = 3;
    else if (step instanceof TraversalFilterStep || step instanceof NotStep)
        rank = 4;
    else if (step instanceof WhereTraversalStep)
        rank = 5;
    else if (step instanceof OrStep)
        rank = 6;
    else if (step instanceof AndStep)
        rank = 7;
    else if (step instanceof WherePredicateStep) // has by()-modulation
        rank = 8;
    else if (step instanceof DedupGlobalStep)
        rank = 9;
    else if (step instanceof OrderGlobalStep)
        rank = 10;
    else
        return 0;
    ////////////
    if (step instanceof TraversalParent)
        return getMaxStepRank((TraversalParent) step, rank);
    else
        return rank;
}
 
Example #26
Source File: MatchStep.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
private Set<String> pullOutVariableStartStepToParent(final Set<String> selectKeys, final Traversal.Admin<?, ?> traversal, boolean testRun) {
    final Step<?, ?> startStep = traversal.getStartStep();
    if (startStep instanceof WhereTraversalStep.WhereStartStep && !((WhereTraversalStep.WhereStartStep) startStep).getScopeKeys().isEmpty()) {
        selectKeys.addAll(((WhereTraversalStep.WhereStartStep<?>) startStep).getScopeKeys());
        if (!testRun) ((WhereTraversalStep.WhereStartStep) startStep).removeScopeKey();
    } else if (startStep instanceof ConnectiveStep || startStep instanceof NotStep) {
        ((TraversalParent) startStep).getLocalChildren().forEach(child -> this.pullOutVariableStartStepToParent(selectKeys, child, testRun));
    }
    return selectKeys;
}
 
Example #27
Source File: PathProcessorStrategy.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
private static int labelCount(final String label, final Traversal.Admin<?, ?> traversal) {
    int count = 0;
    for (final Step step : traversal.getSteps()) {
        if (step.getLabels().contains(label))
            count++;
        if (step instanceof TraversalParent) {
            count = count + ((TraversalParent) step).getLocalChildren().stream().map(t -> labelCount(label, t)).reduce(0, (a, b) -> a + b);
            count = count + ((TraversalParent) step).getGlobalChildren().stream().map(t -> labelCount(label, t)).reduce(0, (a, b) -> a + b);
        }
    }
    return count;
}
 
Example #28
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 #29
Source File: ByModulatorOptimizationStrategy.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
private void optimizeByModulatingTraversal(final TraversalParent step, final Traversal.Admin<?, ?> traversal) {
    if (traversal == null) return;
    final List<Step> steps = traversal.asAdmin().getSteps();
    if (steps.size() == 1) {
        final Step singleStep = steps.get(0);
        optimizeForStep(step, traversal, singleStep);
    }
}
 
Example #30
Source File: SqlgTraversalUtil.java    From sqlg with MIT License 5 votes vote down vote up
public static boolean anyStepRecursively(final Predicate<Step> predicate, final Traversal.Admin<?, ?> traversal) {
    for (final Step<?, ?> step : traversal.getSteps()) {
        if (predicate.test(step)) {
            return true;
        }

        if (step instanceof TraversalParent) {
            if (anyStepRecursively(predicate, ((TraversalParent) step))) {
                return true;
            }
        }
    }
    return false;
}