org.apache.tinkerpop.gremlin.process.traversal.Step Java Examples

The following examples show how to use org.apache.tinkerpop.gremlin.process.traversal.Step. 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 Project: hugegraph   Author: hugegraph   File: TraversalUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static void extractOrder(Step<?, ?> newStep,
                                Traversal.Admin<?, ?> traversal) {
    Step<?, ?> step = newStep;
    do {
        step = step.getNextStep();
        if (step instanceof OrderGlobalStep) {
            QueryHolder holder = (QueryHolder) newStep;
            @SuppressWarnings("resource")
            OrderGlobalStep<?, ?> orderStep = (OrderGlobalStep<?, ?>) step;
            orderStep.getComparators().forEach(comp -> {
                ElementValueComparator<?> comparator =
                        (ElementValueComparator<?>) comp.getValue1();
                holder.orderBy(comparator.getPropertyKey(),
                               (Order) comparator.getValueComparator());
            });
            TraversalHelper.copyLabels(step, newStep, false);
            traversal.removeStep(step);
        }
        step = step.getNextStep();
    } while (step instanceof OrderGlobalStep ||
             step instanceof IdentityStep);
}
 
Example #2
Source Project: grakn   Author: graknlabs   File: JanusGraphTraversalUtil.java    License: 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 #3
Source Project: grakn   Author: graknlabs   File: HasStepFolder.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
static void foldInHasContainer(HasStepFolder janusgraphStep, Traversal.Admin<?, ?> traversal, Traversal<?, ?> rootTraversal) {
    Step<?, ?> currentStep = janusgraphStep.getNextStep();
    while (true) {
        if (currentStep instanceof OrStep && janusgraphStep instanceof JanusGraphStep) {
            for (Traversal.Admin<?, ?> child : ((OrStep<?>) currentStep).getLocalChildren()) {
                if (!validFoldInHasContainer(child.getStartStep(), false)) {
                    return;
                }
            }
            ((OrStep<?>) currentStep).getLocalChildren().forEach(t -> localFoldInHasContainer(janusgraphStep, t.getStartStep(), t, rootTraversal));
            traversal.removeStep(currentStep);
        } else if (currentStep instanceof HasContainerHolder) {
            Iterable<HasContainer> containers = ((HasContainerHolder) currentStep).getHasContainers().stream().map(c -> JanusGraphPredicate.Converter.convert(c)).collect(Collectors.toList());
            if (validFoldInHasContainer(currentStep, true)) {
                janusgraphStep.addAll(containers);
                currentStep.getLabels().forEach(janusgraphStep::addLabel);
                traversal.removeStep(currentStep);
            }
        } else if (!(currentStep instanceof IdentityStep) && !(currentStep instanceof NoOpBarrierStep) && !(currentStep instanceof HasContainerHolder)) {
            break;
        }
        currentStep = currentStep.getNextStep();
    }
}
 
Example #4
Source Project: hgraphdb   Author: rayokota   File: HBaseVertexStepStrategy.java    License: 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 #5
Source Project: tinkerpop   Author: apache   File: AbstractGremlinTest.java    License: 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 #6
Source Project: sqlg   Author: pietermartin   File: VertexStrategy.java    License: MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
void combineSteps() {
    List<Step<?, ?>> steps = new ArrayList(this.traversal.asAdmin().getSteps());
    ListIterator<Step<?, ?>> stepIterator = steps.listIterator();
    MutableInt pathCount = new MutableInt(0);
    while (stepIterator.hasNext()) {
        Step<?, ?> step = stepIterator.next();
        if (this.reset) {
            this.reset = false;
            this.sqlgStep = null;
        }
        if (isReplaceableStep(step.getClass())) {
            stepIterator.previous();
            boolean keepGoing = handleStep(stepIterator, pathCount);
            if (!keepGoing) {
                break;
            }
        } else {
            //restart
            this.sqlgStep = null;
        }
    }
}
 
