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

The following are top voted examples for showing how to use org.apache.tinkerpop.gremlin.structure.Vertex. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: tinkergraph-gremlin   File: TinkerGraphCountStrategyTest.java   View source code 7 votes vote down vote up
@Parameterized.Parameters(name = "{0}")
public static Iterable<Object[]> generateTestParameters() {
    return Arrays.asList(new Object[][]{
            {__.V().count(), countStep(Vertex.class), Collections.emptyList()},
            {__.V().count(), countStep(Vertex.class), TraversalStrategies.GlobalCache.getStrategies(TinkerGraph.class).toList()},
            {__.V().as("a").count(), countStep(Vertex.class), TraversalStrategies.GlobalCache.getStrategies(TinkerGraph.class).toList()},
            {__.V().count().as("a"), countStep(Vertex.class), TraversalStrategies.GlobalCache.getStrategies(TinkerGraph.class).toList()},
            {__.V().map(out()).count().as("a"), countStep(Vertex.class), TraversalStrategies.GlobalCache.getStrategies(TinkerGraph.class).toList()},
            {__.V().map(out()).identity().count().as("a"), countStep(Vertex.class), TraversalStrategies.GlobalCache.getStrategies(TinkerGraph.class).toList()},
            {__.V().map(out().groupCount()).identity().count().as("a"), countStep(Vertex.class), TraversalStrategies.GlobalCache.getStrategies(TinkerGraph.class).toList()},
            {__.V().label().map(s -> s.get().length()).count(), countStep(Vertex.class), TraversalStrategies.GlobalCache.getStrategies(TinkerGraph.class).toList()},
            {__.V().as("a").map(select("a")).count(), countStep(Vertex.class),TraversalStrategies.GlobalCache.getStrategies(TinkerGraph.class).toList()},
            //
            {__.V(), __.V(), Collections.emptyList()},
            {__.V().out().count(), __.V().out().count(), Collections.emptyList()},
            {__.V(1).count(), __.V(1).count(), Collections.emptyList()},
            {__.count(), __.count(), Collections.emptyList()},
            {__.V().map(out().groupCount("m")).identity().count().as("a"), __.V().map(out().groupCount("m")).identity().count().as("a"), Collections.emptyList()},
    });
}
 
Example 2
Project: janusgraph_tutorial   File: LoadData.java   View source code 6 votes vote down vote up
/**
 * The main code basically instantiate its own class and call individual methods.
 * @param argv
 */
public static void main(String[] argv) {
  LoadData loader = new LoadData(Schema.CONFIG_FILE);

  Vertex users[] = loader.generateUsers(1000);
  loader.commit();
  for(Vertex user: users) {
    LOGGER.info("User {} comments:", user.value(Schema.USER_NAME).toString());
    for(Vertex update: loader.generateStatusUpdates(user, 1000)) {
      LOGGER.info("     -> {}", update.value(Schema.CONTENT).toString());
    }
    loader.commit();

    LOGGER.info("User {} follows:", user.value(Schema.USER_NAME).toString());
    for(Vertex followedUser: loader.generateFollows(user, users, 50)) {
      LOGGER.info("     -> {}", followedUser.value(Schema.USER_NAME).toString());
    }
    loader.commit();
  }

  loader.close();
}
 
Example 3
Project: tinkergraph-gremlin   File: TinkerGraphGraphSONSerializerV2d0Test.java   View source code 6 votes vote down vote up
/**
 * Asserts the approximateGraphsChecks function fails when expected. Edge props.
 */
@Test
public void shouldLoseTypesWithGraphSONNoTypesForEdgeProps() throws IOException {
    final GraphWriter writer = getWriter(noTypesMapperV2d0);
    final GraphReader reader = getReader(noTypesMapperV2d0);
    final Graph sampleGraph1 = TinkerFactory.createModern();

    final Vertex v1 = sampleGraph1.addVertex(T.id, 100, "name", "kevin");
    v1.addEdge("hello", sampleGraph1.traversal().V().has("name", "marko").next(), T.id, 101,
            "uuid", UUID.randomUUID());
    try (final ByteArrayOutputStream out = new ByteArrayOutputStream()) {
        writer.writeGraph(out, sampleGraph1);
        final String json = out.toString();
        final TinkerGraph read = TinkerGraph.open();
        reader.readGraph(new ByteArrayInputStream(json.getBytes()), read);
        // Should fail on deserialized edge prop.
        assertFalse(approximateGraphsCheck(sampleGraph1, read));
    }
}
 
