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

The following examples show how to use org.apache.tinkerpop.gremlin.process.traversal.Scope. 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: 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 #2
Source File: TestGremlinCompileWithHas.java    From sqlg with MIT License 6 votes vote down vote up
@Test
public void g_V_asXaX_out_asXaX_out_asXaX_selectXaX_byXunfold_valuesXnameX_foldX_rangeXlocal_1_2X() {
    loadModern();
    Graph g = this.sqlgGraph;
    assertModernGraph(g, true, false);
    DefaultGraphTraversal<Vertex, String> traversal = (DefaultGraphTraversal<Vertex, String>) g.traversal()
            .V().as("a")
            .out().as("a")
            .out().as("a")
            .<List<String>>select(Pop.all, "a")
            .by(__.unfold().values("name").fold())
            .<String>range(Scope.local, 1, 2);
    Assert.assertEquals(5, traversal.getSteps().size());
    int counter = 0;
    while (traversal.hasNext()) {
        final String s = traversal.next();
        Assert.assertEquals("josh", s);
        counter++;
    }
    Assert.assertEquals(2, counter);
    Assert.assertEquals(3, traversal.getSteps().size());
}
 
Example #3
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 #4
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 #5
Source File: SparkStarBarrierInterceptor.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
public static boolean isLegal(final Traversal.Admin<?, ?> traversal) {
    final Step<?, ?> startStep = traversal.getStartStep();
    final Step<?, ?> endStep = traversal.getEndStep();
    // right now this is not supported because of how the SparkStarBarrierInterceptor mutates the traversal prior to local evaluation
    if (traversal.getStrategies().getStrategy(SubgraphStrategy.class).isPresent())
        return false;
    if (!startStep.getClass().equals(GraphStep.class) || ((GraphStep) startStep).returnsEdge())
        return false;
    if (!endStep.getClass().equals(CountGlobalStep.class) &&
            !endStep.getClass().equals(SumGlobalStep.class) &&
            !endStep.getClass().equals(MeanGlobalStep.class) &&
            !endStep.getClass().equals(MaxGlobalStep.class) &&
            !endStep.getClass().equals(MinGlobalStep.class) &&
            !endStep.getClass().equals(FoldStep.class) &&
            !endStep.getClass().equals(GroupStep.class) &&
            !endStep.getClass().equals(GroupCountStep.class))
        // TODO: tree()
        return false;
    if (TraversalHelper.getStepsOfAssignableClassRecursively(Scope.global, Barrier.class, traversal).size() != 1)
        return false;
    if (traversal.getTraverserRequirements().contains(TraverserRequirement.SACK))
        return false;
    return TraversalHelper.isLocalStarGraph(traversal);
}
 
Example #6
Source File: TestWhereWithSelect.java    From sqlg with MIT License 5 votes vote down vote up
@Test
public void coworkerSummaryOLTP() {
    loadModern();
    final Traversal<Vertex, Map<String, Map<String, Map<String, Object>>>> traversal =  this.sqlgGraph.traversal()
            .V().hasLabel("person").filter(__.outE("created")).as("p1")
            .V().hasLabel("person").where(P.neq("p1")).filter(__.outE("created")).as("p2")
            .map(__.out("created").where(__.in("created").as("p1")).values("name").fold())
            .<String, Map<String, Map<String, Object>>>group().by(__.select("p1").by("name")).
                    by(__.group().by(__.select("p2").by("name")).
                            by(__.project("numCoCreated", "coCreated").by(__.count(Scope.local)).by()));
    printTraversalForm(traversal);
    Assert.assertTrue(traversal.hasNext());
    checkCoworkerSummary(traversal.next());
    Assert.assertFalse(traversal.hasNext());
}
 
