Java Code Examples for org.apache.tinkerpop.gremlin.process.traversal.P

The following examples show how to use org.apache.tinkerpop.gremlin.process.traversal.P. These examples are extracted from open source projects. 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: sqlg   Source File: TestBulkWithin.java    License: MIT License 6 votes vote down vote up
@Test
public void testBulkWithin_shortArray() {
    Assume.assumeTrue(this.sqlgGraph.getSqlDialect().supportsShortArrayValues());
    short[] shortArray1 = new short[]{(short) 1, (short) 2, (short) 3};
    short[] shortArray2 = new short[]{(short) 4, (short) 5, (short) 6};
    short[] shortArray3 = new short[]{(short) 7, (short) 8, (short) 9};
    short[] shortArray4 = new short[]{(short) 10, (short) 11, (short) 12};
    Vertex v1 = this.sqlgGraph.addVertex(T.label, "A", "name", shortArray1);
    Vertex v2 = this.sqlgGraph.addVertex(T.label, "A", "name", shortArray2);
    Vertex v3 = this.sqlgGraph.addVertex(T.label, "A", "name", shortArray3);
    Vertex v4 = this.sqlgGraph.addVertex(T.label, "A", "name", shortArray4);
    this.sqlgGraph.tx().commit();
    List<Vertex> vertices = this.sqlgGraph.traversal().V().hasLabel("A").has("name", P.within(shortArray1, shortArray3, shortArray4)).toList();
    Assert.assertEquals(3, vertices.size());
    Assert.assertTrue(Arrays.asList(v1, v3, v4).containsAll(vertices));
}
 
Example 2
Source Project: sqlg   Source File: TestHasLabelAndId.java    License: MIT License 6 votes vote down vote up
@Test
public void testGraphStepHasLabelWithinCollection() {
    Vertex a = this.sqlgGraph.addVertex(T.label, "A");
    Vertex b = this.sqlgGraph.addVertex(T.label, "B");
    Vertex c = this.sqlgGraph.addVertex(T.label, "C");
    Vertex d = this.sqlgGraph.addVertex(T.label, "D");
    this.sqlgGraph.tx().commit();
    GraphTraversal<Vertex, Vertex> traversal = this.sqlgGraph.traversal().V().hasLabel("A", "B");
    printTraversalForm(traversal);
    Assert.assertEquals(2, traversal.toList().size());
    traversal = this.sqlgGraph.traversal().V().hasLabel(P.within("A", "B"));
    Assert.assertEquals(2, traversal.toList().size());
    traversal = this.sqlgGraph.traversal().V().hasLabel(P.within(new HashSet<>(Arrays.asList("A", "B"))));
    Assert.assertEquals(2, traversal.toList().size());

    Assert.assertEquals(0, this.sqlgGraph.traversal().V(a, b).hasLabel(P.within("C")).toList().size());
    List<Vertex> vertices = this.sqlgGraph.traversal().V(a, b).hasLabel(P.within(new HashSet<>(Arrays.asList("A", "B", "D")))).toList();
    Assert.assertEquals(2, vertices.size());
}
 
Example 3
Source Project: tinkergraph-gremlin   Source File: TinkerGraphStep.java    License: Apache License 2.0 6 votes vote down vote up
private Iterator<? extends Edge> edges() {
    final TinkerGraph graph = (TinkerGraph) this.getTraversal().getGraph().get();
    final HasContainer indexedContainer = getIndexKey(Edge.class);
    final Optional<HasContainer> hasLabelContainer = findHasLabelStep();
    // ids are present, filter on them first
    if (null == this.ids)
        return Collections.emptyIterator();
    else if (this.ids.length > 0)
        return this.iteratorList(graph.edges(this.ids));
    else if (graph.ondiskOverflowEnabled && hasLabelContainer.isPresent())
        return graph.edgesByLabel((P<String>) hasLabelContainer.get().getPredicate());
    else
        return null == indexedContainer ?
                this.iteratorList(graph.edges()) :
                TinkerHelper.queryEdgeIndex(graph, indexedContainer.getKey(), indexedContainer.getPredicate().getValue()).stream()
                        .filter(edge -> HasContainer.testAll(edge, this.hasContainers))
                        .collect(Collectors.<Edge>toList()).iterator();
}
 