Example 4
Project: janusgraph_tutorial   File: QueryRunner.java   View source code 6 votes vote down vote up
public void printTimeline(GraphTraversal<Vertex, Map<String, Map<String, Object>>> traversal) {
  int count = 0;
  resetTimer();
  while (traversal.hasNext()) {
    Map<String, Map<String, Object>> item = traversal.next();
    Vertex user = (Vertex) item.get(userVertex);
    Edge posts = (Edge) item.get(postsEdge);
    Vertex statusUpdate = (Vertex) item.get(statusUpdateVertex);
    LOGGER.info(
        " {}: @{} {}: {}",
        count++,
        user.value(USER_NAME),
        formatTimestamp(posts.value(CREATED_AT)),
        statusUpdate.value(CONTENT)
    );
  }

  LOGGER.info("Printed {} element(s) in {}ms", count, duration());
}
 
Example 5
Project: janusgraph_tutorial   File: HadoopQueryRunner.java   View source code 6 votes vote down vote up
public GraphTraversal<Vertex, Map<String, Map<String,Object>>> getTimeline3(int limit){
  return getUser().
      aggregate("users").
      local(
          __.outE(FOLLOWS).
              has(CreateWeightIndex.WEIGHT).
              order().by(CreateWeightIndex.WEIGHT, decr).
              dedup().
              limit(50).
              inV()
      ).
      aggregate("users").
      cap("users").
      unfold().
      as(userVertex).
      outE(POSTS).
      dedup().
      as(postsEdge).
      order().by(CREATED_AT, decr).
      limit(limit).
      inV().
      as(statusUpdateVertex).
      select(userVertex, postsEdge, statusUpdateVertex);
}
 
Example 6
Project: janusgraph_tutorial   File: QueryRunner.java   View source code 6 votes vote down vote up
public GraphTraversal<Vertex, Map<String, Map<String,Object>>> getTimeline2(int limit){
  return getUser().
      aggregate("users").
      out(FOLLOWS).
      aggregate("users").
      cap("users").
      unfold().
      as(userVertex).
      outE(POSTS).
      as(postsEdge).
      order().by(CREATED_AT, decr).
      limit(limit).
      inV().
      as(statusUpdateVertex).
      select(userVertex, postsEdge, statusUpdateVertex);
}
 
Example 7
Project: keti   File: GraphGenericRepository.java   View source code 6 votes vote down vote up
/**
 * Returns the entity with attributes only on the requested vertex. No parent attributes are included.
 */
public E getEntity(final ZoneEntity zone, final String identifier) {
    try {
        GraphTraversal<Vertex, Vertex> traversal = this.graphTraversal.V().has(ZONE_ID_KEY, zone.getName())
                .has(getEntityIdKey(), identifier);
        if (!traversal.hasNext()) {
            return null;
        }
        Vertex vertex = traversal.next();
        E entity = vertexToEntity(vertex);

        // There should be only one entity with a given entity id.
        Assert.isTrue(!traversal.hasNext(),
                String.format("There are two entities with the same %s.", getEntityIdKey()));
        return entity;
    } finally {
        this.graphTraversal.tx().commit();
    }
}
 
Example 8
Project: keti   File: GraphResourceRepositoryTest.java   View source code 6 votes vote down vote up
@Test(threadPoolSize = CONCURRENT_TEST_THREAD_COUNT,
        invocationCount = CONCURRENT_TEST_INVOCATIONS)
public void testUpdateAttachedEntity() {
    ResourceEntity resourceEntity = persistRandomResourcetoZone1AndAssert();
    String resourceId = resourceEntity.getResourceIdentifier();

    GraphTraversalSource g = this.graphTraversalSource;
    GraphTraversal<Vertex, Vertex> traversal = g.V().has(RESOURCE_ID_KEY, resourceId);
    assertThat(traversal.hasNext(), equalTo(true));
    assertThat(traversal.next().property(RESOURCE_ID_KEY).value(), equalTo(resourceId));

    // Update the resource.
    String updateJSON = "{\'status':'test'}";
    resourceEntity.setAttributesAsJson(updateJSON);
    saveWithRetry(this.resourceRepository, resourceEntity, 3);
    assertThat(this.resourceRepository.getEntity(TEST_ZONE_1, resourceEntity.getResourceIdentifier())
            .getAttributesAsJson(), equalTo(updateJSON));
    this.resourceRepository.delete(resourceEntity);
}
 
