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 File: HBaseVertexStepStrategy.java    From hgraphdb with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void apply(final Traversal.Admin<?, ?> traversal) {
    for (final VertexStep originalVertexStep : TraversalHelper.getStepsOfClass(VertexStep.class, traversal)) {
        final HBaseVertexStep<?> hbaseVertexStep = new HBaseVertexStep<>(originalVertexStep);
        TraversalHelper.replaceStep(originalVertexStep, hbaseVertexStep, traversal);
        Step<?, ?> currentStep = hbaseVertexStep.getNextStep();
        while (currentStep instanceof HasStep || currentStep instanceof NoOpBarrierStep) {
            if (currentStep instanceof HasStep) {
                for (final HasContainer hasContainer : ((HasContainerHolder) currentStep).getHasContainers()) {
                    hbaseVertexStep.addHasContainer(hasContainer);
                }
                TraversalHelper.copyLabels(currentStep, currentStep.getPreviousStep(), false);
                traversal.removeStep(currentStep);
            }
            currentStep = currentStep.getNextStep();
        }
    }
}
 
Example #2
Source File: TraversalUtil.java    From hugegraph with 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 #3
Source File: LP_NL_O_OB_S_SE_SL_Traverser.java    From tinkerpop with 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 #4
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 #5
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 #6
Source File: HasStepFolder.java    From grakn with 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 #7
Source File: ProfileTest.java    From tinkerpop with 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 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 #9
Source File: VertexStrategy.java    From sqlg with 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 #10
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 #11
Source File: PixySplitMergeStep.java    From pixy with Apache License 2.0 5 votes vote down vote up
public PixySplitMergeStep(final Traversal.Admin<S, E> traversal, List<Traversal.Admin<S, E>> pipelines) {
	super(traversal);

	this.pipelines = pipelines;
    this.numPipelines = pipelines.size();
    this.cutPipeList = new ArrayList<List<PixyCutStep>>(numPipelines);
    this.current = 0;
    this.nextStart = null;

    for (Traversal.Admin<S, E> pipeline : pipelines) {
    	List<PixyCutStep> cutPipes = null;

    	for (Step step : pipeline.getSteps()) {
    		if (step instanceof PixyCutStep) {
    			PixyCutStep cutPipe = (PixyCutStep)step; 
     		// This is a cut -- need to track it
 			if (cutPipes == null) {
 				cutPipes = new ArrayList<PixyCutStep>();
 			}

 			cutPipes.add(cutPipe);
    		}
    	}
    	
    	this.cutPipeList.add(cutPipes);
    }
}
 
Example #12
Source File: TestRangeLimit.java    From sqlg with MIT License 5 votes vote down vote up
/**
 * once we've run the traversal, it shouldn't contain the RangeGlobalStep,
 * since it was changed into a Range on the ReplacedStep
 *
 * @param g
 */
private void ensureNoRangeGlobal(GraphTraversal<?, ?> g) {
    DefaultGraphTraversal<?, ?> dgt = (DefaultGraphTraversal<?, ?>) g;
    for (Step<?, ?> s : dgt.getSteps()) {
        Assert.assertFalse(s instanceof RangeGlobalStep<?>);
    }
}
 
Example #13
Source File: IncidentToAdjacentStrategy.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
/**
 * Optimizes the given edge-emitting step and the vertex-emitting step by replacing them with a single
 * vertex-emitting step.
 *
 * @param traversal the traversal that holds the given steps
 * @param step1     the edge-emitting step to replace
 * @param step2     the vertex-emitting step to replace
 */
private static void optimizeSteps(final Traversal.Admin traversal, final VertexStep step1, final Step step2) {
    final Step newStep = new VertexStep(traversal, Vertex.class, step1.getDirection(), step1.getEdgeLabels());
    for (final String label : (Iterable<String>) step2.getLabels()) {
        newStep.addLabel(label);
    }
    TraversalHelper.replaceStep(step1, newStep, traversal);
    traversal.removeStep(step2);
}
 
Example #14
Source File: TraversalHelper.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
public static boolean hasAllStepsOfClass(final Traversal.Admin<?, ?> traversal, final Class<?>... classesToCheck) {
    for (final Step step : traversal.getSteps()) {
        boolean foundInstance = false;
        for (final Class<?> classToCheck : classesToCheck) {
            if (classToCheck.isInstance(step)) {
                foundInstance = true;
                break;
            }
        }
        if (!foundInstance)
            return false;
    }
    return true;
}
 
Example #15
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 #16
Source File: GraphTraversal.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
/**
 * A step modulator that provides a label to the step that can be accessed later in the traversal by other steps.
 *
 * @param stepLabel  the name of the step
 * @param stepLabels additional names for the label
 * @return the traversal with the modified end step
 * @see <a href="http://tinkerpop.apache.org/docs/${project.version}/reference/#as-step" target="_blank">Reference Documentation - As Step</a>
 * @since 3.0.0-incubating
 */