Example #7
Source Project: tinkerpop   Author: apache   File: ProfileTest.java    License: Apache License 2.0 6 votes vote down vote up
private void validate_g_V_out_out_profile_modern(final Traversal traversal, final TraversalMetrics traversalMetrics) {
    traversalMetrics.toString(); // ensure no exceptions are thrown

    assumeThat("The following assertions apply to TinkerGraph only as provider strategies can alter the steps to not comply with expectations",
            graph.getClass().getSimpleName(), equalTo("TinkerGraph"));

    Metrics metrics = traversalMetrics.getMetrics(0);
    assertEquals(6, metrics.getCount(TraversalMetrics.TRAVERSER_COUNT_ID).longValue());
    assertEquals(6, metrics.getCount(TraversalMetrics.ELEMENT_COUNT_ID).longValue());

    metrics = traversalMetrics.getMetrics(1);
    assertEquals(6, metrics.getCount(TraversalMetrics.ELEMENT_COUNT_ID).longValue());
    assertNotEquals(0, metrics.getCount(TraversalMetrics.TRAVERSER_COUNT_ID).longValue());

    metrics = traversalMetrics.getMetrics(2);
    assertEquals(2, metrics.getCount(TraversalMetrics.ELEMENT_COUNT_ID).longValue());
    assertNotEquals(0, metrics.getCount(TraversalMetrics.TRAVERSER_COUNT_ID).longValue());

    if (!onGraphComputer(traversal.asAdmin())) {
        // Every other step should be a Profile step
        List<Step> steps = traversal.asAdmin().getSteps();
        for (int ii = 1; ii <= 6; ii += 2) {
            assertEquals("Every other Step should be a ProfileStep.", ProfileStep.class, steps.get(ii).getClass());
        }
    }
}
 
Example #8
Source Project: tinkerpop   Author: apache   File: TinkerGraphCountStrategy.java    License: 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 #9
Source Project: tinkerpop   Author: apache   File: TraversalHelper.java    License: 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 #10
Source Project: tinkerpop   Author: apache   File: LP_NL_O_OB_S_SE_SL_Traverser.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public <R> Admin<R> split(final R r, final Step<T, R> step) {
    final LP_NL_O_OB_S_SE_SL_Traverser<R> clone = (LP_NL_O_OB_S_SE_SL_Traverser<R>) super.split(r, step);
    clone.nestedLoops = new Stack<>();
    for(LabelledCounter lc : this.nestedLoops)
        clone.nestedLoops.push((LabelledCounter) lc.clone());

    if (this.loopNames != null) {
        clone.loopNames = new ReferenceMap(ReferenceMap.HARD, ReferenceMap.WEAK);

        final Iterator loopNamesIterator = this.loopNames.entrySet().iterator();
        while (loopNamesIterator.hasNext()) {
            final ReferenceMap.Entry pair = (ReferenceMap.Entry) loopNamesIterator.next();

            final int idx = this.nestedLoops.indexOf(pair.getValue());
            if (idx != -1)
                clone.loopNames.put(pair.getKey(), clone.nestedLoops.get(idx));
        }
    }

    return clone;
}
 
Example #11
Source Project: tinkerpop   Author: apache   File: TraversalHelper.java    License: Apache License 2.0 5 votes vote down vote up
private static Set<Scoping.Variable> getVariableLocations(final Set<Scoping.Variable> variables, final Traversal.Admin<?, ?> traversal) {
    if (variables.size() == 2) return variables;    // has both START and END so no need to compute further
    final Step<?, ?> startStep = traversal.getStartStep();
    if (StartStep.isVariableStartStep(startStep))
        variables.add(Scoping.Variable.START);
    else if (startStep instanceof WherePredicateStep) {
        if (((WherePredicateStep) startStep).getStartKey().isPresent())
            variables.add(Scoping.Variable.START);
    } else if (startStep instanceof WhereTraversalStep.WhereStartStep) {
        if (!((WhereTraversalStep.WhereStartStep) startStep).getScopeKeys().isEmpty())
            variables.add(Scoping.Variable.START);
    } else if (startStep instanceof MatchStep.MatchStartStep) {
        if (((MatchStep.MatchStartStep) startStep).getSelectKey().isPresent())
            variables.add(Scoping.Variable.START);
    } else if (startStep instanceof MatchStep) {
        for (final Traversal.Admin<?, ?> global : ((MatchStep<?, ?>) startStep).getGlobalChildren()) {
            TraversalHelper.getVariableLocations(variables, global);
        }
    } else if (startStep instanceof ConnectiveStep || startStep instanceof NotStep || startStep instanceof WhereTraversalStep) {
        for (final Traversal.Admin<?, ?> local : ((TraversalParent) startStep).getLocalChildren()) {
            TraversalHelper.getVariableLocations(variables, local);
        }
    }
    ///
    final Step<?, ?> endStep = traversal.getEndStep();
    if (endStep instanceof WherePredicateStep) {
        if (((WherePredicateStep) endStep).getStartKey().isPresent())
            variables.add(Scoping.Variable.END);
    } else if (endStep instanceof WhereTraversalStep.WhereEndStep) {
        if (!((WhereTraversalStep.WhereEndStep) endStep).getScopeKeys().isEmpty())
            variables.add(Scoping.Variable.END);
    } else if (endStep instanceof MatchStep.MatchEndStep) {
        if (((MatchStep.MatchEndStep) endStep).getMatchKey().isPresent())
            variables.add(Scoping.Variable.END);
    } else if (!endStep.getLabels().isEmpty())
        variables.add(Scoping.Variable.END);
    ///
    return variables;
}
 
