org.apache.tinkerpop.gremlin.structure.Vertex Java Examples

The following examples show how to use org.apache.tinkerpop.gremlin.structure.Vertex. 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: Neo4JSession.java    From neo4j-gremlin-bolt with Apache License 2.0 6 votes vote down vote up
Neo4JVertex addVertex(Object... keyValues) {
    Objects.requireNonNull(keyValues, "keyValues cannot be null");
    // verify parameters are key/value pairs
    ElementHelper.legalPropertyKeyValueArray(keyValues);
    // id cannot be present
    if (ElementHelper.getIdValue(keyValues).isPresent())
        throw Vertex.Exceptions.userSuppliedIdsNotSupported();
    // create vertex
    Neo4JVertex vertex = new Neo4JVertex(graph, this, vertexIdProvider, edgeIdProvider, Arrays.asList(ElementHelper.getLabelValue(keyValues).orElse(Vertex.DEFAULT_LABEL).split(Neo4JVertex.LabelDelimiter)));
    // add vertex to transient set (before processing properties to avoid having a transient vertex in update queue)
    transientVertices.add(vertex);
    // attach properties
    ElementHelper.attachProperties(vertex, keyValues);
    // check vertex has id
    Object id = vertex.id();
    if (id != null)
        transientVertexIndex.put(id, vertex);
    // return vertex
    return vertex;
}
 
Example #2
Source File: TestBatchNormalUpdatePrimitiveArrays.java    From sqlg with MIT License 6 votes vote down vote up
@Test
public void testintArrayUpdateNull() throws InterruptedException {
    Assume.assumeTrue(this.sqlgGraph.getSqlDialect().supportsIntegerArrayValues());
    this.sqlgGraph.tx().normalBatchModeOn();
    int[] intArray = new int[]{1, 2};
    Vertex a1 = this.sqlgGraph.addVertex(T.label, "A", "intArray1", intArray);
    Vertex a2 = this.sqlgGraph.addVertex(T.label, "A", "intArray2", intArray);
    Vertex a3 = this.sqlgGraph.addVertex(T.label, "A", "intArray3", intArray);
    this.sqlgGraph.tx().commit();

    this.sqlgGraph.tx().normalBatchModeOn();
    int[] intArrayAgain = new int[]{3, 4};
    a1.property("intArray1", intArrayAgain);
    a2.property("intArray2", intArrayAgain);
    a3.property("intArray3", intArrayAgain);
    this.sqlgGraph.tx().commit();

    testintArrayUpdateNull_assert(this.sqlgGraph, a1, a2, a3, intArrayAgain);
    if (this.sqlgGraph1 != null) {
        sleep(SLEEP_TIME);
        testintArrayUpdateNull_assert(this.sqlgGraph1, a1, a2, a3, intArrayAgain);
    }

}
 
Example #3
Source File: VertexModel.java    From hgraphdb with Apache License 2.0 6 votes vote down vote up
public Iterator<Vertex> verticesInRange(String label, String key, Object inclusiveFrom, Object exclusiveTo) {
    ElementHelper.validateProperty(key, inclusiveFrom);
    ElementHelper.validateProperty(key, exclusiveTo);
    IndexMetadata index = graph.getIndex(OperationType.READ, ElementType.VERTEX, label, key);
    if (index != null) {
        LOGGER.debug("Using vertex index for ({}, {})", label, key);
        return graph.getVertexIndexModel().verticesInRange(label, index.isUnique(), key, inclusiveFrom, exclusiveTo);
    }
    final VertexReader parser = new VertexReader(graph);

    byte[] fromVal = ValueUtils.serializePropertyValue(graph, ElementType.VERTEX, label, key, inclusiveFrom);
    byte[] toVal = ValueUtils.serializePropertyValue(graph, ElementType.VERTEX, label, key, exclusiveTo);
    final byte[] keyBytes = Bytes.toBytes(key);
    Scan scan = getPropertyScan(label, keyBytes, fromVal, toVal);
    ResultScanner scanner = null;
    try {
        scanner = table.getScanner(scan);
        return HBaseGraphUtils.mapWithCloseAtEnd(scanner, parser::parse);
    } catch (IOException e) {
        throw new HBaseGraphException(e);
    }
}
 
