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

The following examples show how to use org.apache.tinkerpop.gremlin.structure.Edge. 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: tinkerpop   Author: apache   File: VertexTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@LoadGraphWith(MODERN)
public void g_VX4X_bothE() {
    final Traversal<Vertex, Edge> traversal = get_g_VX4X_bothE(convertToVertexId("josh"));
    printTraversalForm(traversal);
    int counter = 0;
    final Set<Edge> edges = new HashSet<>();
    while (traversal.hasNext()) {
        counter++;
        final Edge edge = traversal.next();
        edges.add(edge);
        assertTrue(edge.label().equals("knows") || edge.label().equals("created"));
    }
    assertEquals(3, counter);
    assertEquals(3, edges.size());
}
 
Example #2
Source Project: tinkerpop   Author: apache   File: PageRankVertexProgramStep.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void configure(final Object... keyValues) {
    if (keyValues[0].equals(PageRank.edges)) {
        if (!(keyValues[1] instanceof Traversal))
            throw new IllegalArgumentException("PageRank.edges requires a Traversal as its argument");
        this.edgeTraversal = new PureTraversal<>(((Traversal<Vertex,Edge>) keyValues[1]).asAdmin());
        this.integrateChild(this.edgeTraversal.get());
    } else if (keyValues[0].equals(PageRank.propertyName)) {
        if (!(keyValues[1] instanceof String))
            throw new IllegalArgumentException("PageRank.propertyName requires a String as its argument");
        this.pageRankProperty = (String) keyValues[1];
    } else if (keyValues[0].equals(PageRank.times)) {
        if (!(keyValues[1] instanceof Integer))
            throw new IllegalArgumentException("PageRank.times requires an Integer as its argument");
        this.times = (int) keyValues[1];
    } else {
        this.parameters.set(this, keyValues);
    }
}
 
Example #3
Source Project: timbuctoo   Author: HuygensING   File: DatabaseFixerTest.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Test
public void fixAddsAVersionOfRelation() {
  String vertex1CreatedProp = changeStringWithTimestamp(1500L);
  GraphWrapper graphWrapper = newGraph().withVertex("v1", v -> v.withTimId("id1")
                                                                .withProperty("rev", 2)
                                                                .withProperty("modified",
                                                                  changeStringWithTimestamp(10000L))
                                                                .withProperty("created", vertex1CreatedProp)
                                                                .withProperty("isLatest", true))
                                        .wrap();
  DatabaseFixer instance = new DatabaseFixer(graphWrapper);

  instance.fix();


  Optional<Vertex> vertex = graphWrapper.getGraph().traversal().V().has("tim_id", "id1").has("rev", 1).tryNext();
  assertThat(vertex, is(present()));
  Iterator<Edge> versionOfRelations = vertex.get().edges(Direction.OUT, "VERSION_OF");
  assertThat(versionOfRelations.hasNext(), is(true));
}
 
Example #4
Source Project: sqlg   Author: pietermartin   File: TestBatchNormalUpdateDateTime.java    License: MIT License 6 votes vote down vote up
@Test
public void batchUpdateZonedDateTimeEdge() throws InterruptedException {
    this.sqlgGraph.tx().normalBatchModeOn();
    ZonedDateTime zonedDateTime = ZonedDateTime.now();
    for (int i = 0; i < 10; i++) {
        Vertex v1 = this.sqlgGraph.addVertex(T.label, "Person", "createOn", zonedDateTime);
        Vertex v2 = this.sqlgGraph.addVertex(T.label, "Person", "createOn", zonedDateTime);
        v1.addEdge("test", v2, "createOn", zonedDateTime);
    }
    this.sqlgGraph.tx().commit();
    List<Edge> edges = this.sqlgGraph.traversal().E().toList();
    Assert.assertEquals(10, edges.size());
    Assert.assertEquals(zonedDateTime, edges.get(0).value("createOn"));
    this.sqlgGraph.tx().normalBatchModeOn();
    zonedDateTime = ZonedDateTime.now().minusDays(1);
    for (Edge edge : edges) {
        edge.property("createOn", zonedDateTime);
    }
    this.sqlgGraph.tx().commit();
    batchUpdateZonedDateTimeEdge_assert(this.sqlgGraph, zonedDateTime);
    if (this.sqlgGraph1 != null) {
        Thread.sleep(SLEEP_TIME);
        batchUpdateZonedDateTimeEdge_assert(this.sqlgGraph1, zonedDateTime);
    }
}
 