Example 9
Project: debattons   File: UserService.java   View source code 6 votes vote down vote up
public User create(User user) throws Exception {
  // Must first create the person and then create its wishList
  String password = user.getPassword();
  if (StringUtils.isNotBlank(password)) {
    final byte[] salt = new byte[SALT_LENGTH];
    final byte[] passwordHash = createSaltThenComputePasswordHash(salt, password);

    return graphUtils.doInGraphTransaction(graph -> {
      Vertex reactionVertex = graph.addVertex(
        T.label, "User",
        "login", user.getLogin(),
        "email", user.getEmail(),
        "passwordHash", passwordHash,
        "salt", salt,
        "creationDate", new Date());
      graphUtils.getRoot(graph).addEdge("created", reactionVertex);
      user.setId(graphUtils.getStringVertexId(reactionVertex, graph));
      return user;
    });
  } else {
    throw new IllegalArgumentException("The given user must define a password");
  }
}
 
Example 10
Project: tinkergraph-gremlin   File: TinkerGraphTest.java   View source code 6 votes vote down vote up
private static void generate(final Graph graph) {
    final int size = 100;
    final List<Object> ids = new ArrayList<>();
    final Vertex v = graph.addVertex("sin", 0.0f, "cos", 1.0f, "ii", 0f);
    ids.add(v.id());

    final GraphTraversalSource g = graph.traversal();

    final Random rand = new Random();
    for (int ii = 1; ii < size; ii++) {
        final Vertex t = graph.addVertex("ii", ii, "sin", Math.sin(ii / 5.0f), "cos", Math.cos(ii / 5.0f));
        final Vertex u = g.V(ids.get(rand.nextInt(ids.size()))).next();
        t.addEdge("linked", u);
        ids.add(u.id());
        ids.add(v.id());
    }
}
 
Example 11
Project: tinkergraph-gremlin   File: TinkerGraphTest.java   View source code 6 votes vote down vote up
@Test(expected = IllegalStateException.class)
public void shouldNotAddEdgeToAVertexThatWasRemoved() {
    final TinkerGraph graph = TinkerGraph.open();
    final Vertex v = graph.addVertex();
    v.property("name", "stephen");

    assertEquals("stephen", v.value("name"));
    v.remove();
    v.addEdge("self", v);
}
 
Example 12
Project: tinkergraph-gremlin   File: TinkerGraph.java   View source code 6 votes vote down vote up
/**
 * An empty private constructor that initializes {@link TinkerGraph}.
 */
private TinkerGraph(final Configuration configuration, boolean usesSpecializedElements) {
    this.configuration = configuration;
    this.usesSpecializedElements = usesSpecializedElements;
    vertexIdManager = selectIdManager(configuration, GREMLIN_TINKERGRAPH_VERTEX_ID_MANAGER, Vertex.class);
    edgeIdManager = selectIdManager(configuration, GREMLIN_TINKERGRAPH_EDGE_ID_MANAGER, Edge.class);
    vertexPropertyIdManager = selectIdManager(configuration, GREMLIN_TINKERGRAPH_VERTEX_PROPERTY_ID_MANAGER, VertexProperty.class);
    defaultVertexPropertyCardinality = VertexProperty.Cardinality.valueOf(
            configuration.getString(GREMLIN_TINKERGRAPH_DEFAULT_VERTEX_PROPERTY_CARDINALITY, VertexProperty.Cardinality.single.name()));

    graphLocation = configuration.getString(GREMLIN_TINKERGRAPH_GRAPH_LOCATION, null);
    graphFormat = configuration.getString(GREMLIN_TINKERGRAPH_GRAPH_FORMAT, null);

    if ((graphLocation != null && null == graphFormat) || (null == graphLocation && graphFormat != null))
        throw new IllegalStateException(String.format("The %s and %s must both be specified if either is present",
                GREMLIN_TINKERGRAPH_GRAPH_LOCATION, GREMLIN_TINKERGRAPH_GRAPH_FORMAT));

    if (graphLocation != null) loadGraph();
}
 
Example 13
Project: tinkergraph-gremlin   File: TinkerGraph.java   View source code 6 votes vote down vote up
private <T extends Element> Iterator<T> createElementIterator(final Class<T> clazz, final Map<Object, T> elements,
                                                              final IdManager idManager,
                                                              final Object... ids) {
    final Iterator<T> iterator;
    if (0 == ids.length) {
        iterator = elements.values().iterator();
    } else {
        final List<Object> idList = Arrays.asList(ids);
        validateHomogenousIds(idList);

        // if the type is of Element - have to look each up because it might be an Attachable instance or
        // other implementation. the assumption is that id conversion is not required for detached
        // stuff - doesn't seem likely someone would detach a Titan vertex then try to expect that
        // vertex to be findable in OrientDB
        return clazz.isAssignableFrom(ids[0].getClass()) ?
                IteratorUtils.filter(IteratorUtils.map(idList, id -> elements.get(clazz.cast(id).id())).iterator(), Objects::nonNull)
                : IteratorUtils.filter(IteratorUtils.map(idList, id -> elements.get(idManager.convert(id))).iterator(), Objects::nonNull);
    }
    return TinkerHelper.inComputerMode(this) ?
            (Iterator<T>) (clazz.equals(Vertex.class) ?
                    IteratorUtils.filter((Iterator<Vertex>) iterator, t -> this.graphComputerView.legalVertex(t)) :
                    IteratorUtils.filter((Iterator<Edge>) iterator, t -> this.graphComputerView.legalEdge(t.outVertex(), t))) :
            iterator;
}
 