Example #7
Source File: RepeatUnrollStrategy.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Override
public void apply(final Traversal.Admin<?, ?> traversal) {
    if (TraversalHelper.onGraphComputer(traversal))
        return;

    for (int i = 0; i < traversal.getSteps().size(); i++) {
        if (traversal.getSteps().get(i) instanceof RepeatStep) {
            final RepeatStep<?> repeatStep = (RepeatStep) traversal.getSteps().get(i);
            if (null == repeatStep.getEmitTraversal() && null != repeatStep.getRepeatTraversal() &&
                    repeatStep.getUntilTraversal() instanceof LoopTraversal && ((LoopTraversal) repeatStep.getUntilTraversal()).getMaxLoops() > 0 &&
                    !TraversalHelper.hasStepOfAssignableClassRecursively(Scope.global, DedupGlobalStep.class, repeatStep.getRepeatTraversal()) &&
                    !TraversalHelper.hasStepOfAssignableClassRecursively(INVALIDATING_STEPS, repeatStep.getRepeatTraversal())) {
                final Traversal.Admin<?, ?> repeatTraversal = repeatStep.getGlobalChildren().get(0);
                repeatTraversal.removeStep(repeatTraversal.getSteps().size() - 1); // removes the RepeatEndStep
                TraversalHelper.applySingleLevelStrategies(traversal, repeatTraversal, RepeatUnrollStrategy.class);
                final int repeatLength = repeatTraversal.getSteps().size();
                int insertIndex = i;
                final int loops = (int) ((LoopTraversal) repeatStep.getUntilTraversal()).getMaxLoops();
                for (int j = 0; j < loops; j++) {
                    TraversalHelper.insertTraversal(insertIndex, repeatTraversal.clone(), traversal);
                    insertIndex = insertIndex + repeatLength;
                    if ((j != (loops - 1) || !(traversal.getSteps().get(insertIndex).getNextStep() instanceof Barrier)) // only add a final NoOpBarrier is subsequent step is not a barrier
                        && !(traversal.getSteps().get(insertIndex) instanceof NoOpBarrierStep) // Don't add a barrier if this step is a barrier (prevents nested repeat adding the barrier multiple times)
                       ) {
                        traversal.addStep(++insertIndex, new NoOpBarrierStep<>(traversal, MAX_BARRIER_SIZE));
                    }
                }
                // label last step if repeat() was labeled
                if (!repeatStep.getLabels().isEmpty())
                    TraversalHelper.copyLabels(repeatStep, traversal.getSteps().get(insertIndex), false);
                traversal.removeStep(i); // remove the RepeatStep
            }
        }
    }
}
 
Example #8
Source File: SampleLocalStepTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Override
protected List<Traversal> getTraversals() {
    return Arrays.asList(
            __.sample(Scope.local, 5),
            __.sample(Scope.local, 10)
    );
}
 
Example #9
Source File: SampleLocalStepTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldSelectSubsetsCorrectly() {
    final List<Integer> list = new ArrayList<>();
    for (int i = 0; i < 100; i++) {
        list.add(i);
    }
    for(int i=0; i<100; i++) {
        List<Integer> result;
        result = __.inject(list).sample(Scope.local, i).next();
        assertEquals(i, result.size());
        assertEquals(i, new HashSet<>(result).size());
        assertTrue(list.containsAll(result));
    }
}
 
Example #10
Source File: MeanLocalStepTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
public void testReturnTypes() {
    assertEquals(3d, __.__(2, 4).fold().mean(Scope.local).next());
    assertEquals(3d, __.__((short) 2, (short) 4).fold().mean(Scope.local).next()); // why? because the internal counter is a Long value
    assertEquals(BigDecimal.ONE, __.__(BigInteger.ONE, BigInteger.ONE).fold().mean(Scope.local).next());
    assertEquals(BigDecimal.ONE, __.__((short) 1, BigInteger.ONE).fold().mean(Scope.local).next());
    assertEquals(BigDecimal.ONE, __.__(BigInteger.ONE, (short) 1).fold().mean(Scope.local).next());
}
 
Example #11
Source File: TraceHeight.java    From jaeger-analytics-java with Apache License 2.0 5 votes vote down vote up
public static int calculate(Graph graph) {
  TraceTraversal<Vertex, Comparable> maxHeight = graph.traversal(TraceTraversalSource.class).V()
      .repeat(__.in()).emit().path().count(Scope.local).max();
  List<Integer> heights = maxHeight.toStream()
      .map(height -> Integer.valueOf(height.toString()))
      .collect(toList());
  return heights.size() > 0 ? heights.get(0) - 1 : 0;
}
 
Example #12
Source File: OrderLocalStepTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldNotThrowContractException() {
    for (int x = 0; x < 1000; x++) {
        final List<Integer> list = new ArrayList<>();
        for (int i = 0; i < 1000; i++) {
            list.add(i);
        }
        __.inject(list).order(Scope.local).by(Order.shuffle).iterate();
        __.inject(list).order(Scope.local).by().by(Order.shuffle).iterate();
        __.inject(list).order(Scope.local).by(Order.shuffle).by().iterate();
        __.inject(list).order(Scope.local).by(__.identity(), Order.shuffle).iterate();
        __.inject(list).order(Scope.local).by().by(__.identity(), Order.shuffle).iterate();
        __.inject(list).order(Scope.local).by(__.identity(), Order.shuffle).by().iterate();
    }
}
 
Example #13
Source File: TailLocalStepTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Override
protected List<Traversal> getTraversals() {
    return Arrays.asList(
            __.tail(Scope.local, 5L),
            __.tail(Scope.local, 10L)
    );
}
 