Example 4
Source Project: tinkergraph-gremlin   Source File: TinkerGraphTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldUpdateVertexIndicesInExistingGraph() {
    final TinkerGraph g = TinkerGraph.open();

    g.addVertex("name", "marko", "age", 29);
    g.addVertex("name", "stephen", "age", 35);

    // a tricky way to evaluate if indices are actually being used is to pass a fake BiPredicate to has()
    // to get into the Pipeline and evaluate what's going through it.  in this case, we know that at index
    // is not used because "stephen" and "marko" ages both pass through the pipeline.
    assertEquals(new Long(1), g.traversal().V().has("age", P.test((t, u) -> {
        assertTrue(t.equals(35) || t.equals(29));
        return true;
    }, 35)).has("name", "stephen").count().next());

    g.createIndex("name", Vertex.class);

    // another spy into the pipeline for index check.  in this case, we know that at index
    // is used because only "stephen" ages should pass through the pipeline due to the inclusion of the
    // key index lookup on "name".  If there's an age of something other than 35 in the pipeline being evaluated
    // then something is wrong.
    assertEquals(new Long(1), g.traversal().V().has("age", P.test((t, u) -> {
        assertEquals(35, t);
        return true;
    }, 35)).has("name", "stephen").count().next());
}
 
Example 5
Source Project: tinkerpop   Source File: GryoSerializersV3d0.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public <O extends OutputShim> void write(final KryoShim<?, O> kryo, final O output, final P p) {
    output.writeString(p instanceof ConnectiveP ?
            (p instanceof AndP ? "and" : "or") :
            p.getBiPredicate().toString());
    if (p instanceof ConnectiveP || p.getValue() instanceof Collection) {
        output.writeByte((byte) 0);
        final Collection<?> coll = p instanceof ConnectiveP ?
                ((ConnectiveP<?>) p).getPredicates() : (Collection) p.getValue();
        output.writeInt(coll.size());
        coll.forEach(v -> kryo.writeClassAndObject(output, v));
    } else {
        output.writeByte((byte) 1);
        kryo.writeClassAndObject(output, p.getValue());
    }
}
 
Example 6
Source Project: sqlg   Source File: TestBulkWithin.java    License: MIT License 6 votes vote down vote up
@Test
public void testBulkWithin_LocalDateArray() {
    Assume.assumeTrue(this.sqlgGraph.getSqlDialect().supportsLocalDateArrayValues());
    LocalDate[] localDateArray1 = new LocalDate[]{LocalDate.now().minusDays(1), LocalDate.now().minusDays(2), LocalDate.now().minusDays(3)};
    LocalDate[] localDateArray2 = new LocalDate[]{LocalDate.now().minusDays(4), LocalDate.now().minusDays(5), LocalDate.now().minusDays(6)};
    LocalDate[] localDateArray3 = new LocalDate[]{LocalDate.now().minusDays(7), LocalDate.now().minusDays(8), LocalDate.now().minusDays(9)};
    LocalDate[] localDateArray4 = new LocalDate[]{LocalDate.now().minusDays(10), LocalDate.now().minusDays(11), LocalDate.now().minusDays(12)};
    Vertex v1 = this.sqlgGraph.addVertex(T.label, "A", "name", localDateArray1);
    Vertex v2 = this.sqlgGraph.addVertex(T.label, "A", "name", localDateArray2);
    Vertex v3 = this.sqlgGraph.addVertex(T.label, "A", "name", localDateArray3);
    Vertex v4 = this.sqlgGraph.addVertex(T.label, "A", "name", localDateArray4);
    this.sqlgGraph.tx().commit();
    List<Vertex> vertices = this.sqlgGraph.traversal().V().hasLabel("A").has("name", P.within(localDateArray1, localDateArray3, localDateArray4)).toList();
    Assert.assertEquals(3, vertices.size());
    Assert.assertTrue(Arrays.asList(v1, v3, v4).containsAll(vertices));
}
 