Example #12
Source Project: tinkerpop   Author: apache   File: CountStrategy.java    License: Apache License 2.0 5 votes vote down vote up
private boolean doStrategy(final Step step) {
    if (!(step instanceof CountGlobalStep) ||
            !(step.getNextStep() instanceof IsStep) ||
            step.getPreviousStep() instanceof RangeGlobalStep) // if a RangeStep was provided, assume that the user knows what he's doing
        return false;

    final Step parent = step.getTraversal().getParent().asStep();
    return (parent instanceof FilterStep || parent.getLabels().isEmpty()) && // if the parent is labeled, then the count matters
            !(parent.getNextStep() instanceof MatchStep.MatchEndStep && // if this is in a pattern match, then don't do it.
                    ((MatchStep.MatchEndStep) parent.getNextStep()).getMatchKey().isPresent());
}
 
Example #13
Source Project: sqlg   Author: pietermartin   File: SqlgTraversalUtil.java    License: 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;
}
 
Example #14
Source Project: tinkerpop   Author: apache   File: ComputerFinalizationStrategy.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void apply(Traversal.Admin<?, ?> traversal) {
    if (!TraversalHelper.onGraphComputer(traversal) || !TraversalHelper.isGlobalChild(traversal))
        return;

    for (final Step<?, ?> step : traversal.getSteps()) {
        if (step instanceof GraphComputing)
            ((GraphComputing) step).onGraphComputer();
    }
}
 
Example #15
Source Project: hugegraph   Author: hugegraph   File: TraversalUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static void extractCount(Step<?, ?> newStep,
                                Traversal.Admin<?, ?> traversal) {
    Step<?, ?> step = newStep;
    do {
        step = step.getNextStep();
        if (step instanceof CountGlobalStep) {
            QueryHolder holder = (QueryHolder) newStep;
            holder.setCount();
        }
    } while (step instanceof CountGlobalStep ||
             step instanceof FilterStep ||
             step instanceof IdentityStep ||
             step instanceof NoOpBarrierStep);
}
 
Example #16
Source Project: tinkerpop   Author: apache   File: TraversalHelper.java    License: Apache License 2.0 5 votes vote down vote up
public static boolean hasStepOfClass(final Traversal.Admin<?, ?> traversal, final Class<?>... classesToCheck) {
    for (final Step<?, ?> step : traversal.getSteps()) {
        for (final Class<?> classToCheck : classesToCheck) {
            if (classToCheck.isInstance(step))
                return true;
        }
    }
    return false;
}
 
Example #17
Source Project: tinkerpop   Author: apache   File: InlineFilterStrategy.java    License: Apache License 2.0 5 votes vote down vote up
private static final boolean processMatchStep(final MatchStep<?, ?> step, final Traversal.Admin<?, ?> traversal) {
    if (step.getPreviousStep() instanceof EmptyStep)
        return false;
    boolean changed = false;
    final String startLabel = MatchStep.Helper.computeStartLabel(step.getGlobalChildren());
    for (final Traversal.Admin<?, ?> matchTraversal : new ArrayList<>(step.getGlobalChildren())) {
        if (TraversalHelper.hasAllStepsOfClass(matchTraversal,
                HasStep.class,
                MatchStep.MatchStartStep.class,
                MatchStep.MatchEndStep.class) &&
                matchTraversal.getStartStep() instanceof MatchStep.MatchStartStep &&
                startLabel.equals(((MatchStep.MatchStartStep) matchTraversal.getStartStep()).getSelectKey().orElse(null))) {
            changed = true;
            step.removeGlobalChild(matchTraversal);
            final String endLabel = ((MatchStep.MatchEndStep) matchTraversal.getEndStep()).getMatchKey().orElse(null); // why would this exist? but just in case
            matchTraversal.removeStep(0);                                       // remove MatchStartStep
            matchTraversal.removeStep(matchTraversal.getSteps().size() - 1);    // remove MatchEndStep
            TraversalHelper.applySingleLevelStrategies(traversal, matchTraversal, InlineFilterStrategy.class);

            matchTraversal.getEndStep().addLabel(startLabel);
            if (null != endLabel) matchTraversal.getEndStep().addLabel(endLabel);
            TraversalHelper.insertTraversal((Step) step.getPreviousStep(), matchTraversal, traversal);
        }
    }
    if (step.getGlobalChildren().isEmpty())
        traversal.removeStep(step);
    return changed;
}
 