Example #4
Source File: LocalProperty.java    From timbuctoo with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Vertex save(Graph graph, String clientPropertyName) {
  Vertex propertyVertex = super.save(graph, clientPropertyName);

  propertyVertex.property(DATABASE_PROPERTY_NAME, propName);

  if (converter instanceof HasOptions) {
    try {
      propertyVertex.property(OPTIONS_PROPERTY_NAME,
        new ObjectMapper().writeValueAsString(((HasOptions) converter).getOptions()));
    } catch (JsonProcessingException e) {
      LOG.error("Failed to write options to database for property {}", propName);
    }
  }
  return propertyVertex;
}
 
Example #5
Source File: StarGraphTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_USER_SUPPLIED_IDS)
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexPropertyFeatures.FEATURE_USER_SUPPLIED_IDS)
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_USER_SUPPLIED_IDS)
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES)
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_PROPERTY)
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_META_PROPERTIES)
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_MULTI_PROPERTIES)
@FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_EDGES)
@FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_PROPERTY)
public void shouldAttachWithCreateMethod() {
    final Random random = TestHelper.RANDOM;
    StarGraph starGraph = StarGraph.open();
    Vertex starVertex = starGraph.addVertex(T.label, "person", "name", "stephen", "name", "spmallete");
    starVertex.property("acl", true, "timestamp", random.nextLong(), "creator", "marko");
    for (int i = 0; i < 100; i++) {
        starVertex.addEdge("knows", starGraph.addVertex("person", "name", new UUID(random.nextLong(), random.nextLong()), "since", random.nextLong()));
        starGraph.addVertex(T.label, "project").addEdge("developedBy", starVertex, "public", random.nextBoolean());
    }
    final Vertex createdVertex = starGraph.getStarVertex().attach(Attachable.Method.create(graph));
    starGraph.getStarVertex().edges(Direction.BOTH).forEachRemaining(edge -> ((Attachable<Edge>) edge).attach(Attachable.Method.create(random.nextBoolean() ? graph : createdVertex)));
    TestHelper.validateEquality(starVertex, createdVertex);
}
 
Example #6
Source File: VertexAPI.java    From hugegraph with Apache License 2.0 6 votes vote down vote up
@DELETE
@Timed
@Path("{id}")
@Consumes(APPLICATION_JSON)
@RolesAllowed({"admin", "$owner=$graph $action=vertex_delete"})
public void delete(@Context GraphManager manager,
                   @PathParam("graph") String graph,
                   @PathParam("id") String idValue) {
    LOG.debug("Graph [{}] remove vertex by id '{}'", graph, idValue);

    Id id = checkAndParseVertexId(idValue);
    HugeGraph g = graph(manager, graph);
    // TODO: add removeVertex(id) to improve
    commit(g, () -> {
        Iterator<Vertex> iter = g.vertices(id);
        try {
            E.checkArgument(iter.hasNext(),
                            "No such vertex with id: '%s'", idValue);
            iter.next().remove();
        } finally {
            CloseableIterator.closeIterator(iter);
        }
    });
}
 
Example #7
Source File: TestEdgeCache.java    From sqlg with MIT License 6 votes vote down vote up
@Test
public void testMultipleEdgesFromSameVertex() {
    Vertex v1 = this.sqlgGraph.addVertex(T.label, "Person", "name", "mike");
    Vertex v2 = this.sqlgGraph.addVertex(T.label, "Car", "name", "bmw");
    Vertex v3 = this.sqlgGraph.addVertex(T.label, "Car", "name", "bmw");
    Vertex v4 = this.sqlgGraph.addVertex(T.label, "Bike", "name", "ktm");
    v1.addEdge("bts_aaaaaa", v2);
    v1.addEdge("bts_btsalmtos", v4);
    v1.addEdge("bts_btsalm", v3);
    this.sqlgGraph.tx().commit();
    this.sqlgGraph.close();
    try (SqlgGraph sqlgGraph = SqlgGraph.open(configuration)) {
        v1 = sqlgGraph.traversal().V(v1.id()).next();
        assertEquals(1, sqlgGraph.traversal().V(v1.id()).out("bts_btsalm").count().next().intValue());
        assertEquals(1, sqlgGraph.traversal().V(v1.id()).out("bts_btsalmtos").count().next().intValue());
    }
}
 