Example 7
Source Project: windup   Source File: ClassificationService.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns the total effort points in all of the {@link ClassificationModel}s associated with the provided {@link FileModel}.
 */
public int getMigrationEffortPoints(FileModel fileModel)
{
    GraphTraversal<Vertex, Vertex> classificationPipeline = new GraphTraversalSource(getGraphContext().getGraph()).V(fileModel.getElement());
    classificationPipeline.in(ClassificationModel.FILE_MODEL);
    classificationPipeline.has(EffortReportModel.EFFORT, P.gt(0));
    classificationPipeline.has(WindupVertexFrame.TYPE_PROP, Text.textContains(ClassificationModel.TYPE));

    int classificationEffort = 0;
    for (Vertex v : classificationPipeline.toList())
    {
        Property<Integer> migrationEffort = v.property(ClassificationModel.EFFORT);
        if (migrationEffort.isPresent())
        {
            classificationEffort += migrationEffort.value();
        }
    }
    return classificationEffort;
}
 
Example 8
Source Project: tinkerpop   Source File: MatchStepTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldCalculateStartLabelCorrectly() {
    Traversal.Admin<?, ?> traversal = match(
            where(and(
                    as("a").out("created").as("b"),
                    as("b").in("created").count().is(eq(3)))),
            as("a").both().as("b"),
            where(as("b").in())).asAdmin();
    assertEquals("a", MatchStep.Helper.computeStartLabel(((MatchStep<?, ?>) traversal.getStartStep()).getGlobalChildren()));
    /////
    traversal = match(
            where("a", P.neq("c")),
            as("a").out("created").as("b"),
            or(
                    as("a").out("knows").has("name", "vadas"),
                    as("a").in("knows").and().as("a").has(T.label, "person")
            ),
            as("b").in("created").as("c"),
            as("b").in("created").count().is(P.gt(1))).asAdmin();
    assertEquals("a", MatchStep.Helper.computeStartLabel(((MatchStep<?, ?>) traversal.getStartStep()).getGlobalChildren()));
}
 
Example 9
Source Project: sqlg   Source File: TestHasLabelAndId.java    License: MIT License 6 votes vote down vote up
@Test
public void testNeqWithinManyIDs() {
    Vertex a = sqlgGraph.addVertex("A");
    Vertex b1 = sqlgGraph.addVertex("B");
    Vertex b2 = sqlgGraph.addVertex("B");
    Vertex b3 = sqlgGraph.addVertex("B");
    Vertex b4 = sqlgGraph.addVertex("B");
    Vertex b5 = sqlgGraph.addVertex("B");
    Vertex b6 = sqlgGraph.addVertex("B");
    Vertex c = sqlgGraph.addVertex("C");

    a.addEdge("e_a", b1);
    a.addEdge("e_a", b2);
    a.addEdge("e_a", b3);
    a.addEdge("e_a", b4);
    a.addEdge("e_a", b5);
    a.addEdge("e_a", b6);
    a.addEdge("e_a", c);

    //uses tmp table to join on
    GraphTraversal<Vertex, Vertex> t = sqlgGraph.traversal().V(a).out().has(T.id, P.without(b1.id(), b2.id(), b3.id(), b4.id(), b5.id()));
    List<Vertex> vertices = t.toList();
    Assert.assertEquals(2, vertices.size());
    Assert.assertTrue(vertices.contains(b6));
    Assert.assertTrue(vertices.contains(c));
}
 
Example 10
Source Project: grakn   Source File: OLAPOperation.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
private void applyFilters(Set<LabelId> types, boolean includesRolePlayerEdge) {
        if (types == null || types.isEmpty()) return;
        Set<Integer> labelIds = types.stream().map(LabelId::getValue).collect(Collectors.toSet());

        Traversal<Vertex, Vertex> vertexFilter =
                __.has(Schema.VertexProperty.THING_TYPE_LABEL_ID.name(), P.within(labelIds));

        Traversal<Vertex, Edge> edgeFilter;
        if (filterAllEdges) {
            edgeFilter = __.bothE().limit(0);
        } else {
            edgeFilter = includesRolePlayerEdge ?
                    __.union(
                            __.bothE(Schema.EdgeLabel.ROLE_PLAYER.getLabel()),
                            __.bothE(Schema.EdgeLabel.ATTRIBUTE.getLabel()) ) :
//                                    .has(Schema.EdgeProperty.RELATION_TYPE_LABEL_ID.name(), P.within(labelIds))) :
                    __.bothE(Schema.EdgeLabel.ATTRIBUTE.getLabel()) ;
//                            .has(Schema.EdgeProperty.RELATION_TYPE_LABEL_ID.name(), P.within(labelIds));
        }

        graphComputer.vertices(vertexFilter).edges(edgeFilter);
    }
 