Example #14
Source File: LambdaRestrictionStrategyTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Parameterized.Parameters(name = "{0}")
public static Iterable<Object[]> data() {
    return Arrays.asList(new Object[][]{
            {"map(Lambda.function('true')}", __.map(Lambda.function("true")), false},
            {"filter(Lambda.predicate('true')}", __.filter(Lambda.predicate("true")), false},
            {"filter(x->true)", __.filter(x -> true), false},
            {"map(Traverser::get)", __.map(Traverser::get), false},
            {"sideEffect(x -> {int i = 1+1;})", __.sideEffect(x -> {
                int i = 1 + 1;
            }), false},
            {"select('a').by(values)", __.select("a").by(values), true},
            {"select('a','b').by(Object::toString)", __.select("a", "b").by(Object::toString), false},
            {"order().by((a,b)->a.compareTo(b))", __.order().by((a, b) -> ((Integer) a).compareTo((Integer) b)), false},
            {"order(local).by((a,b)->a.compareTo(b))", __.order(Scope.local).by((a, b) -> ((Integer) a).compareTo((Integer) b)), false},
            {"__.choose(v->v.toString().equals(\"marko\"),__.out(),__.in())", __.choose(v -> v.toString().equals("marko"), __.out(), __.in()), false},
            {"order().by(label,desc)", __.order().by(T.label, Order.desc), true},
            {"order(local).by(values)", __.order(Scope.local).by(values), true},
            {"order(local).by(values,desc)", __.order(Scope.local).by(values,Order.desc), true},
            {"order(local).by(values,(a,b) -> a.compareTo(b))", __.order(Scope.local).by(values, (a, b) -> ((Double) a).compareTo((Double) b)), false},
            //
            {"groupCount().by(label)", __.groupCount().by(T.label), true},
            //
            {"sack(sum).by('age')", __.sack(sum).by("age"), true},
            {"sack{a,b -> a+b}.by('age')", __.sack((a, b) -> (int) a + (int) b).by("age"), false},
            //
            {"order().by(outE('rating').values('stars').mean()).profile()", __.order().by(outE("ratings").values("stars").mean()).profile(), true}
    });
}
 
Example #15
Source File: SparkSingleIterationStrategy.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Override
public void apply(final Traversal.Admin<?, ?> traversal) {
    final Graph graph = traversal.getGraph().orElse(EmptyGraph.instance()); // best guess at what the graph will be as its dynamically determined
    for (final TraversalVertexProgramStep step : TraversalHelper.getStepsOfClass(TraversalVertexProgramStep.class, traversal)) {
        final Traversal.Admin<?, ?> computerTraversal = step.generateProgram(graph, EmptyMemory.instance()).getTraversal().get().clone();
        if (!computerTraversal.isLocked())
            computerTraversal.applyStrategies();
        ///
        boolean doesMessagePass = TraversalHelper.hasStepOfAssignableClassRecursively(Scope.global, MULTI_ITERATION_CLASSES, computerTraversal);
        if (!doesMessagePass) {
            for (final VertexStep vertexStep : TraversalHelper.getStepsOfAssignableClassRecursively(Scope.global, VertexStep.class, computerTraversal)) {
                if (vertexStep.returnsVertex() || !vertexStep.getDirection().equals(Direction.OUT)) { // in-edges require message pass in OLAP
                    doesMessagePass = true;
                    break;
                }
            }
        }
        if (!doesMessagePass &&
                !MessagePassingReductionStrategy.endsWithElement(computerTraversal.getEndStep()) &&
                !(computerTraversal.getTraverserRequirements().contains(TraverserRequirement.LABELED_PATH) || // TODO: remove this when dynamic detachment is available in 3.3.0
                        computerTraversal.getTraverserRequirements().contains(TraverserRequirement.PATH))) {  // TODO: remove this when dynamic detachment is available in 3.3.0
            step.setComputer(step.getComputer()
                    // if no message passing, don't partition the loaded graph
                    .configure(Constants.GREMLIN_SPARK_SKIP_PARTITIONER, true)
                    // if no message passing, don't cache the loaded graph
                    .configure(Constants.GREMLIN_SPARK_SKIP_GRAPH_CACHE, true));
        }
    }
}
 
Example #16
Source File: AbstractTypedCompatibilityTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReadWriteScope() throws Exception {
    final String resourceName = "scope";
    assumeCompatibility(resourceName);

    final Scope resource = findModelEntryObject(resourceName);
    final Scope fromStatic = read(getCompatibility().readFromResource(resourceName), Scope.class);
    final Scope recycled = read(write(fromStatic, Scope.class), Scope.class);
    assertEquals(fromStatic, recycled);
    assertEquals(resource, fromStatic);
    assertEquals(resource, recycled);
}
 