Example #5
Source Project: sqlg   Author: pietermartin   File: TestTraversalAddV.java    License: MIT License 6 votes vote down vote up
@Test
public void g_addV_asXfirstX_repeatXaddEXnextX_toXaddVX_inVX_timesX5X_addEXnextX_toXselectXfirstXX() {
    final Traversal<Vertex, Edge> traversal = this.sqlgGraph.traversal()
            .addV().as("first")
            .repeat(
                    __.addE("next").to(__.addV()).inV()).times(5)
            .addE("next")
            .to(__.select("first"));
    printTraversalForm(traversal);
    Assert.assertEquals("next", traversal.next().label());
    Assert.assertFalse(traversal.hasNext());
    Assert.assertEquals(6L, this.sqlgGraph.traversal().V().count().next().longValue());
    Assert.assertEquals(6L, this.sqlgGraph.traversal().E().count().next().longValue());
    Assert.assertEquals(Arrays.asList(2L, 2L, 2L, 2L, 2L, 2L), this.sqlgGraph.traversal().V().map(__.bothE().count()).toList());
    Assert.assertEquals(Arrays.asList(1L, 1L, 1L, 1L, 1L, 1L), this.sqlgGraph.traversal().V().map(__.inE().count()).toList());
    Assert.assertEquals(Arrays.asList(1L, 1L, 1L, 1L, 1L, 1L), this.sqlgGraph.traversal().V().map(__.outE().count()).toList());
}
 