Example #8
Source File: SqlgAddVertexStartStep.java    From sqlg with MIT License 6 votes vote down vote up
@Override
protected Traverser.Admin<Vertex> processNextStart() {
    if (this.first) {
        this.first = false;
        final SqlgTraverserGenerator generator = SqlgTraverserGenerator.instance();
        final Vertex vertex = this.getTraversal().getGraph().get().addVertex(
                this.parameters.getKeyValues(
                        generator.generate(false, (Step)this, 1L, false, false)
                ));
        if (this.callbackRegistry != null && !this.callbackRegistry.getCallbacks().isEmpty()) {
            final EventStrategy eventStrategy = getTraversal().getStrategies().getStrategy(EventStrategy.class).get();
            final Event.VertexAddedEvent vae = new Event.VertexAddedEvent(eventStrategy.detach(vertex));
            this.callbackRegistry.getCallbacks().forEach(c -> c.accept(vae));
        }
        return generator.generate(vertex, (Step)this, 1L, false, false);
    } else
        throw FastNoSuchElementException.instance();
}
 
Example #9
Source File: TinkerGraphTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldRemoveAVertexFromAnIndex() {
    final TinkerGraph g = TinkerGraph.open();
    g.createIndex("name", Vertex.class);

    g.addVertex("name", "marko", "age", 29);
    g.addVertex("name", "stephen", "age", 35);
    final Vertex v = 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 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(2), g.traversal().V().has("age", P.test((t, u) -> {
        assertEquals(35, t);
        return true;
    }, 35)).has("name", "stephen").count().next());

    v.remove();
    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 #10
Source File: TestBatchNormalUpdatePrimitiveArrays.java    From sqlg with MIT License 6 votes vote down vote up
@Test
public void testShortArrayUpdateNull() throws InterruptedException {
    this.sqlgGraph.tx().normalBatchModeOn();
    Assume.assumeTrue(this.sqlgGraph.getSqlDialect().supportsShortArrayValues());
    Short[] shortArray = new Short[]{1, 2};
    Vertex a1 = this.sqlgGraph.addVertex(T.label, "A", "shortArray1", shortArray);
    Vertex a2 = this.sqlgGraph.addVertex(T.label, "A", "shortArray2", shortArray);
    Vertex a3 = this.sqlgGraph.addVertex(T.label, "A", "shortArray3", shortArray);
    this.sqlgGraph.tx().commit();

    this.sqlgGraph.tx().normalBatchModeOn();
    Short[] shortArrayAgain = new Short[]{3, 4};
    a1.property("shortArray1", shortArrayAgain);
    a2.property("shortArray2", shortArrayAgain);
    a3.property("shortArray3", shortArrayAgain);
    this.sqlgGraph.tx().commit();

    testShortArrayUpdateNull_assert(this.sqlgGraph, a1, a2, a3, shortArrayAgain);
    if (this.sqlgGraph1 != null) {
        sleep(SLEEP_TIME);
        testShortArrayUpdateNull_assert(this.sqlgGraph1, a1, a2, a3, shortArrayAgain);
    }
}
 