Example #18
Source Project: hugegraph   Author: hugegraph   File: TraversalUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static QueryHolder firstPageStep(GraphTraversal<?, ?> traversal) {
    for (final Step<?, ?> step : traversal.asAdmin().getSteps()) {
        if (step instanceof QueryHolder &&
            ((QueryHolder) step).queryInfo().paging()) {
            return (QueryHolder) step;
        }
    }
    return null;
}
 
Example #19
Source Project: tinkerpop   Author: apache   File: VertexProgramStrategy.java    License: Apache License 2.0 5 votes vote down vote up
private static Step<?, ?> getFirstLegalOLAPStep(Step<?, ?> currentStep) {
    while (!(currentStep instanceof EmptyStep)) {
        if (!(currentStep instanceof VertexComputing))
            return currentStep;
        currentStep = currentStep.getNextStep();
    }
    return EmptyStep.instance();
}
 
Example #20
Source Project: sqlg   Author: pietermartin   File: SqlgStartStepStrategy.java    License: MIT License 5 votes vote down vote up
@Override
public void apply(final Traversal.Admin<?, ?> traversal) {
    //Only optimize SqlgGraph. StarGraph also passes through here.
    if (!(traversal.getGraph().orElseThrow(IllegalStateException::new) instanceof SqlgGraph)) {
        return;
    }
    if (!SqlgTraversalUtil.mayOptimize(traversal)) {
        return;
    }
    while (true) {
        Optional<StartStep> startStepOptional = TraversalHelper.getLastStepOfAssignableClass(StartStep.class, traversal);
        if (startStepOptional.isPresent()) {
            StartStep<?> startStep = startStepOptional.get();


            SqlgStartStepBarrier<?> sqlgStartStepBarrier = new SqlgStartStepBarrier<>(traversal, startStep);
            for (String label : startStep.getLabels()) {
                sqlgStartStepBarrier.addLabel(label);
            }

            //noinspection unchecked
            TraversalHelper.replaceStep((Step) startStep, sqlgStartStepBarrier, traversal);
        } else {
            break;
        }
    }
}
 
Example #21
Source Project: tinkerpop   Author: apache   File: TraversalHelperTest.java    License: Apache License 2.0 5 votes vote down vote up
private static void validateToyTraversal(final Traversal traversal) {
    assertEquals(traversal.asAdmin().getSteps().size(), 3);

    assertEquals(IdentityStep.class, traversal.asAdmin().getSteps().get(0).getClass());
    assertEquals(HasStep.class, traversal.asAdmin().getSteps().get(1).getClass());
    assertEquals(LambdaFilterStep.class, traversal.asAdmin().getSteps().get(2).getClass());

    // IDENTITY STEP
    assertEquals(EmptyStep.class, ((Step) traversal.asAdmin().getSteps().get(0)).getPreviousStep().getClass());
    assertEquals(HasStep.class, ((Step) traversal.asAdmin().getSteps().get(0)).getNextStep().getClass());
    assertEquals(LambdaFilterStep.class, ((Step) traversal.asAdmin().getSteps().get(0)).getNextStep().getNextStep().getClass());
    assertEquals(EmptyStep.class, ((Step) traversal.asAdmin().getSteps().get(0)).getNextStep().getNextStep().getNextStep().getClass());

    // HAS STEP
    assertEquals(IdentityStep.class, ((Step) traversal.asAdmin().getSteps().get(1)).getPreviousStep().getClass());
    assertEquals(EmptyStep.class, ((Step) traversal.asAdmin().getSteps().get(1)).getPreviousStep().getPreviousStep().getClass());
    assertEquals(LambdaFilterStep.class, ((Step) traversal.asAdmin().getSteps().get(1)).getNextStep().getClass());
    assertEquals(EmptyStep.class, ((Step) traversal.asAdmin().getSteps().get(1)).getNextStep().getNextStep().getClass());

    // FILTER STEP
    assertEquals(HasStep.class, ((Step) traversal.asAdmin().getSteps().get(2)).getPreviousStep().getClass());
    assertEquals(IdentityStep.class, ((Step) traversal.asAdmin().getSteps().get(2)).getPreviousStep().getPreviousStep().getClass());
    assertEquals(EmptyStep.class, ((Step) traversal.asAdmin().getSteps().get(2)).getPreviousStep().getPreviousStep().getPreviousStep().getClass());
    assertEquals(EmptyStep.class, ((Step) traversal.asAdmin().getSteps().get(2)).getNextStep().getClass());

    assertEquals(3, traversal.asAdmin().getSteps().size());
}
 