public default GraphTraversal<S, E> as(final String stepLabel, final String... stepLabels) {
    this.asAdmin().getBytecode().addStep(Symbols.as, stepLabel, stepLabels);
    if (this.asAdmin().getSteps().size() == 0) this.asAdmin().addStep(new StartStep<>(this.asAdmin()));
    final Step<?, E> endStep = this.asAdmin().getEndStep();
    endStep.addLabel(stepLabel);
    for (final String label : stepLabels) {
        endStep.addLabel(label);
    }
    return this;
}
 
Example #17
Source File: VertexStrategy.java    From sqlg with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
protected void replaceStepInTraversal(Step stepToReplace, SqlgStep sqlgStep) {
    if (this.traversal.getSteps().contains(stepToReplace)) {
        TraversalHelper.replaceStep(stepToReplace, sqlgStep, this.traversal);
    } else {
        TraversalHelper.insertAfterStep(sqlgStep, stepToReplace.getPreviousStep(), this.traversal);
    }
}
 
Example #18
Source File: TraversalHelper.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
public static <S, E> void removeToTraversal(final Step<S, ?> startStep, final Step<?, E> endStep, final Traversal.Admin<S, E> newTraversal) {
    final Traversal.Admin<?, ?> originalTraversal = startStep.getTraversal();
    Step<?, ?> currentStep = startStep;
    while (currentStep != endStep && !(currentStep instanceof EmptyStep)) {
        final Step<?, ?> temp = currentStep.getNextStep();
        originalTraversal.removeStep(currentStep);
        newTraversal.addStep(currentStep);
        currentStep = temp;
    }
}
 
Example #19
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 #20
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 #21
Source File: TraversalHelper.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the index of a particular step in the {@link Traversal}.
 *
 * @param step      the step to retrieve the index for
 * @param traversal the traversal to perform the action on
 * @return the index of the step or -1 if the step is not present
 */
public static <S, E> int stepIndex(final Step<S, E> step, final Traversal.Admin<?, ?> traversal) {
    int i = 0;
    for (final Step s : traversal.getSteps()) {
        if (s.equals(step, true))
            return i;
        i++;
    }
    return -1;
}
 
Example #22
Source File: WhereTraversalBuilder.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
private static GraphTraversal<?, ?> transform(final E_NotExists expression) {
    final OpBGP opBGP = (OpBGP) expression.getGraphPattern();
    final List<Triple> triples = opBGP.getPattern().getList();
    if (triples.size() != 1) throw new IllegalStateException("Unhandled NOT EXISTS pattern");
    final GraphTraversal<?, ?> traversal = TraversalBuilder.transform(triples.get(0));
    final Step endStep = traversal.asAdmin().getEndStep();
    final String label = (String) endStep.getLabels().iterator().next();
    endStep.removeLabel(label);
    return __.not(traversal);
}
 
Example #23
Source File: B_LP_O_S_SE_SL_Traverser.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Override
public <R> Traverser.Admin<R> split(final R r, final Step<T, R> step) {
    final B_LP_O_S_SE_SL_Traverser<R> clone = (B_LP_O_S_SE_SL_Traverser<R>) super.split(r, step);
    clone.path = clone.path.clone();
    final Set<String> labels = step.getLabels();
    if (!labels.isEmpty()) clone.path = clone.path.extend(r, labels);
    return clone;
}
 
Example #24
Source File: StringFactory.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
public static String stepString(final Step<?, ?> step, final Object... arguments) {
    final StringBuilder builder = new StringBuilder(step.getClass().getSimpleName());
    final List<String> strings = Stream.of(arguments)
            .filter(o -> null != o)
            .filter(o -> {
                if (o instanceof TraversalRing)
                    return !((TraversalRing) o).isEmpty();
                else if (o instanceof Collection)
                    return !((Collection) o).isEmpty();
                else if (o instanceof Map)
                    return !((Map) o).isEmpty();
                else
                    return !o.toString().isEmpty();
            })
            .map(o -> {
                final String string = o.toString();
                return hasLambda(string) ? "lambda" : string;
            }).collect(Collectors.toList());
    if (!strings.isEmpty()) {
        builder.append('(');
        builder.append(String.join(",", strings));
        builder.append(')');
    }
    if (!step.getLabels().isEmpty()) builder.append('@').append(step.getLabels());
    //builder.append("^").append(step.getId());
    return builder.toString();
}
 
Example #25
Source File: TraversalHelper.java    From tinkerpop with 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 #26
Source File: TraversalHelper.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
/**
 * Determine if any child step of a {@link TraversalParent} match the step given the provided {@link Predicate}.
 *
 * @param predicate the match function
 * @param step      the step 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 TraversalParent step) {
    for (final Traversal.Admin<?, ?> localChild : step.getLocalChildren()) {
        if (anyStepRecursively(predicate, localChild)) return true;
    }
    for (final Traversal.Admin<?, ?> globalChild : step.getGlobalChildren()) {
        if (anyStepRecursively(predicate, globalChild)) return true;
    }
    return false;
}
 
Example #27
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 #28
Source File: TitanGraphStepStrategy.java    From titan1withtp3.1 with 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 #29
Source File: FulgoraUtil.java    From titan1withtp3.1 with 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 #30
Source File: TinkerCountGlobalStep.java    From tinkerpop with 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();
}