Example #11
Source File: AddEdgeTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
@LoadGraphWith(MODERN)
@FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_EDGES)
public void g_V_aggregateXxX_asXaX_selectXxX_unfold_addEXexistsWithX_toXaX_propertyXtime_nowX() {
    final Traversal<Vertex, Edge> traversal = get_g_V_aggregateXxX_asXaX_selectXxX_unfold_addEXexistsWithX_toXaX_propertyXtime_nowX();
    printTraversalForm(traversal);
    int count = 0;
    while (traversal.hasNext()) {
        final Edge edge = traversal.next();
        assertEquals("existsWith", edge.label());
        assertEquals("now", g.E(edge).values("time").next());
        assertEquals(1, g.E(edge).properties().count().next().intValue());
        count++;
    }
    assertEquals(36, count);
    assertEquals(42, IteratorUtils.count(g.E()));
    for (final Vertex vertex : IteratorUtils.list(g.V())) {
        assertEquals(6, g.V(vertex).out("existsWith").count().next().intValue());
        assertEquals(6, g.V(vertex).in("existsWith").count().next().intValue());
    }
    assertEquals(6, IteratorUtils.count(g.V()));
}
 
Example #12
Source File: RelationTypeDescription.java    From timbuctoo with GNU General Public License v3.0 6 votes vote down vote up
public RelationTypeDescription(Vertex vertex) {

    setId(vertex.<String>property("tim_id").value());
    setType(vertex.<String>property("types").value());
    setRegularName(vertex.<String>property("relationtype_regularName").value());
    setInverseName(vertex.<String>property("relationtype_inverseName").value());

    setSourceTypeName(vertex.<String>property("relationtype_sourceTypeName").value());
    setTargetTypeName(vertex.<String>property("relationtype_targetTypeName").value());


    vertex.<String>property("created").ifPresent(this::setCreated);
    vertex.<String>property("modified").ifPresent(this::setModified); 
    setRev(vertex.<Integer>property("rev").value());
    setReflexive(vertex.<Boolean>property("relationtype_reflexive").value());
    setDerived(vertex.<Boolean>property("relationtype_derived").value());
    setSymmetric(vertex.<Boolean>property("relationtype_symmetric").value());

  }
 
Example #13
Source File: EdgeListFacetDescriptionTest.java    From timbuctoo with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void filterAddsNoFilterIfTheFacetValuesIsEmpty() {
  List<FacetValue> facetValues = Lists.newArrayList(
          new ListFacetValue(FACET_NAME, Lists.newArrayList()));

  SearchRequestV2_1 searchRequest = new SearchRequestV2_1();
  searchRequest.setFacetValues(facetValues);
  GraphTraversal<Vertex, Vertex> traversal = newGraph()
          .withVertex(v -> v.withTimId("1"))
          .withVertex(v -> v.withTimId("2"))
          .build().traversal().V();

  instance.filter(traversal, facetValues);

  assertThat(traversal.toList(),
          containsInAnyOrder(VertexMatcher.likeVertex().withTimId("1"), VertexMatcher.likeVertex().withTimId("2")));
}
 
Example #14
Source File: TinkerPopOperations.java    From timbuctoo with GNU General Public License v3.0 6 votes vote down vote up
private void saveRelationType(RelationType relationType) {
  final String rdfUri = TIMBUCTOO_NAMESPACE + relationType.getOutName();
  final String[] rdfAlternatives = {TIMBUCTOO_NAMESPACE + relationType.getInverseName()};
  final Vertex vertex = graph.addVertex(
    T.label, "relationtype",
    "rev", 1,
    "types", jsnA(jsn("relationtype")).toString(),
    "isLatest", true,
    "tim_id", relationType.getTimId().toString(),

    "relationtype_regularName", relationType.getOutName(),
    "relationtype_inverseName", relationType.getInverseName(),
    "relationtype_sourceTypeName", relationType.getSourceTypeName(),
    "relationtype_targetTypeName", relationType.getTargetTypeName(),

    "relationtype_reflexive", relationType.isReflexive(),
    "relationtype_symmetric", relationType.isSymmetric(),
    "relationtype_derived", relationType.isDerived(),

    "rdfUri", rdfUri,
    "rdfAlternatives", rdfAlternatives
  );

  systemPropertyModifier.setCreated(vertex, "timbuctoo", "timbuctoo");
}
 