Example #22
Source Project: tinkerpop   Author: apache   File: PathUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static Set<String> getReferencedLabelsAfterStep(Step<?, ?> step) {
    final Set<String> labels = new HashSet<>();
    while (!(step instanceof EmptyStep)) {
        labels.addAll(PathUtil.getReferencedLabels(step));
        step = step.getNextStep();
    }
    return labels;
}
 
Example #23
Source Project: grakn   Author: graknlabs   File: JanusGraphTraversalUtil.java    License: 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 #24
Source Project: grakn   Author: graknlabs   File: HasStepFolder.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
static void foldInIds(HasStepFolder janusgraphStep, Traversal.Admin<?, ?> traversal) {
        Step<?, ?> currentStep = janusgraphStep.getNextStep();
        while (true) {
            if (currentStep instanceof HasContainerHolder) {
                HasContainerHolder hasContainerHolder = (HasContainerHolder) currentStep;
                GraphStep graphStep = (GraphStep) janusgraphStep;
                // HasContainer collection that we get back is immutable so we keep track of which containers
                // need to be deleted after they've been folded into the JanusGraphStep and then remove them from their
                // step using HasContainer.removeHasContainer
                List<HasContainer> removableHasContainers = new ArrayList<>();
                Set<String> stepLabels = currentStep.getLabels();
                hasContainerHolder.getHasContainers().forEach(hasContainer -> {
                    if (GraphStep.processHasContainerIds(graphStep, hasContainer)) {
                        stepLabels.forEach(janusgraphStep::addLabel);
                        // this has container is no longer needed because its ids will be folded into the JanusGraphStep
                        removableHasContainers.add(hasContainer);
                    }
                });

                if (!removableHasContainers.isEmpty()) {
                    removableHasContainers.forEach(hasContainerHolder::removeHasContainer);
                }
                // if all has containers have been removed, the current step can be removed
                if (hasContainerHolder.getHasContainers().isEmpty()) {
                    traversal.removeStep(currentStep);
                }
//            } else if (currentStep instanceof IdentityStep) {
//                // do nothing, has no impact
//            } else if (currentStep instanceof NoOpBarrierStep) {
//                // do nothing, has no impact
            } else {
                break;
            }
            currentStep = currentStep.getNextStep();
        }
    }
 
Example #25
Source Project: grakn   Author: graknlabs   File: HasStepFolder.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
static boolean validFoldInHasContainer(Step<?, ?> tinkerpopStep, boolean defaultValue) {
    Step<?, ?> currentStep = tinkerpopStep;
    Boolean toReturn = null;
    while (!(currentStep instanceof EmptyStep)) {
        if (currentStep instanceof HasContainerHolder) {
            Iterable<HasContainer> containers = ((HasContainerHolder) currentStep).getHasContainers();
            toReturn = toReturn == null ? validJanusGraphHas(containers) : toReturn && validJanusGraphHas(containers);
        } else if (!(currentStep instanceof IdentityStep) && !(currentStep instanceof NoOpBarrierStep) && !(currentStep instanceof RangeGlobalStep) && !(currentStep instanceof OrderGlobalStep)) {
            toReturn = toReturn != null && (toReturn && defaultValue);
            break;
        }
        currentStep = currentStep.getNextStep();
    }
    return Boolean.TRUE.equals(toReturn);
}
 