Example #6
Source Project: timbuctoo   Author: HuygensING   File: FileLogOutput.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public void newEdge(Edge edge) {
  String modifiedString = edge.value("modified");
  try {
    Change modified = objectMapper.readValue(modifiedString, Change.class);
    writeAndFlush(
      String.format(
        "%d - Edge with tim_id '%s' between Vertex with tim_id '%s' and Vertex with tim_id '%s' created.%n",
        modified.getTimeStamp(),
        edge.value("tim_id"),
        edge.outVertex().value("tim_id"),
        edge.inVertex().value("tim_id")));
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example #7
Source Project: sqlg   Author: pietermartin   File: TestVertexNavToEdges.java    License: MIT License 6 votes vote down vote up
@Test
public void testInOut() {
    Vertex v1 = sqlgGraph.addVertex();
    Vertex v2 = sqlgGraph.addVertex();
    Vertex v3 = sqlgGraph.addVertex();
    Vertex v4 = sqlgGraph.addVertex();
    Vertex v5 = sqlgGraph.addVertex();
    Edge e1 = v1.addEdge("label1", v2);
    Edge e2 = v2.addEdge("label2", v3);
    Edge e3 = v3.addEdge("label3", v4);
    sqlgGraph.tx().commit();

    assertEquals(1, vertexTraversal(this.sqlgGraph, v2).inE().count().next(), 1);
    assertEquals(e1, vertexTraversal(this.sqlgGraph, v2).inE().next());
    assertEquals(1L, edgeTraversal(this.sqlgGraph, e1).inV().count().next(), 0);
    assertEquals(v2, edgeTraversal(this.sqlgGraph, e1).inV().next());
    assertEquals(0L, edgeTraversal(this.sqlgGraph, e1).outV().inE().count().next(), 0);
    assertEquals(1L, edgeTraversal(this.sqlgGraph, e2).inV().count().next(), 0);
    assertEquals(v3, edgeTraversal(this.sqlgGraph, e2).inV().next());
}
 
Example #8
Source Project: hugegraph   Author: hugegraph   File: EdgeAPI.java    License: Apache License 2.0 6 votes vote down vote up
@GET
@Timed
@Path("{id}")
@Produces(APPLICATION_JSON_WITH_CHARSET)
@RolesAllowed({"admin", "$owner=$graph $action=edge_read"})
public String get(@Context GraphManager manager,
                  @PathParam("graph") String graph,
                  @PathParam("id") String id) {
    LOG.debug("Graph [{}] get edge by id '{}'", graph, id);

    HugeGraph g = graph(manager, graph);
    try {
        Iterator<Edge> edges = g.edges(id);
        checkExist(edges, HugeType.EDGE, id);
        return manager.serializer(g).writeEdge(edges.next());
    } finally {
        if (g.tx().isOpen()) {
            g.tx().close();
        }
    }
}
 
Example #9
Source Project: sqlg   Author: pietermartin   File: TestBatch.java    License: MIT License 6 votes vote down vote up
@Test
public void testBatchRemoveVerticesAndEdges() throws InterruptedException {
    Vertex v1 = this.sqlgGraph.addVertex(T.label, "Person");
    Vertex v2 = this.sqlgGraph.addVertex(T.label, "Person");
    Vertex v3 = this.sqlgGraph.addVertex(T.label, "Person");
    Edge edge1 = v1.addEdge("test", v2);
    Edge edge2 = v1.addEdge("test", v3);
    this.sqlgGraph.tx().commit();
    this.sqlgGraph.tx().normalBatchModeOn();
    edge1.remove();
    edge2.remove();
    v1.remove();
    v2.remove();
    v3.remove();
    this.sqlgGraph.tx().commit();
    testBatchRemoveVerticesAndEdges_assert(this.sqlgGraph);
    if (this.sqlgGraph1 != null) {
        Thread.sleep(1000);
        testBatchRemoveVerticesAndEdges_assert(this.sqlgGraph1);
    }
}
 
Example #10
Source Project: sqlg   Author: pietermartin   File: TestBatchServerSideEdgeCreation.java    License: MIT License 6 votes vote down vote up
@Test
public void testBulkAddEdgesStringAndIntegerIds() throws InterruptedException {
    Vertex realWorkspaceElement1 = this.sqlgGraph.addVertex(T.label, "RealWorkspaceElement", "cmUid", "a");
    Vertex realWorkspaceElement2 = this.sqlgGraph.addVertex(T.label, "RealWorkspaceElement", "cmUid", "b");
    Vertex virtualGroup = this.sqlgGraph.addVertex(T.label, "VirtualGroup", "name", "asd");
    this.sqlgGraph.tx().commit();
    Edge e =realWorkspaceElement1.addEdge("realWorkspaceElement_virtualGroup", virtualGroup);
    this.sqlgGraph.tx().commit();
    e.remove();
    this.sqlgGraph.tx().commit();

    this.sqlgGraph.tx().streamingBatchModeOn();
    List<Pair<String, Integer>> ids = new ArrayList<>();
    ids.add(Pair.of("a", 1));
    ids.add(Pair.of("b", 1));
    this.sqlgGraph.bulkAddEdges("RealWorkspaceElement", "VirtualGroup", "realWorkspaceElement_virtualGroup", Pair.of("cmUid", "ID"), ids);
    this.sqlgGraph.tx().commit();

    testBulkAddEdgeStringAndIntegerIds_assert(this.sqlgGraph, realWorkspaceElement1, realWorkspaceElement2, virtualGroup);
    if (this.sqlgGraph1 != null) {
        Thread.sleep(SLEEP_TIME);
        testBulkAddEdgeStringAndIntegerIds_assert(this.sqlgGraph1, realWorkspaceElement1, realWorkspaceElement2, virtualGroup);
    }
}
 
Example #11
Source Project: tinkerpop   Author: apache   File: AddEdgeTest.java    License: 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_addEXknowsX_fromXaX_toXbX_propertyXweight_0_1X() {
    final Vertex a = g.V().has("name", "marko").next();
    final Vertex b = g.V().has("name", "peter").next();

    final Traversal<Edge, Edge> traversal = get_g_addEXknowsX_fromXaX_toXbX_propertyXweight_0_1X(a, b);
    printTraversalForm(traversal);
    final Edge edge = traversal.next();
    assertEquals(edge.outVertex(), convertToVertex(graph, "marko"));
    assertEquals(edge.inVertex(), convertToVertex(graph, "peter"));
    assertEquals("knows", edge.label());
    assertEquals(1, IteratorUtils.count(edge.properties()));
    assertEquals(0.1d, edge.value("weight"), 0.1d);
    assertEquals(6L, g.V().count().next().longValue());
    assertEquals(7L, g.E().count().next().longValue());
}
 
Example #12
Source Project: hgraphdb   Author: rayokota   File: EdgeReader.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void load(Edge edge, Result result) {
    if (result.isEmpty()) {
        throw new HBaseGraphNotFoundException(edge, "Edge does not exist: " + edge.id());
    }
    Object inVertexId = null;
    Object outVertexId = null;
    String label = null;
    Long createdAt = null;
    Long updatedAt = null;
    Map<String, byte[]> rawProps = new HashMap<>();
    for (Cell cell : result.listCells()) {
        String key = Bytes.toString(CellUtil.cloneQualifier(cell));
        if (!Graph.Hidden.isHidden(key)) {
            rawProps.put(key, CellUtil.cloneValue(cell));
        } else if (key.equals(Constants.TO)) {
            inVertexId = ValueUtils.deserialize(CellUtil.cloneValue(cell));
        } else if (key.equals(Constants.FROM)) {
            outVertexId = ValueUtils.deserialize(CellUtil.cloneValue(cell));
        } else if (key.equals(Constants.LABEL)) {
            label = ValueUtils.deserialize(CellUtil.cloneValue(cell));
        } else if (key.equals(Constants.CREATED_AT)) {
            createdAt = ValueUtils.deserialize(CellUtil.cloneValue(cell));
        } else if (key.equals(Constants.UPDATED_AT)) {
            updatedAt = ValueUtils.deserialize(CellUtil.cloneValue(cell));
        }
    }
    final String labelStr = label;
    Map<String, Object> props = rawProps.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey,
            e -> ValueUtils.deserializePropertyValue(graph, ElementType.EDGE, labelStr, e.getKey(), e.getValue())));
    if (inVertexId != null && outVertexId != null && label != null) {
        HBaseEdge newEdge = new HBaseEdge(graph, edge.id(), label, createdAt, updatedAt, props,
                graph.findOrCreateVertex(inVertexId),
                graph.findOrCreateVertex(outVertexId));
        ((HBaseEdge) edge).copyFrom(newEdge);
    } else {
        throw new IllegalStateException("Unable to parse edge from cells");
    }
}
 