Example #15
Source File: TestLocalVertexStepOptional.java    From sqlg with MIT License 5 votes vote down vote up
@Test
public void testUnoptimizableChooseStep() {
    Vertex a1 = this.sqlgGraph.addVertex(T.label, "A");
    Vertex b1 = this.sqlgGraph.addVertex(T.label, "B");
    Vertex b2 = this.sqlgGraph.addVertex(T.label, "B");
    a1.addEdge("ab", b1);
    a1.addEdge("ab", b2);
    this.sqlgGraph.tx().commit();

    DefaultGraphTraversal<Vertex, Vertex> traversal = (DefaultGraphTraversal<Vertex, Vertex>)this.sqlgGraph.traversal()
            .V(a1)
            .local(
                    __.<Vertex, Vertex>choose(
                            v -> v.label().equals("A"), __.out(), __.in()
                    )
            );
    List<Vertex> vertices = traversal.toList();
    Assert.assertEquals(2, traversal.getSteps().size());
    Assert.assertTrue(traversal.getSteps().get(1) instanceof SqlgLocalStepBarrier);
    SqlgLocalStepBarrier<?, ?> localStep = (SqlgLocalStepBarrier) traversal.getSteps().get(1);
    List<SqlgVertexStep> sqlgVertexStepCompileds = TraversalHelper.getStepsOfAssignableClassRecursively(SqlgVertexStep.class, localStep.getLocalChildren().get(0));
    Assert.assertEquals(2, sqlgVertexStepCompileds.size());
    SqlgVertexStep sqlgVertexStepCompiled = sqlgVertexStepCompileds.get(0);
    assertStep(sqlgVertexStepCompiled, false, false, false, true);
    sqlgVertexStepCompiled = sqlgVertexStepCompileds.get(1);
    assertStep(sqlgVertexStepCompiled, false, false, false, true);
    Assert.assertEquals(2, vertices.size());
}
 
Example #16
Source File: MinTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
@LoadGraphWith(MODERN)
public void g_V_age_min() {
    final Traversal<Vertex, Integer> traversal = get_g_V_age_min();
    printTraversalForm(traversal);
    checkResults(Arrays.asList(27), traversal);
}
 
Example #17
Source File: AndTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
@LoadGraphWith(MODERN)
public void g_V_hasXname_markoX_and_hasXname_markoX_and_hasXname_markoX() {
    final Traversal<Vertex, Vertex> traversal = get_g_V_hasXname_markoX_and_hasXname_markoX_and_hasXname_markoX();
    printTraversalForm(traversal);
    checkResults(Collections.singletonList(convertToVertex(graph, "marko")), traversal);
}
 
Example #18
Source File: GraphSONMessageSerializerV3d0Test.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldSerializeEdge() throws Exception {
    final Graph graph = TinkerGraph.open();
    final Vertex v1 = graph.addVertex();
    final Vertex v2 = graph.addVertex();
    final Edge e = v1.addEdge("test", v2);
    e.property("abc", 123);

    final Iterable<Edge> iterable = IteratorUtils.list(graph.edges());

    final ResponseMessage response = convert(iterable);
    assertCommon(response);

    final List<Edge> edgeList = (List<Edge>) response.getResult().getData();
    assertEquals(1, edgeList.size());

    final Edge deserializedEdge = edgeList.get(0);
    assertEquals(e.id(), deserializedEdge.id());
    assertEquals(v1.id(), deserializedEdge.outVertex().id());
    assertEquals(v2.id(), deserializedEdge.inVertex().id());
    assertEquals(v1.label(), deserializedEdge.outVertex().label());
    assertEquals(v2.label(), deserializedEdge.inVertex().label());
    assertEquals(e.label(), deserializedEdge.label());

    final List<Property> properties = new ArrayList<>();
    deserializedEdge.properties().forEachRemaining(properties::add);
    assertEquals(1, properties.size());

    assertNotNull(properties);
    assertEquals("abc", properties.get(0).key());
    assertEquals(123, properties.get(0).value());

}
 