Example #26
Source Project: tinkerpop   Author: apache   File: MasterExecutor.java    License: Apache License 2.0 5 votes vote down vote up
private static boolean isLocalElement(final Step<?, ?> step) {
    return step instanceof PropertiesStep || step instanceof PropertyMapStep ||
            step instanceof IdStep || step instanceof LabelStep || step instanceof SackStep ||
            step instanceof PropertyKeyStep || step instanceof PropertyValueStep ||
            step instanceof TailGlobalStep || step instanceof RangeGlobalStep || step instanceof HasStep ||
            step instanceof ConnectiveStep;
}
 
Example #27
Source Project: tinkerpop   Author: apache   File: TinkerCountGlobalStep.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Traverser.Admin<Long> processNextStart() throws NoSuchElementException {
    if (!this.done) {
        this.done = true;
        final TinkerGraph graph = (TinkerGraph) this.getTraversal().getGraph().get();
        return this.getTraversal().getTraverserGenerator().generate(Vertex.class.isAssignableFrom(this.elementClass) ?
                        (long) TinkerHelper.getVertices(graph).size() :
                        (long) TinkerHelper.getEdges(graph).size(),
                (Step) this, 1L);
    } else
        throw FastNoSuchElementException.instance();
}
 
Example #28
Source Project: titan1withtp3.1   Author: graben1437   File: FulgoraUtil.java    License: Apache License 2.0 5 votes vote down vote up
private static void verifyIncidentTraversal(FulgoraElementTraversal<Vertex,Edge> traversal) {
    //First step must be TitanVertexStep
    List<Step> steps = traversal.getSteps();
    Step<Vertex,?> startStep = steps.get(0);
    Preconditions.checkArgument(startStep instanceof TitanVertexStep &&
            TitanTraversalUtil.isEdgeReturnStep((TitanVertexStep) startStep),"Expected first step to be an edge step but found: %s",startStep);
    Optional<Step> violatingStep = steps.stream().filter(s -> !(s instanceof TitanVertexStep ||
            s instanceof OrderGlobalStep || s instanceof OrderLocalStep ||
                    s instanceof IdentityStep || s instanceof FilterStep)).findAny();
    if (violatingStep.isPresent()) throw new IllegalArgumentException("Encountered unsupported step in incident traversal: " + violatingStep.get());
}
 
Example #29
Source Project: titan1withtp3.1   Author: graben1437   File: TitanGraphStepStrategy.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void apply(final Traversal.Admin<?, ?> traversal) {
    if (traversal.getEngine().isComputer())
        return;

    TraversalHelper.getStepsOfClass(GraphStep.class, traversal).forEach(originalGraphStep -> {
        if (originalGraphStep.getIds() == null || originalGraphStep.getIds().length == 0) {
            //Try to optimize for index calls
            final TitanGraphStep<?, ?> titanGraphStep = new TitanGraphStep<>(originalGraphStep);
            TraversalHelper.replaceStep(originalGraphStep, (Step) titanGraphStep, traversal);

            HasStepFolder.foldInHasContainer(titanGraphStep, traversal);
            HasStepFolder.foldInOrder(titanGraphStep, traversal, traversal, titanGraphStep.returnsVertex());
            HasStepFolder.foldInRange(titanGraphStep, traversal);
        } else {
            //Make sure that any provided "start" elements are instantiated in the current transaction
            Object[] ids = originalGraphStep.getIds();
            ElementUtils.verifyArgsMustBeEitherIdorElement(ids);
            if (ids[0] instanceof Element) {
                //GraphStep constructor ensures that the entire array is elements
                final Object[] elementIds = new Object[ids.length];
                for (int i = 0; i < ids.length; i++) {
                    elementIds[i] = ((Element) ids[i]).id();
                }
                originalGraphStep.setIteratorSupplier(() -> (Iterator) (originalGraphStep.returnsVertex() ?
                        ((Graph) originalGraphStep.getTraversal().getGraph().get()).vertices(elementIds) :
                        ((Graph) originalGraphStep.getTraversal().getGraph().get()).edges(elementIds)));
            }
        }
    });
}
 
Example #30
Source Project: tinkerpop   Author: apache   File: FilterRankingStrategy.java    License: 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;
}