Example #13
Source Project: sqlg   Author: pietermartin   File: TestLocalStepCompile.java    License: MIT License 5 votes vote down vote up
@Test
public void testSelectVertexAndEdgeOrderByEdge() {
    Vertex god = this.sqlgGraph.addVertex(T.label, "God");
    Vertex fantasy1 = this.sqlgGraph.addVertex(T.label, "Fantasy", "name", "fan1");
    Vertex fantasy2 = this.sqlgGraph.addVertex(T.label, "Fantasy", "name", "fan2");
    Vertex fantasy3 = this.sqlgGraph.addVertex(T.label, "Fantasy", "name", "fan3");
    Vertex fantasy4 = this.sqlgGraph.addVertex(T.label, "Fantasy", "name", "fan4");
    Edge e1 = god.addEdge("godDream", fantasy1, "sequence", 1);
    Edge e2 = god.addEdge("godDream", fantasy2, "sequence", 2);
    Edge e3 = god.addEdge("godDream", fantasy3, "sequence", 3);
    Edge e4 = god.addEdge("godDream", fantasy4, "sequence", 4);
    this.sqlgGraph.tx().commit();
    DefaultGraphTraversal<Vertex, Map<String, Object>> traversal = (DefaultGraphTraversal<Vertex, Map<String, Object>>) this.sqlgGraph.traversal().V(god)
            .outE("godDream").as("e")
            .inV().as("v")
            .select("e", "v")
            .order().by(__.select("e").by("sequence"), Order.desc);
    Assert.assertEquals(5, traversal.getSteps().size());
    List<Map<String, Object>> result = traversal.toList();
    Assert.assertEquals(2, traversal.getSteps().size());

    Assert.assertEquals(4, result.size());
    Assert.assertEquals(fantasy4, result.get(0).get("v"));
    Assert.assertEquals(fantasy3, result.get(1).get("v"));
    Assert.assertEquals(fantasy2, result.get(2).get("v"));
    Assert.assertEquals(fantasy1, result.get(3).get("v"));

    Assert.assertEquals(e4, result.get(0).get("e"));
    Assert.assertEquals(e3, result.get(1).get("e"));
    Assert.assertEquals(e2, result.get(2).get("e"));
    Assert.assertEquals(e1, result.get(3).get("e"));
}
 
Example #14
Source Project: tinkerpop   Author: apache   File: GraphMLReader.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * This method is not supported for this reader.
 *
 * @throws UnsupportedOperationException when called.
 */