Example #19
Source File: TestArrayProperties.java    From sqlg with MIT License 5 votes vote down vote up
@Test
public void testByteArrayProperties() {
    Assume.assumeTrue(this.sqlgGraph.getSqlDialect().supportsByteArrayValues());
    Vertex vertex1 = this.sqlgGraph.addVertex(T.label, "Person", "age", new Byte[]{1, 2, 3, 4, 5});
    Vertex vertex2 = this.sqlgGraph.addVertex(T.label, "Person", "age", new Byte[]{1, 2, 3, 4, 5});
    vertex1.addEdge("test", vertex2, "age", new Byte[]{1, 2, 3, 4, 5});
    this.sqlgGraph.tx().commit();
    Vertex v = this.sqlgGraph.traversal().V().next();
    assertTrue(Arrays.equals(new Byte[]{1, 2, 3, 4, 5}, (Byte[]) v.property("age").value()));
    Edge e = this.sqlgGraph.traversal().E().next();
    assertTrue(Arrays.equals(new Byte[]{1, 2, 3, 4, 5}, (Byte[]) e.property("age").value()));
}
 
Example #20
Source File: JavaGraphLoader.java    From Ferma with Apache License 2.0 5 votes vote down vote up
private Vertex makeClass(Graph graph, Vertex superClass, Class<?> javaClass, Vertex... implementedInterfaces) {
    Vertex classVertex = makeType(graph, JavaClassVertex.class, javaClass, JavaAccessModifier.PUBLIC);
    
    for (Vertex implInterface : implementedInterfaces) {
        classVertex.addEdge("implements", implInterface, TYPE_RESOLUTION_KEY, ImplementsEdge.class.getName());
    }
    
    if (superClass != null) {
        classVertex.addEdge("extends", superClass, TYPE_RESOLUTION_KEY, ExtendsEdge.class.getName());
    }
    return classVertex;
}
 
Example #21
Source File: OrderTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
@LoadGraphWith(MODERN)
public void g_V_outE_order_byXweight_descX_weight() {
    final Traversal<Vertex, Double> traversal = get_g_V_outE_order_byXweight_descX_weight();
    printTraversalForm(traversal);
    checkOrderedResults(Arrays.asList(1.0d, 1.0d, 0.5d, 0.4d, 0.4d, 0.2d), traversal);
}
 
Example #22
Source File: ElementFactoryTest.java    From act-platform with ISC License 5 votes vote down vote up
@Test
public void testGetVertexCached() {
  ObjectTypeStruct objectTypeMock = mockObjectType();
  ObjectRecord objectSource = mockObject(objectTypeMock);

  UUID objectID = objectSource.getId();
  Vertex first = elementFactory.getVertex(objectID);
  Vertex second = elementFactory.getVertex(objectID);

  assertSame(first, second);
}
 
Example #23
Source File: InjectTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
@LoadGraphWith(MODERN)
public void g_VX1X_injectXg_VX4XX_out_name() {
    final Traversal<Vertex, String> traversal = get_g_VX1X_injectXg_VX4XX_out_name(convertToVertexId("marko"), convertToVertexId("josh"));
    printTraversalForm(traversal);
    checkResults(Arrays.asList("ripple", "lop", "lop", "vadas", "josh"), traversal);
}
 
Example #24
Source File: TestGraphStepWithIds.java    From sqlg with MIT License 5 votes vote down vote up
@Test
public void testGraphWithIds() {
    Vertex a1 = this.sqlgGraph.addVertex(T.label, "A");
    Vertex a2 = this.sqlgGraph.addVertex(T.label, "A");
    Vertex a3 = this.sqlgGraph.addVertex(T.label, "A");
    this.sqlgGraph.tx().commit();

    List<Vertex> vertices = this.sqlgGraph.traversal().V(a1.id()).toList();
    Assert.assertEquals(1, vertices.size());
    Assert.assertEquals(a1, vertices.get(0));

    vertices = this.sqlgGraph.traversal().V(a1).toList();
    Assert.assertEquals(1, vertices.size());
    Assert.assertEquals(a1, vertices.get(0));
}
 