Example 11
Source Project: sqlg   Source File: TestGisBulkWithin.java    License: MIT License 6 votes vote down vote up
@Test
public void testBulkWithinPolygon() throws SQLException {
    LinearRing linearRing1 = new LinearRing("0 0, 1 1, 1 2, 1 1, 0 0");
    Polygon polygon1 = new Polygon(new LinearRing[]{linearRing1});
    LinearRing linearRing2 = new LinearRing("1 1, 1 1, 1 2, 1 1, 1 1");
    Polygon polygon2 = new Polygon(new LinearRing[]{linearRing2});
    LinearRing linearRing3 = new LinearRing("2 2, 1 1, 1 2, 1 1, 2 2");
    Polygon polygon3 = new Polygon(new LinearRing[]{linearRing3});
    LinearRing linearRing4 = new LinearRing("1 3, 1 2, 2 2, 1 1, 1 3");
    Polygon polygon4 = new Polygon(new LinearRing[]{linearRing4});

    Vertex v1 = this.sqlgGraph.addVertex(T.label, "Gis", "polygon", polygon1);
    Vertex v2 = this.sqlgGraph.addVertex(T.label, "Gis", "polygon", polygon2);
    Vertex v3 = this.sqlgGraph.addVertex(T.label, "Gis", "polygon", polygon3);
    Vertex v4 = this.sqlgGraph.addVertex(T.label, "Gis", "polygon", polygon4);
    this.sqlgGraph.tx().commit();
    List<Vertex> vertices = this.sqlgGraph.traversal().V().hasLabel("Gis").has("polygon", P.within(polygon1, polygon3, polygon4)).toList();
    Assert.assertEquals(3, vertices.size());
    Assert.assertTrue(Arrays.asList(v1, v3, v4).containsAll(vertices));
}
 
Example 12
Source Project: sqlg   Source File: TestBulkWithin.java    License: MIT License 6 votes vote down vote up
@Test
public void testBulkWithin_IntegerArray() {
    Assume.assumeTrue(this.sqlgGraph.getSqlDialect().supportsIntegerArrayValues());
    Integer[] intArray1 = new Integer[]{1, 2, 3};
    Integer[] intArray2 = new Integer[]{4, 5, 6};
    Integer[] intArray3 = new Integer[]{7, 8, 9};
    Integer[] intArray4 = new Integer[]{10, 11, 12};
    Vertex v1 = this.sqlgGraph.addVertex(T.label, "A", "name", intArray1);
    Vertex v2 = this.sqlgGraph.addVertex(T.label, "A", "name", intArray2);
    Vertex v3 = this.sqlgGraph.addVertex(T.label, "A", "name", intArray3);
    Vertex v4 = this.sqlgGraph.addVertex(T.label, "A", "name", intArray4);
    this.sqlgGraph.tx().commit();
    List<Vertex> vertices = this.sqlgGraph.traversal().V().hasLabel("A").has("name", P.within(intArray1, intArray3, intArray4)).toList();
    Assert.assertEquals(3, vertices.size());
    Assert.assertTrue(Arrays.asList(v1, v3, v4).containsAll(vertices));
}
 