@Override
public Iterator<Vertex> readVertices(final InputStream inputStream,
                                     final Function<Attachable<Vertex>, Vertex> vertexAttachMethod,
                                     final Function<Attachable<Edge>, Edge> edgeAttachMethod,
                                     final Direction attachEdgesOfThisDirection) throws IOException {
    throw Io.Exceptions.readerFormatIsForFullGraphSerializationOnly(this.getClass());
}
 
Example #15
Source Project: janusgraph-java-example   Author: pluradj   File: JavaExample.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    JanusGraph graph = JanusGraphFactory.open("conf/janusgraph-berkeleyje-lucene.properties");
    GraphTraversalSource g = graph.traversal();
    if (g.V().count().next() == 0) {
        // load the schema and graph data
        GraphOfTheGodsFactory.load(graph);
    }
    Map<Object, Object> saturnProps = g.V().has("name", "saturn").valueMap(true).next();
    LOGGER.info(saturnProps.toString());
    List<Edge> places = g.E().has("place", Geo.geoWithin(Geoshape.circle(37.97, 23.72, 50))).toList();
    LOGGER.info(places.toString());
    System.exit(0);
}
 
Example #16
Source Project: hugegraph   Author: hugegraph   File: HugeVertex.java    License: Apache License 2.0 5 votes vote down vote up
public Iterator<Edge> getEdges(Directions direction, String... edgeLabels) {
    List<Edge> list = new LinkedList<>();
    for (HugeEdge edge : this.edges) {
        if (edge.matchDirection(direction) &&
            edge.belongToLabels(edgeLabels)) {
            list.add(edge);
        }
    }
    return list.iterator();
}
 
Example #17
Source Project: timbuctoo   Author: HuygensING   File: IdIndexChangeListenerTest.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Test
public void onEdgeUpdateCallsTheIndexHandler() {
  UUID timId = UUID.randomUUID();
  Edge edge = edgeWithId(timId);
  Edge nullEdge = null;

  instance.onEdgeUpdate(NULL_COLLECTION, nullEdge, edge);

  verify(indexHandler).upsertIntoEdgeIdIndex(timId, edge);
}
 
Example #18
Source Project: tinkergraph-gremlin   Author: ShiftLeftSecurity   File: TinkerGraphTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldUpdateEdgeIndicesInExistingGraph() {
    final TinkerGraph g = TinkerGraph.open();

    final Vertex v = g.addVertex();
    v.addEdge("friend", v, "oid", "1", "weight", 0.5f);
    v.addEdge("friend", v, "oid", "2", "weight", 0.6f);

    // 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 "1" and "2" weights both pass through the pipeline.
    assertEquals(new Long(1), g.traversal().E().has("weight", P.test((t, u) -> {
        assertTrue(t.equals(0.5f) || t.equals(0.6f));
        return true;
    }, 0.5)).has("oid", "1").count().next());

    g.createIndex("oid", Edge.class);

    // another spy into the pipeline for index check.  in this case, we know that at index
    // is used because only oid 1 should pass through the pipeline due to the inclusion of the
    // key index lookup on "oid".  If there's an weight of something other than 0.5f in the pipeline being
    // evaluated then something is wrong.
    assertEquals(new Long(1), g.traversal().E().has("weight", P.test((t, u) -> {
        assertEquals(0.5f, t);
        return true;
    }, 0.5)).has("oid", "1").count().next());
}
 