Example #25
Source File: EventStrategyProcessTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
@FeatureRequirementSet(FeatureRequirementSet.Package.VERTICES_ONLY)
public void shouldDetachVertexPropertyWhenRemoved() {
    final AtomicBoolean triggered = new AtomicBoolean(false);
    final Vertex v = graph.addVertex();
    final VertexProperty vp = v.property("to-remove","blah");
    final String label = vp.label();
    final Object value = vp.value();
    final VertexProperty vpToKeep = v.property("to-keep","dah");

    final MutationListener listener = new AbstractMutationListener() {
        @Override
        public void vertexPropertyRemoved(final VertexProperty element) {
            assertThat(element, instanceOf(DetachedVertexProperty.class));
            assertEquals(label, element.label());
            assertEquals(value, element.value());
            triggered.set(true);
        }
    };
    final EventStrategy.Builder builder = EventStrategy.build().addListener(listener);

    if (graph.features().graph().supportsTransactions())
        builder.eventQueue(new EventStrategy.TransactionalEventQueue(graph));

    final EventStrategy eventStrategy = builder.create();
    final GraphTraversalSource gts = create(eventStrategy);

    gts.V(v).properties("to-remove").drop().iterate();
    tryCommit(graph);

    assertEquals(1, IteratorUtils.count(g.V(v).properties()));
    assertEquals(vpToKeep.value(), g.V(v).values("to-keep").next());
    assertThat(triggered.get(), is(true));
}
 
Example #26
Source File: MatchTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
@LoadGraphWith(MODERN)
public void g_V_notXmatchXa_age_b__a_name_cX_whereXb_eqXcXX_selectXaXX_name() {
    final Traversal<Vertex, String> traversal = get_g_V_notXmatchXa_age_b__a_name_cX_whereXb_eqXcXX_selectXaXX_name();
    printTraversalForm(traversal);
    checkResults(Arrays.asList("marko", "peter", "josh", "vadas", "lop", "ripple"), traversal);
}
 
Example #27
Source File: ProfileTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
@LoadGraphWith(GRATEFUL)
public void grateful_V_out_out_profile() {
    final Traversal<Vertex, TraversalMetrics> traversal = get_g_V_out_out_profile();
    printTraversalForm(traversal);
    final TraversalMetrics traversalMetrics = traversal.next();
    validate_g_V_out_out_profile_grateful(traversalMetrics);
}
 
Example #28
Source File: TestGremlinCompileWithAs.java    From sqlg with MIT License 5 votes vote down vote up
@Test
public void testChainSelect() throws Exception {
    Vertex a1 = this.sqlgGraph.addVertex(T.label, "Person", "name", "a1");
    Vertex a2 = this.sqlgGraph.addVertex(T.label, "Person", "name", "a2");
    a1.addEdge("friend", a2, "weight", 5);
    this.sqlgGraph.tx().commit();

    testChainSelect_assert(this.sqlgGraph, a2);
    if (this.sqlgGraph1 != null) {
        Thread.sleep(SLEEP_TIME);
        testChainSelect_assert(this.sqlgGraph1, a2);
    }

}
 
Example #29
Source File: BitsyEdge.java    From bitsy with Apache License 2.0 5 votes vote down vote up
@Override
public Iterator<Vertex> vertices(Direction dir) {
    tx.validateForQuery(this);

    if (dir != Direction.BOTH) {
        Vertex ans = inOrOutVertex(dir);

        return Collections.singleton(ans).iterator();
    } else {
        return bothVertices();
    }
}
 
Example #30
Source File: GraphComputerTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(Vertex vertex, Messenger<Long> messenger, Memory memory) {
    switch (memory.getIteration()) {
        case 0:
            if (vertex.value("name").equals("josh")) {
                messenger.sendMessage(this.countMessageScopeIn, 2L);
                messenger.sendMessage(this.countMessageScopeOut, 1L);
            }
            break;
        case 1:
            long edgeCount = IteratorUtils.reduce(messenger.receiveMessages(), 0L, (a, b) -> a + b);
            vertex.property(MEMORY_KEY, edgeCount);
            break;
    }
}