Example 13
Source Project: sqlg   Source File: TestBulkWithin.java    License: MIT License 6 votes vote down vote up
@Test
public void testBulkWithin_FloatArray() {
    Assume.assumeTrue(this.sqlgGraph.getSqlDialect().supportsFloatArrayValues());
    Float[] floatArray1 = new Float[]{1F, 2F, 3F};
    Float[] floatArray2 = new Float[]{4F, 5F, 6F};
    Float[] floatArray3 = new Float[]{7F, 8F, 9F};
    Float[] floatArray4 = new Float[]{10F, 11F, 12F};
    Vertex v1 = this.sqlgGraph.addVertex(T.label, "A", "name", floatArray1);
    Vertex v2 = this.sqlgGraph.addVertex(T.label, "A", "name", floatArray2);
    Vertex v3 = this.sqlgGraph.addVertex(T.label, "A", "name", floatArray3);
    Vertex v4 = this.sqlgGraph.addVertex(T.label, "A", "name", floatArray4);
    this.sqlgGraph.tx().commit();
    List<Vertex> vertices = this.sqlgGraph.traversal().V().hasLabel("A").has("name", P.within(floatArray1, floatArray3, floatArray4)).toList();
    Assert.assertEquals(3, vertices.size());
    Assert.assertTrue(Arrays.asList(v1, v3, v4).containsAll(vertices));
}
 
Example 14
Source Project: sqlg   Source File: TestSchema.java    License: MIT License 5 votes vote down vote up
@Test
public void testUnprefixedEdgeLabelWithin() {
    Vertex a1 = this.sqlgGraph.addVertex(T.label, "A.A");
    Vertex b1 = this.sqlgGraph.addVertex(T.label, "B.B");
    Edge eee = a1.addEdge("eee", b1);
    Edge fff = a1.addEdge("fff", b1);
    this.sqlgGraph.tx().commit();
    GraphTraversal<Edge, Edge> traversal = this.sqlgGraph.traversal().E().has(T.label, P.within("eee", "fff"));
    List<Edge> edges = traversal.toList();
    Assert.assertEquals(2, edges.size());
    Assert.assertTrue(edges.contains(eee) && edges.contains(fff));
}
 
Example 15
Source Project: sqlg   Source File: TestBulkWithin.java    License: MIT License 5 votes vote down vote up
@Test
public void testBulkWithinDouble() {
    this.sqlgGraph.addVertex(T.label, "A", "name", 1.1D);
    this.sqlgGraph.addVertex(T.label, "A", "name", 2.2D);
    this.sqlgGraph.addVertex(T.label, "A", "name", 3.3D);
    this.sqlgGraph.tx().commit();
    List<Vertex> vertices = this.sqlgGraph.traversal().V().hasLabel("A").has("name", P.within(1.1D, 2.2D, 3.3D)).toList();
    Assert.assertEquals(3, vertices.size());
}
 
Example 16
Source Project: sqlg   Source File: TestRecordId.java    License: MIT License 5 votes vote down vote up
@Test
public void testRecordIdHasCommas() {
    Schema schema = this.sqlgGraph.getTopology().ensureSchemaExist("A");
    schema.ensureVertexLabelExist("aaa.bbb", new LinkedHashMap<String, PropertyType>() {{
        put("_id", PropertyType.STRING);
        put("value", PropertyType.STRING);
    }}, ListOrderedSet.listOrderedSet(Collections.singletonList("_id")));
    this.sqlgGraph.tx().commit();

    this.sqlgGraph.addVertex(T.label, "A.aaa.bbb", "_id", "id1", "value", "a");
    this.sqlgGraph.tx().commit();

    RecordId recordId = RecordId.from(this.sqlgGraph, "A.aaa.bbb:::[id1]");
    Assert.assertEquals(1, this.sqlgGraph.traversal().V().hasLabel("A.aaa.bbb").hasId(P.eq(recordId)).count().next(), 0L);

    schema.ensureVertexLabelExist("aaa.ccc", new LinkedHashMap<String, PropertyType>() {{
        put("_id", PropertyType.STRING);
        put("value", PropertyType.STRING);
    }}, ListOrderedSet.listOrderedSet(Collections.singletonList("_id")));
    this.sqlgGraph.tx().commit();

    this.sqlgGraph.addVertex(T.label, "A.aaa.ccc", "_id", "id:::what", "value", "a");
    this.sqlgGraph.tx().commit();

    recordId = RecordId.from(this.sqlgGraph, "A.aaa.ccc:::[id:::what]");
    Assert.assertEquals(1, this.sqlgGraph.traversal().V().hasLabel("A.aaa.ccc").hasId(P.eq(recordId)).count().next(), 0L);
}
 