Example #17
Source File: OrderLocalStepTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Override
protected List<Traversal> getTraversals() {
    return Arrays.asList(
            __.order(Scope.local),
            __.order(Scope.local).by(Order.desc),
            __.order(Scope.local).by("age", Order.asc),
            __.order(Scope.local).by("age", Order.desc),
            __.order(Scope.local).by(outE().count(), Order.asc),
            __.order(Scope.local).by("age", Order.asc).by(outE().count(), Order.asc),
            __.order(Scope.local).by(outE().count(), Order.asc).by("age", Order.asc)
    );
}
 
Example #18
Source File: RangeLocalStepTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Override
protected List<Traversal> getTraversals() {
    return Arrays.asList(
            __.limit(Scope.local, 10L),
            __.range(Scope.local, 1L, 10L)
    );
}
 
Example #19
Source File: SumTest.java    From tinkerpop with Apache License 2.0 4 votes vote down vote up
@Override
public Traversal<Vertex, Number> get_g_V_age_fold_sumXlocalX() {
    return g.V().values("age").fold().sum(Scope.local);
}
 
Example #20
Source File: MinTest.java    From tinkerpop with Apache License 2.0 4 votes vote down vote up
@Override
public Traversal<Vertex, Comparable> get_g_V_foo_fold_minXlocalX() {
    return g.V().values("foo").fold().min(Scope.local);
}
 
Example #21
Source File: MinTest.java    From tinkerpop with Apache License 2.0 4 votes vote down vote up
@Override
public Traversal<Vertex, Integer> get_g_V_age_fold_minXlocalX() {
    return g.V().values("age").fold().min(Scope.local);
}
 
Example #22
Source File: SumTest.java    From tinkerpop with Apache License 2.0 4 votes vote down vote up
@Override
public Traversal<Vertex, Number> get_g_V_foo_fold_sumXlocalX() {
    return g.V().values("foo").fold().sum(Scope.local);
}
 
Example #23
Source File: OrderTest.java    From tinkerpop with Apache License 2.0 4 votes vote down vote up
@Override
public Traversal<Vertex, Map<String, Number>> get_g_V_hasLabelXpersonX_group_byXnameX_byXoutE_weight_sumX_orderXlocalX_byXvaluesX() {
    return g.V().hasLabel("person").<String, Number>group().by("name").by(outE().values("weight").sum()).order(Scope.local).by(Column.values);
}
 
Example #24
Source File: OrderTest.java    From tinkerpop with Apache License 2.0 4 votes vote down vote up
@Override
public Traversal<Vertex, Map.Entry<Object, Object>> get_g_VX1X_elementMap_orderXlocalX_byXkeys_descXunfold(final Object v1Id) {
    return g.V(v1Id).elementMap().order(Scope.local).by(keys, desc).unfold();
}
 
Example #25
Source File: IndexTest.java    From tinkerpop with Apache License 2.0 4 votes vote down vote up
@Override
public Traversal<Vertex, List<Object>> get_g_V_hasLabelXsoftwareX_name_fold_orderXlocalX_index_unfold_order_byXtailXlocal_1XX() {
    return g.V().hasLabel("software").values("name").fold().order(Scope.local).index()
            .<List<Object>> unfold().order().by(tail(Scope.local, 1));
}
 
Example #26
Source File: IndexTest.java    From tinkerpop with Apache License 2.0 4 votes vote down vote up
@Override
public Traversal<Vertex, Map<Integer, String>> get_g_V_hasLabelXpersonX_name_fold_orderXlocalX_index_withXmapX() {
    return g.V().hasLabel("person").values("name").fold().order(Scope.local)
            .<Map<Integer, String>> index().with(WithOptions.indexer, WithOptions.map);
}
 
Example #27
Source File: CountTest.java    From tinkerpop with Apache License 2.0 4 votes vote down vote up
@Override
public Traversal<Vertex, Long> get_g_V_fold_countXlocalX() {
    return g.V().fold().count(Scope.local);
}
 
Example #28
Source File: MeanTest.java    From tinkerpop with Apache License 2.0 4 votes vote down vote up
@Override
public Traversal<Vertex, Double> get_g_V_age_fold_meanXlocalX() {
    return g.V().values("age").fold().mean(Scope.local);
}
 
Example #29
Source File: MeanTest.java    From tinkerpop with Apache License 2.0 4 votes vote down vote up
@Override
public Traversal<Vertex, Number> get_g_V_foo_fold_meanXlocalX() {
    return g.V().values("foo").fold().mean(Scope.local);
}
 
Example #30
Source File: OrderTest.java    From tinkerpop with Apache License 2.0 4 votes vote down vote up
@Override
public Traversal<Vertex, List<Vertex>> get_g_V_hasLabelXpersonX_fold_orderXlocalX_byXageX() {
    return g.V().hasLabel("person").fold().order(Scope.local).by("age");
}