Example #19
Source Project: tinkerpop   Author: apache   File: EventStrategyProcessTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
@FeatureRequirementSet(FeatureRequirementSet.Package.SIMPLE)
public void shouldDetachPropertyOfEdgeWhenChanged() {
    final AtomicBoolean triggered = new AtomicBoolean(false);
    final Vertex v = graph.addVertex();
    final Edge e = v.addEdge("self", v);
    final String label = e.label();
    final Object inId = v.id();
    final Object outId = v.id();
    e.property("to-change", "no!");

    final MutationListener listener = new AbstractMutationListener() {
        @Override
        public void edgePropertyChanged(final Edge element, final Property oldValue, final Object setValue) {
            assertThat(element, instanceOf(DetachedEdge.class));
            assertEquals(label, element.label());
            assertEquals(inId, element.inVertex().id());
            assertEquals(outId, element.outVertex().id());
            assertEquals("no!", oldValue.value());
            assertEquals("to-change", oldValue.key());
            assertEquals("yay!", setValue);
            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.E(e).property("to-change","yay!").iterate();
    tryCommit(graph);

    assertEquals(1, IteratorUtils.count(g.E(e).properties()));
    assertThat(triggered.get(), is(true));
}
 
Example #20
Source Project: sqlg   Author: pietermartin   File: TestBatchEdgeDateTime.java    License: MIT License 5 votes vote down vote up
@Test
public void testLocalTime() throws InterruptedException {
    this.sqlgGraph.tx().normalBatchModeOn();
    Vertex personA = this.sqlgGraph.addVertex(T.label, "Person", "name", "A");
    Vertex personB = this.sqlgGraph.addVertex(T.label, "Person", "name", "B");
    LocalTime localTime = LocalTime.now();
    Edge e = personA.addEdge("loves", personB, "localTime", localTime);
    this.sqlgGraph.tx().commit();
    testLocalTime_assert(this.sqlgGraph, localTime, e);
    if (this.sqlgGraph1 != null) {
        Thread.sleep(1000);
        testLocalTime_assert(this.sqlgGraph1, localTime, e);
    }
}
 
Example #21
Source Project: tinkerpop   Author: apache   File: DetachedPropertyTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
@LoadGraphWith(LoadGraphWith.GraphData.MODERN)
public void shouldAttachToGraph() {
    final Edge e = g.E(convertToEdgeId("josh", "created", "lop")).next();
    final Property toDetach = e.properties("weight").next();
    final DetachedProperty<?> detachedProperty = DetachedFactory.detach(toDetach);
    final Property attached = detachedProperty.attach(Attachable.Method.get(graph));

    assertEquals(toDetach, attached);
    assertFalse(attached instanceof DetachedProperty);
}
 
Example #22
Source Project: egeria   Author: odpi   File: GraphOMRSMetadataStore.java    License: Apache License 2.0 5 votes vote down vote up
synchronized void updateRelationshipInStore(Relationship relationship)
        throws
        RepositoryErrorException
{

    String methodName = "updateRelationshipInStore";

    String guid = relationship.getGUID();
    GraphTraversalSource g = instanceGraph.traversal();

    Iterator<Edge> edgeIt = g.E().hasLabel("Relationship").has(PROPERTY_KEY_RELATIONSHIP_GUID, guid);

    if (edgeIt.hasNext()) {
        Edge edge = edgeIt.next();
        log.debug("{} found existing edge {}", methodName, edge);

        try {

            relationshipMapper.mapRelationshipToEdge(relationship, edge);

        } catch (Exception e) {

            log.error("{} Caught exception from relationship mapper {}", methodName, e.getMessage());
            g.tx().rollback();
            throw new RepositoryErrorException(GraphOMRSErrorCode.RELATIONSHIP_NOT_UPDATED.getMessageDefinition(relationship.getGUID(), methodName,
                                                                                                                this.getClass().getName(),
                                                                                                                repositoryName),
                    this.getClass().getName(),
                    methodName, e);
        }
    }

    g.tx().commit();
}
 
Example #23
Source Project: titan1withtp3.1   Author: graben1437   File: TitanIndexTest.java    License: Apache License 2.0 5 votes vote down vote up
private void setupChainGraph(int numV, String[] strs, boolean sameNameMapping) {
    clopen(option(INDEX_NAME_MAPPING, INDEX), sameNameMapping);
    TitanGraphIndex vindex = getExternalIndex(Vertex.class, INDEX);
    TitanGraphIndex eindex = getExternalIndex(Edge.class, INDEX);
    TitanGraphIndex pindex = getExternalIndex(TitanVertexProperty.class, INDEX);
    PropertyKey name = makeKey("name", String.class);

    mgmt.addIndexKey(vindex, name, getStringMapping());
    mgmt.addIndexKey(eindex, name, getStringMapping());
    mgmt.addIndexKey(pindex, name, getStringMapping(), Parameter.of("mapped-name", "xstr"));
    PropertyKey text = makeKey("text", String.class);
    mgmt.addIndexKey(vindex, text, getTextMapping(), Parameter.of("mapped-name", "xtext"));
    mgmt.addIndexKey(eindex, text, getTextMapping());
    mgmt.addIndexKey(pindex, text, getTextMapping());
    mgmt.makeEdgeLabel("knows").signature(name).make();
    mgmt.makePropertyKey("uid").dataType(String.class).signature(text).make();
    finishSchema();
    TitanVertex previous = null;
    for (int i = 0; i < numV; i++) {
        TitanVertex v = graph.addVertex("name", strs[i % strs.length], "text", strs[i % strs.length]);
        Edge e = v.addEdge("knows", previous == null ? v : previous,
                "name", strs[i % strs.length], "text", strs[i % strs.length]);
        VertexProperty p = v.property("uid", "v" + i,
                "name", strs[i % strs.length], "text", strs[i % strs.length]);
        previous = v;
    }
}
 
Example #24
Source Project: tinkerpop   Author: apache   File: IoTest.java    License: Apache License 2.0 5 votes vote down vote up
private static void assertWeightLoosely(final float expected, final Edge e) {
    try {
        assertEquals(expected, e.value("weight"), 0.0001f);
    } catch (Exception ex) {
        // for graphs that have strong typing via schema it is possible that a value that came across as graphson
        // with lossiness will end up having a value expected to float to be coerced to double by the underlying
        // graph.
        logger.warn("Attempting to assert weight as double for {} - if your graph is strongly typed from schema this is likely expected", e);
        assertEquals(new Float(expected).doubleValue(), e.value("weight"), 0.0001d);
    }
}
 
Example #25
Source Project: sqlg   Author: pietermartin   File: TestIoEdge.java    License: MIT License 5 votes vote down vote up
@Test
public void shouldReadWriteEdge() throws Exception {
    final Vertex v1 = this.sqlgGraph.addVertex(T.label, "person");
    final Vertex v2 = this.sqlgGraph.addVertex(T.label, "person");
    final Edge e = v1.addEdge("friend", v2, "weight", 0.5d, "acl", "rw");

    assertEdge(v1, v2, e, true);
}
 
Example #26
Source Project: tinkerpop   Author: apache   File: VertexTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
@LoadGraphWith(MODERN)
public void g_EX11AsStringX() {
    final Object edgeId = convertToEdgeId("josh", "created", "lop");
    final Traversal<Edge, Edge> traversal = get_g_EX11X(edgeId.toString());
    assert_g_EX11X(edgeId, traversal);
}
 
Example #27
Source Project: sqlg   Author: pietermartin   File: TestTopology.java    License: MIT License 5 votes vote down vote up
@Test
public void testRollback() {
    loadModern();
    final Traversal<Vertex, Edge> traversal = this.sqlgGraph.traversal().V().aggregate("x").as("a").select("x").unfold().addE("existsWith").to("a").property("time", "now");
    IteratorUtils.asList(traversal);
    this.sqlgGraph.tx().rollback();
}
 
Example #28
Source Project: egeria   Author: odpi   File: GraphOMRSRelationshipMapper.java    License: Apache License 2.0 5 votes vote down vote up
private Object getEdgeProperty(Edge edge, String propName)
{
    Property ep = edge.property(propName);
    if (ep == null || !ep.isPresent())
        return null;
    else
        return ep.value();
}
 
Example #29
Source Project: sqlg   Author: pietermartin   File: TestArrayProperties.java    License: MIT License 5 votes vote down vote up
@Test
public void testLongPrimitiveArrayProperties() {
    Assume.assumeTrue(this.sqlgGraph.getSqlDialect().supportsLongArrayValues());
    Vertex vertex1 = this.sqlgGraph.addVertex(T.label, "Person", "age", new long[]{1, 2, 3, 4, 5});
    Vertex vertex2 = this.sqlgGraph.addVertex(T.label, "Person", "age", new long[]{1, 2, 3, 4, 5});
    vertex1.addEdge("test", vertex2, "age", new long[]{1, 2, 3, 4, 5});
    this.sqlgGraph.tx().commit();
    Vertex v = this.sqlgGraph.traversal().V().next();
    assertTrue(Arrays.equals(new long[]{1, 2, 3, 4, 5}, (long[]) v.property("age").value()));
    Edge e = this.sqlgGraph.traversal().E().next();
    assertTrue(Arrays.equals(new long[]{1, 2, 3, 4, 5}, (long[]) e.property("age").value()));
}
 
Example #30
Source Project: atlas   Author: apache   File: AtlasJanusVertex.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Iterable<AtlasEdge<AtlasJanusVertex, AtlasJanusEdge>> getEdges(AtlasEdgeDirection dir, String[] edgeLabels) {
    Direction      direction = AtlasJanusObjectFactory.createDirection(dir);
    Iterator<Edge> edges     = getWrappedElement().edges(direction, edgeLabels);

    return graph.wrapEdges(edges);
}