Example 14
Project: hdt-gremlin   File: HDTtoGremlin.java   View source code 6 votes vote down vote up
public static void smallTest(Graph graph) {
	Iterator<Vertex> it = graph.vertices();
	int i=0;
	while(i<100 && it.hasNext()) {
		Vertex v = it.next();
		System.out.println(v.id()+"/"+v.property("node"));
		i++;

	}
	
	// Iterate over Edges
	Iterator<Edge> it2 = graph.edges();
	i=0;
	while(i<100 && it2.hasNext()) {
		Edge e = it2.next();
		System.out.println(e);
		i++;
	}
}
 
Example 15
Project: tinkergraph-gremlin   File: TinkerIoRegistryV3d0.java   View source code 6 votes vote down vote up
@Override
public TinkerGraph deserialize(final JsonParser jsonParser, final DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
    final Configuration conf = new BaseConfiguration();
    conf.setProperty("gremlin.tinkergraph.defaultVertexPropertyCardinality", "list");
    final TinkerGraph graph = TinkerGraph.open(conf);

    while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
        if (jsonParser.getCurrentName().equals("vertices")) {
            while (jsonParser.nextToken() != JsonToken.END_ARRAY) {
                if (jsonParser.currentToken() == JsonToken.START_OBJECT) {
                    final DetachedVertex v = (DetachedVertex) deserializationContext.readValue(jsonParser, Vertex.class);
                    v.attach(Attachable.Method.getOrCreate(graph));
                }
            }
        } else if (jsonParser.getCurrentName().equals("edges")) {
            while (jsonParser.nextToken() != JsonToken.END_ARRAY) {
                if (jsonParser.currentToken() == JsonToken.START_OBJECT) {
                    final DetachedEdge e = (DetachedEdge) deserializationContext.readValue(jsonParser, Edge.class);
                    e.attach(Attachable.Method.getOrCreate(graph));
                }
            }
        }
    }

    return graph;
}
 