Example 17
Source Project: hugegraph   Source File: IndexLabelCoreTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testAddIndexLabelOfVertexWithVertexExist() {
    Assume.assumeTrue("Not support range condition query",
                      storeFeatures().supportsQueryWithRangeCondition());
    super.initPropertyKeys();
    SchemaManager schema = graph().schema();

    schema.vertexLabel("person").properties("name", "age", "city")
          .primaryKeys("name").create();
    graph().addVertex(T.label, "person", "name", "Baby",
                      "city", "Hongkong", "age", 3);
    graph().tx().commit();

    Assert.assertThrows(NoIndexException.class, () -> {
        graph().traversal().V().hasLabel("person")
               .has("city", "Hongkong").next();
    });

    schema.indexLabel("personByCity").onV("person").secondary()
          .by("city").create();

    Vertex vertex = graph().traversal().V().hasLabel("person")
                           .has("city", "Hongkong").next();
    Assert.assertNotNull(vertex);

    Assert.assertThrows(NoIndexException.class, () -> {
        graph().traversal().V().hasLabel("person")
               .has("age", P.inside(2, 4)).next();
    });
    schema.indexLabel("personByAge").onV("person").range()
          .by("age").create();

    vertex = graph().traversal().V().hasLabel("person")
                    .has("age", P.inside(2, 4)).next();
    Assert.assertNotNull(vertex);
}
 
Example 18
Source Project: sqlg   Source File: TestHasLabelAndId.java    License: MIT License 5 votes vote down vote up
@Test
public void testInWithHasLabelAndHasWithinId2() {
    Vertex a = this.sqlgGraph.addVertex(T.label, "A");
    Vertex b = this.sqlgGraph.addVertex(T.label, "B");
    Vertex b2 = this.sqlgGraph.addVertex(T.label, "B");
    Vertex c = this.sqlgGraph.addVertex(T.label, "C");
    Vertex d = this.sqlgGraph.addVertex(T.label, "D");
    b.addEdge("ab", a);
    b2.addEdge("ab", a);
    c.addEdge("ac", a);
    d.addEdge("ad", a);
    this.sqlgGraph.tx().commit();

    DefaultGraphTraversal<Vertex, Vertex> traversal = (DefaultGraphTraversal<Vertex, Vertex>) this.sqlgGraph.traversal()
            .V().hasLabel("A").in().hasLabel("B", "C", "D").has(T.id, P.within(b.id(), c.id()));
    List<Vertex> vertices = traversal.toList();
    Assert.assertEquals(2, vertices.size());
    Assert.assertTrue(vertices.contains(b) && vertices.contains(c));
    Assert.assertEquals(1, traversal.getSteps().size());
    Assert.assertTrue(traversal.getSteps().get(0) instanceof SqlgGraphStep);
    SqlgGraphStep sqlgGraphStep = (SqlgGraphStep) traversal.getSteps().get(0);
    Assert.assertEquals(2, sqlgGraphStep.getReplacedSteps().size());
    ReplacedStep replacedStep = (ReplacedStep) sqlgGraphStep.getReplacedSteps().get(0);
    Assert.assertEquals(1, replacedStep.getLabelHasContainers().size());
    replacedStep = (ReplacedStep) sqlgGraphStep.getReplacedSteps().get(1);
    Assert.assertEquals(2, replacedStep.getLabelHasContainers().size());
}
 