Example 16
Project: tinkergraph-gremlin   File: TinkerGraphTest.java   View source code 6 votes vote down vote up
@Override
public void write(final Kryo kryo, final Output output, final Color color) {
    final TinkerGraph graph = TinkerGraph.open();
    final Vertex v = graph.addVertex(T.id, 1, T.label, "color", "name", color.toString());
    final Vertex vRed = graph.addVertex(T.id, 2, T.label, "primary", "name", "red");
    final Vertex vGreen = graph.addVertex(T.id, 3, T.label, "primary", "name", "green");
    final Vertex vBlue = graph.addVertex(T.id, 4, T.label, "primary", "name", "blue");

    v.addEdge("hasComponent", vRed, "amount", color.getRed());
    v.addEdge("hasComponent", vGreen, "amount", color.getGreen());
    v.addEdge("hasComponent", vBlue, "amount", color.getBlue());

    // make some junk so the graph is kinda big
    generate(graph);

    try (final ByteArrayOutputStream stream = new ByteArrayOutputStream()) {
        GryoWriter.build().mapper(() -> kryo).create().writeGraph(stream, graph);
        final byte[] bytes = stream.toByteArray();
        output.writeInt(bytes.length);
        output.write(bytes);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
 
Example 17
Project: tinkergraph-gremlin   File: TinkerIoRegistryV2d0.java   View source code 6 votes vote down vote up
@Override
public TinkerGraph deserialize(final JsonParser jsonParser, final DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
    final Configuration conf = new BaseConfiguration();
    conf.setProperty("gremlin.tinkergraph.defaultVertexPropertyCardinality", "list");
    final TinkerGraph graph = TinkerGraph.open(conf);

    while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
        if (jsonParser.getCurrentName().equals("vertices")) {
            while (jsonParser.nextToken() != JsonToken.END_ARRAY) {
                if (jsonParser.currentToken() == JsonToken.START_OBJECT) {
                    final DetachedVertex v = (DetachedVertex) deserializationContext.readValue(jsonParser, Vertex.class);
                    v.attach(Attachable.Method.getOrCreate(graph));
                }
            }
        } else if (jsonParser.getCurrentName().equals("edges")) {
            while (jsonParser.nextToken() != JsonToken.END_ARRAY) {
                if (jsonParser.currentToken() == JsonToken.START_OBJECT) {
                    final DetachedEdge e = (DetachedEdge) deserializationContext.readValue(jsonParser, Edge.class);
                    e.attach(Attachable.Method.getOrCreate(graph));
                }
            }
        }
    }

    return graph;
}
 
Example 18
Project: tinkergraph-gremlin   File: TinkerMessenger.java   View source code 5 votes vote down vote up
@Override
    public Iterator<M> receiveMessages() {
        final MultiIterator<M> multiIterator = new MultiIterator<>();
        for (final MessageScope messageScope : this.messageBoard.receiveMessages.keySet()) {
//        for (final MessageScope messageScope : this.messageBoard.previousMessageScopes) {
            if (messageScope instanceof MessageScope.Local) {
                final MessageScope.Local<M> localMessageScope = (MessageScope.Local<M>) messageScope;
                final Traversal.Admin<Vertex, Edge> incidentTraversal = TinkerMessenger.setVertexStart(localMessageScope.getIncidentTraversal().get().asAdmin(), this.vertex);
                final Direction direction = TinkerMessenger.getDirection(incidentTraversal);
                final Edge[] edge = new Edge[1]; // simulates storage side-effects available in Gremlin, but not Java8 streams
                multiIterator.addIterator(StreamSupport.stream(Spliterators.spliteratorUnknownSize(VertexProgramHelper.reverse(incidentTraversal.asAdmin()), Spliterator.IMMUTABLE | Spliterator.SIZED), false)
                        .map(e -> this.messageBoard.receiveMessages.get(messageScope).get((edge[0] = e).vertices(direction).next()))
                        .filter(q -> null != q)
                        .flatMap(Queue::stream)
                        .map(message -> localMessageScope.getEdgeFunction().apply(message, edge[0]))
                        .iterator());

            } else {
                multiIterator.addIterator(Stream.of(this.vertex)
                        .map(this.messageBoard.receiveMessages.get(messageScope)::get)
                        .filter(q -> null != q)
                        .flatMap(Queue::stream)
                        .iterator());
            }
        }
        return multiIterator;
    }
 
Example 19
Project: graphsail   File: DataStore.java   View source code 5 votes vote down vote up
boolean edgeExists(final Vertex outV, final Vertex inV, final String label, final String context) {
    Iterator<Edge> edges = outV.edges(Direction.OUT, label);
    while (edges.hasNext()) {
        Edge next = edges.next();
        if (!next.inVertex().equals(inV)) continue;
        if (contextEquals(context, next)) {
            return true;
        }
    }
    return false;
}
 
Example 20
Project: janusgraph_tutorial   File: Schema.java   View source code 5 votes vote down vote up
/**
 * Create the user schema - vertex label, property and index.
 */
private void createUserSchema(){
  LOGGER.info("Create {} schema", USER);
  VertexLabel user = mgt.makeVertexLabel(USER).make();
  PropertyKey userName = mgt.makePropertyKey(USER_NAME).dataType(String.class).make();

  mgt.buildIndex(indexName(USER, USER_NAME), Vertex.class).
      addKey(userName, Mapping.STRING.asParameter()).
      indexOnly(user).
      buildMixedIndex(BACKING_INDEX);
}
 
Example 21
Project: act-platform   File: FactEdgeTest.java   View source code 5 votes vote down vote up
@Test
public void testVerticesWithDirectionBoth() {
  UUID factID = mockFact(null);
  UUID inVertexObjectID = mockObject();
  UUID outVertexObjectID = mockObject();
  Edge edge = new FactEdge(getActGraph(), factID, inVertexObjectID, outVertexObjectID);

  Iterator<Vertex> vertices = edge.vertices(Direction.BOTH);
  assertSame(outVertexObjectID, vertices.next().id());
  assertSame(inVertexObjectID, vertices.next().id());
  assertFalse(vertices.hasNext());
}
 
Example 22
Project: graphsail   File: DataStore.java   View source code 5 votes vote down vote up
private Value toValue(final Vertex vertex) {
    Schema.VertexLabel kind = Schema.VertexLabel.valueOf(vertex.label());
    switch (kind) {
        case IRI:
            return toIRI(vertex);
        case BNode:
            return toBNode(vertex);
        case Literal:
            return toLiteral(vertex);
        default:
            throw new IllegalStateException();
    }
}
 
Example 23
Project: hdt-gremlin   File: HDTGraph.java   View source code 5 votes vote down vote up
public Vertex getVertex(Object id) {
	if(id instanceof String) {
		return getVertexStr((String)id);
	} else if(id instanceof HDTVertex) {
		return (Vertex) id;
	} else {
		int intId = -1;
		if(id instanceof Integer){
			intId = ((Integer) id).intValue();
		}
		
		if(id instanceof Long) {
			intId = ((Long) id).intValue();
		}
		
		if(intId==-1){
			return null;
		}
	
		// Note: When using numeric ids, we assume the following consecutive order: SHARED|SUBJECTS|OBJECTS
		if(intId<=getTotalSubjects()) {
			return new HDTVertex(this, TripleComponentRole.SUBJECT, intId);
		} else {
			// Translate absolute object id to local object id
			return new HDTVertex(this, TripleComponentRole.OBJECT, (int)(intId-getNSubjects()));
		}
	}
}
 
Example 24
Project: graphsail   File: DataStore.java   View source code 5 votes vote down vote up
private Vertex createNewLiteralVertex(final Value value) {
    Vertex vertex = createVertex(Schema.VertexLabel.Literal.name(), value);
    IRI datatype = ((Literal) value).getDatatype();
    vertex.property(Schema.VertexProperties.DATATYPE, datatype.stringValue());
    if (datatype.equals(RDF.LANGSTRING)) {
        vertex.property(Schema.VertexProperties.LANGUAGE, ((Literal) value).getLanguage().get());
    }
    return vertex;
}
 
Example 25
Project: act-platform   File: ActGraphTest.java   View source code 5 votes vote down vote up
@Test
public void testIterateVerticesWithUuidIdSupportUsingReferenceVertex() {
  Vertex vertex1 = createVertex();
  Vertex vertex2 = getActGraph().vertices(ReferenceFactory.detach(vertex1)).next();
  assertEquals(vertex1.id(), vertex2.id());
  assertFalse(vertex2 instanceof ReferenceVertex);
}
 
Example 26
Project: janusgraph_tutorial   File: LoadData.java   View source code 5 votes vote down vote up
private Vertex[] generateFollows(Vertex forUser, Vertex[] users, int count){
  Vertex[] followedUsers = new Vertex[count];

  for(int i = 0; i < count; i++) {
    followedUsers[i] = users[faker.number().numberBetween(0, users.length - 1)];
    Edge follows = forUser.addEdge(Schema.FOLLOWS, followedUsers[i], Schema.CREATED_AT, getTimestamp());
  }
  return followedUsers;
}
 
Example 27
Project: act-platform   File: ObjectVertexTest.java   View source code 5 votes vote down vote up
@Test
public void testCreateVertexFromObject() {
  UUID objectID = mockObject();
  Vertex vertex = new ObjectVertex(getActGraph(), objectID);
  assertEquals(objectID, vertex.id());
  assertEquals("type", vertex.label());
  assertSame(getActGraph(), vertex.graph());
}
 
Example 28
Project: janusgraph_tutorial   File: CreateSupernodes.java   View source code 5 votes vote down vote up
private Vertex[] generateFollows(Vertex forUser, Vertex[] users, int count){
  Vertex[] followedUsers = new Vertex[count];

  for(int i = 0; i < count; i++) {
    followedUsers[i] = users[faker.number().numberBetween(0, users.length - 1)];
    Edge follows = forUser.addEdge(Schema.FOLLOWS, followedUsers[i], Schema.CREATED_AT, getTimestamp());
  }
  return followedUsers;
}
 
Example 29
Project: janusgraph_tutorial   File: ComputeWeightVertexProgram.java   View source code 5 votes vote down vote up
/**
 * Execute this marvelous code, going from the Content to Users.
 *
 * Internally uses the RecommendationForNewUser class to build the recommendation as we want, pretty and
 * simple.
 *
 * @param vertex
 * @param messenger
 * @param memory
 */
@Override
public void execute(Vertex vertex, Messenger<Tuple> messenger, Memory memory) {
  try {
    HadoopQueryRunner runner = new HadoopQueryRunner(g, vertex.value(Schema.USER_NAME));
    GraphTraversal<Vertex, Edge> t = g.V(vertex.id()).inE(Schema.FOLLOWS);

    while(t.hasNext()) {
      Edge followsEdge = t.next();

      long commonFollowedUsers = runner.countCommonFollowedUsers(followsEdge.outVertex());
      long postsPerDaySince = runner.countPostsPerDaySince(sevenDaysAgo);
      long weight = (3 * commonFollowedUsers + postsPerDaySince) / 4;
      if(min == -10 || min > weight) {
        min = (int) weight;
      }
      if(max < weight) {
        max = (int) weight;
      }
      count++;

      followsEdge.property(CreateWeightIndex.WEIGHT, weight);
    }
  } catch (Exception e){
    e.printStackTrace();
    LOGGER.error("while processing " + vertex.id() + ": " + e.getClass().toString() + "(" + e.getMessage() + ")");
    return;
  }
}
 
Example 30
Project: act-platform   File: ObjectVertexTest.java   View source code 5 votes vote down vote up
@Test
public void testEdgesWithDirectionNone() {
  UUID objectID = mockObjectWithFact(Direction.None);
  Vertex vertex = new ObjectVertex(getActGraph(), objectID);

  assertTrue(vertex.edges(BOTH).hasNext());
  assertTrue(vertex.edges(IN).hasNext());
  assertTrue(vertex.edges(OUT).hasNext());
}
 
Example 31
Project: act-platform   File: ObjectVertexTest.java   View source code 5 votes vote down vote up
@Test
public void testEdgesFilterByLabel() {
  UUID objectID = mockObjectWithFact(Direction.BiDirectional);
  Vertex vertex = new ObjectVertex(getActGraph(), objectID);

  assertTrue(vertex.edges(BOTH, "type").hasNext());
  assertFalse(vertex.edges(BOTH, "something").hasNext());
}
 
Example 32
Project: act-platform   File: ObjectVertexTest.java   View source code 5 votes vote down vote up
@Test
public void testVerticesWithDirectionBiDirectional() {
  UUID objectID = mockObjectWithFact(Direction.BiDirectional);
  Vertex vertex = new ObjectVertex(getActGraph(), objectID);

  assertTrue(vertex.vertices(BOTH).hasNext());
  assertTrue(vertex.vertices(IN).hasNext());
  assertTrue(vertex.vertices(OUT).hasNext());
}
 
Example 33
Project: tinkergraph-gremlin   File: TinkerGraphGraphSONSerializerV2d0Test.java   View source code 5 votes vote down vote up
/**
 * Those kinds of types are declared differently in the GraphSON type deserializer, check that all are handled
 * properly.
 */
@Test
public void shouldKeepTypesWhenDeserializingSerializedTinkerGraph() throws IOException {
    final TinkerGraph tg = TinkerGraph.open();

    final Vertex v = tg.addVertex("vertexTest");
    final UUID uuidProp = UUID.randomUUID();
    final Duration durationProp = Duration.ofHours(3);
    final Long longProp = 2L;
    final ByteBuffer byteBufferProp = ByteBuffer.wrap("testbb".getBytes());
    final InetAddress inetAddressProp = InetAddress.getByName("10.10.10.10");

    // One Java util type natively supported by Jackson
    v.property("uuid", uuidProp);
    // One custom time type added by the GraphSON module
    v.property("duration", durationProp);
    // One Java native type not handled by JSON natively
    v.property("long", longProp);
    // One Java util type added by GraphSON
    v.property("bytebuffer", byteBufferProp);
    v.property("inetaddress", inetAddressProp);


    final GraphWriter writer = getWriter(defaultMapperV2d0);
    final GraphReader reader = getReader(defaultMapperV2d0);
    try (final ByteArrayOutputStream out = new ByteArrayOutputStream()) {
        writer.writeGraph(out, tg);
        final String json = out.toString();
        final TinkerGraph read = TinkerGraph.open();
        reader.readGraph(new ByteArrayInputStream(json.getBytes()), read);
        final Vertex vRead = read.traversal().V().hasLabel("vertexTest").next();
        assertEquals(vRead.property("uuid").value(), uuidProp);
        assertEquals(vRead.property("duration").value(), durationProp);
        assertEquals(vRead.property("long").value(), longProp);
        assertEquals(vRead.property("bytebuffer").value(), byteBufferProp);
        assertEquals(vRead.property("inetaddress").value(), inetAddressProp);
    }
}
 
Example 34
Project: keti   File: GraphGenericRepository.java   View source code 5 votes vote down vote up
@Override
public boolean exists(final Long id) {
    try {
        GraphTraversal<Vertex, Vertex> traversal = this.graphTraversal.V(id);
        return traversal.hasNext();
    } finally {
        this.graphTraversal.tx().commit();
    }
}
 
Example 35
Project: keti   File: GraphConfig.java   View source code 5 votes vote down vote up
public static void createUniqueIndexForLabel(final Graph newGraph, final String indexName, final String indexKey,
        final String label) throws InterruptedException {
    newGraph.tx().rollback(); // Never create new indexes while a transaction is active
    TitanManagement mgmt = ((TitanGraph) newGraph).openManagement();
    if (!mgmt.containsGraphIndex(indexName)) {
        PropertyKey indexPropertyKey = mgmt.makePropertyKey(indexKey).dataType(Integer.class).make();
        VertexLabel versionLabel = mgmt.makeVertexLabel(label).make();
        // Create a unique composite index for the property key that indexes only vertices with a given label
        mgmt.buildIndex(indexName, Vertex.class).addKey(indexPropertyKey).indexOnly(versionLabel).unique()
                .buildCompositeIndex();
    }
    mgmt.commit();
    // Wait for the index to become available
    ManagementSystem.awaitGraphIndexStatus((TitanGraph) newGraph, indexName).status(SchemaStatus.ENABLED).call();
}
 
Example 36
Project: bitsy   File: BitsyTransaction.java   View source code 5 votes vote down vote up
public Vertex getVertex(UUID id) throws BitsyException {
    // Only work on live transactions
    checkIfActive();
    
    // 1. Check if this vertex is defined in this transaction
    BitsyVertex ans = context.changedVertices.get(id);
    if (ans == null) {
        ans = context.unmodifiedVertices.get(id);
    }
    
    if (ans != null) {
        // A deleted vertex must not be returned
        if (isDeleted(ans)) {
            return null;
        } else {
            return ans;
        }
    }

    // 2. Get an unmodified vertex tied to this transaction
    ans = context.store.getBitsyVertex(this, id);
    if (ans != null) {
        // 3. Keep a reference if the isolation level is repeatable read
        if (isolationLevel == BitsyIsolationLevel.REPEATABLE_READ) {
            context.unmodifiedVertices.put((UUID)(ans.id()), ans);
        }
    }
    
    return ans;
}
 
Example 37
Project: tinkergraph-gremlin   File: TinkerGraphTest.java   View source code 5 votes vote down vote up
@Test
public void shouldCloneTinkergraph() {
    final TinkerGraph original = TinkerGraph.open();
    final TinkerGraph clone = TinkerGraph.open();

    final Vertex marko = original.addVertex("name", "marko", "age", 29);
    final Vertex stephen = original.addVertex("name", "stephen", "age", 35);
    marko.addEdge("knows", stephen);
    GraphHelper.cloneElements(original, clone);

    final Vertex michael = clone.addVertex("name", "michael");
    michael.addEdge("likes", marko);
    michael.addEdge("likes", stephen);
    clone.traversal().V().property("newProperty", "someValue").toList();
    clone.traversal().E().property("newProperty", "someValue").toList();

    assertEquals("original graph should be unchanged", new Long(2), original.traversal().V().count().next());
    assertEquals("original graph should be unchanged", new Long(1), original.traversal().E().count().next());
    assertEquals("original graph should be unchanged", new Long(0), original.traversal().V().has("newProperty").count().next());

    assertEquals("cloned graph should contain new elements", new Long(3), clone.traversal().V().count().next());
    assertEquals("cloned graph should contain new elements", new Long(3), clone.traversal().E().count().next());
    assertEquals("cloned graph should contain new property", new Long(3), clone.traversal().V().has("newProperty").count().next());
    assertEquals("cloned graph should contain new property", new Long(3), clone.traversal().E().has("newProperty").count().next());

    assertNotSame("cloned elements should reference to different objects",
        original.traversal().V().has("name", "stephen").next(),
        clone.traversal().V().has("name", "stephen").next());
}
 
Example 38
Project: graphsail   File: DataStore.java   View source code 5 votes vote down vote up
private CloseableIteration<? extends Statement, SailException> getObjectStatements(final Value object) {
    // assuming all edges are statements
    Vertex vertex = getVertexByValue(object);
    Iterator<Edge> edges = null == vertex
            ? Collections.emptyIterator()
            : vertex.edges(Direction.IN);
    return toStatements(edges);
}
 
Example 39
Project: janusgraph_tutorial   File: CreateSupernodes.java   View source code 5 votes vote down vote up
private Vertex[] getUsers(int from, int to){
  Vertex[] users = new Vertex[to - from + 1];

  for(int i=from; i <= to; i++){
    users[i-from] = queryRunner.getUser("testUser" + i).next();
  }

  return users;
}
 
Example 40
Project: bitsy   File: BitsyEdge.java   View source code 5 votes vote down vote up
@Override
public Iterator<Vertex> bothVertices() {
    tx.validateForQuery(this);

    Vertex inV = inVertex();
    Vertex outV = outVertex();
    return Arrays.asList(new Vertex[] {outV, inV}).iterator();
}