Example 19
Source Project: hugegraph   Source File: IndexLabelCoreTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testRemoveIndexLabelOfEdgeWithoutLabelIndex() {
    Assume.assumeFalse("Support query by label",
                       storeFeatures().supportsQueryByLabel());

    initDataWithoutLabelIndex();

    // Not support query by label
    Assert.assertThrows(NoIndexException.class, () -> {
        graph().traversal().E().hasLabel("read").toList();
    }, e -> {
        Assert.assertTrue(
               e.getMessage().startsWith("Don't accept query by label") &&
               e.getMessage().endsWith("label index is disabled"));
    });

    // Query by property index is ok
    List<Edge> edges = graph().traversal().E()
                              .has("date", P.lt("2019-12-30 13:00:00"))
                              .toList();
    Assert.assertEquals(20, edges.size());

    graph().schema().indexLabel("readByDate").remove();

    Assert.assertThrows(NoIndexException.class, () ->
            graph().traversal().E()
                   .has("date", P.lt("2019-12-30 13:00:00")).toList()
    );
}
 
Example 20
/**
 * Gets users by their identifier.
 */
public GraphTraversal<Vertex, Vertex> users(String userId, String... additionalUserIds) {
    List<String> userIds = Stream.concat(Stream.of(userId), Stream.of(additionalUserIds)).collect(Collectors.toList());
    GraphTraversal traversal = this.clone().V();
    traversal = traversal.hasLabel(VERTEX_USER);
    if (userIds.size() == 1)
        traversal = traversal.has(KEY_USER_ID, userIds.get(0));
    else if (userIds.size() > 1)
        traversal = traversal.has(KEY_USER_ID, P.within(userIds));

    return traversal;
}
 
Example 21
Source Project: graph-examples   Source File: ShortestPathQueryBuilder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @return The inner {@code repeat()) traversal.
 */
private Traversal<?, E> buildRepeatTraversal() {
    GraphTraversal<?, E> traversal = __.start();
    if (traverseEdges()) {
        switch (direction) {
            case OUT:
                computeDistance(traversal.outE(edgeLabels)).inV();
                break;
            case IN:
                computeDistance(traversal.inE(edgeLabels)).outV();
                break;
            default:
                computeDistance(traversal.bothE(edgeLabels)).otherV();
                break;
        }
    } else {
        switch (direction) {
            case OUT:
                traversal.out(edgeLabels);
                break;
            case IN:
                traversal.in(edgeLabels);
                break;
            default:
                traversal.both(edgeLabels);
                break;
        }
        computeDistance(traversal);
        if (maxDistance != null) {
            // stop traversing if maximum distance is reached or exceeded
            traversal.filter(__.sack().is(P.lt(maxDistance)));
        }
    }
    traversal.simplePath().from(START_LABEL);
    return traversal;
}
 
Example 22
Source Project: sqlg   Source File: TestGremlinCompileWhere.java    License: MIT License 5 votes vote down vote up
private void testEmptyWithout_assert(SqlgGraph sqlgGraph) {
    DefaultGraphTraversal<Vertex, Vertex> traversal = (DefaultGraphTraversal<Vertex, Vertex>) sqlgGraph.traversal()
            .V().hasLabel("Person").has("age", P.without(Collections.emptyList()));
    Assert.assertEquals(2, traversal.getSteps().size());
    List<Vertex> vertices = traversal.toList();
    Assert.assertEquals(1, traversal.getSteps().size());
    Assert.assertEquals(3, vertices.size());
}
 
Example 23
@Override
public GraphTraversal<Vertex, Vertex> getCurrentEntitiesFor(String... entityTypeNames) {
  if (entityTypeNames.length == 1) {
    String type = entityTypeNames[0];
    return getLatestState().V().has(T.label, LabelP.of(type));
  } else {
    P<String> labels = LabelP.of(entityTypeNames[0]);
    for (int i = 1; i < entityTypeNames.length; i++) {
      labels = labels.or(LabelP.of(entityTypeNames[i]));
    }

    return getLatestState().V().has(T.label, labels);
  }
}
 
Example 24
Source Project: tinkerpop   Source File: WherePredicateStep.java    License: Apache License 2.0 5 votes vote down vote up
private void configurePredicates(final P<Object> predicate) {
    if (predicate instanceof ConnectiveP)
        ((ConnectiveP<Object>) predicate).getPredicates().forEach(this::configurePredicates);
    else {
        final String selectKey = (String) (predicate.getValue() instanceof Collection ? ((Collection) predicate.getValue()).iterator().next() : predicate.getValue()); // hack for within("x"))
        this.selectKeys.add(selectKey);
        this.scopeKeys.add(selectKey);
    }
}
 
Example 25
Source Project: sqlg   Source File: TestBulkWithin.java    License: MIT License 5 votes vote down vote up
private void testBulkWithinMultipleHasContrainers_assert(SqlgGraph sqlgGraph) {
    List<Vertex> persons = sqlgGraph.traversal().V()
            .hasLabel("God")
            .out()
            .has("name", "pete")
            .has("idNumber", P.within(1,2,3))
            .toList();
    Assert.assertEquals(2, persons.size());
}
 
Example 26
Source Project: sqlg   Source File: TestBulkWithin.java    License: MIT License 5 votes vote down vote up
@Test
public void testBulkWithinFloat() {
    Assume.assumeTrue(this.sqlgGraph.getSqlDialect().supportsFloatValues());
    this.sqlgGraph.addVertex(T.label, "A", "name", 1.1F);
    this.sqlgGraph.addVertex(T.label, "A", "name", 2.2F);
    this.sqlgGraph.addVertex(T.label, "A", "name", 3.3F);
    this.sqlgGraph.tx().commit();
    List<Vertex> vertices = this.sqlgGraph.traversal().V().hasLabel("A").has("name", P.within(1.1F, 2.2F, 3.3F)).toList();
    Assert.assertEquals(3, vertices.size());
}
 
Example 27
Source Project: sqlg   Source File: TestBulkWithin.java    License: MIT License 5 votes vote down vote up
@Test
public void testBulkWithinInteger() {
    this.sqlgGraph.addVertex(T.label, "A", "name", 1);
    this.sqlgGraph.addVertex(T.label, "A", "name", 2);
    this.sqlgGraph.addVertex(T.label, "A", "name", 3);
    this.sqlgGraph.tx().commit();
    List<Vertex> vertices = this.sqlgGraph.traversal().V().hasLabel("A").has("name", P.within(1, 2, 3)).toList();
    Assert.assertEquals(3, vertices.size());
}
 
Example 28
Source Project: windup   Source File: GraphService.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Override
public List<T> findAllWithoutProperty(final String key, final Object value)
{
    return ExecutionStatistics.performBenchmarked("GraphService.findAllWithoutProperty(" + key + ")", () -> {
        //return (List<T>)findAllQuery().traverse(g -> g.hasNot(key).or(g.has(key, P.neq(value)))).toList(type);
        return findAllQuery().getRawTraversal().not(__.has(key, P.eq(value))).toList()
                .stream()
                .map(v -> frame((Vertex)v))
                .collect(Collectors.toList());
    });
}
 
Example 29
Source Project: tinkerpop   Source File: JavaTranslatorBenchmark.java    License: Apache License 2.0 5 votes vote down vote up
@Benchmark
public GraphTraversal.Admin<Vertex,Vertex> testTranslationLong() {
    return translator.translate(g.V().match(
            as("a").has("song", "name", "HERE COMES SUNSHINE"),
            as("a").map(inE("followedBy").values("weight").mean()).as("b"),
            as("a").inE("followedBy").as("c"),
            as("c").filter(values("weight").where(P.gte("b"))).outV().as("d")).
            <String>select("d").by("name").asAdmin().getBytecode());
}
 
Example 30
Source Project: sqlg   Source File: FullText.java    License: MIT License 5 votes vote down vote up
/**
 * Build full text matching predicate (use in where(...))
 * Uses several columns for text search. This assumes PostgreSQL and concatenates column names with a space in between
 * just like we would by default build the index
 * @param configuration the full text configuration to use
 * @param plain should we use plain mode?
 * @param columns the columns to query
 * @param value the value to search for
 * @return the predicate
 */
public static P<String> fullTextMatch(String configuration, boolean plain, final List<String> columns, final String value){
	StringBuilder query=new StringBuilder(); 
	int count=1;
	for (String column : columns) {
		query.append("\""+column+"\"");
           if (count++ < columns.size()) {
           	query.append(" || ' ' || ");
           }
       }
	return new P<>(new FullText(configuration,query.toString(),plain),value);
}