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

The following are top voted examples for showing how to use org.apache.tinkerpop.gremlin.structure.Graph. 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: keti   File: GraphConfig.java   Source Code and License 8 votes vote down vote up
public Graph createGraph() throws InterruptedException {
    Graph newGraph;
    if (this.cassandraEnabled) {
        Builder titanBuilder = TitanFactory.build().set("storage.backend", "cassandra")
                .set("storage.cassandra.keyspace", this.cassandraKeyspace)
                .set("storage.hostname", Arrays.asList(hostname.split(","))).set("storage.port", this.port)
                .set("cache.db-cache", this.cacheEnabled).set("cache.db-cache-clean-wait", this.titanCacheCleanWait)
                .set("cache.db-cache-time", this.titanCacheTime).set("cache.db-cache-size", this.titanCacheSize);
        if (StringUtils.isNotEmpty(this.username)) {
            titanBuilder = titanBuilder.set("storage.username", this.username);
        }
        if (StringUtils.isNotEmpty(this.password)) {
            titanBuilder = titanBuilder.set("storage.password", this.password);
        }
        newGraph = titanBuilder.open();
    } else {
        newGraph = TitanFactory.build().set("storage.backend", "inmemory").open();
    }
    createSchemaElements(newGraph);
    LOGGER.info("Initialized titan db.");
    return newGraph;
}
 
Example 2
Project: tinkergraph-gremlin   File: TinkerGraphUUIDProvider.java   Source Code and License 7 votes vote down vote up
@Override
public Map<String, Object> getBaseConfiguration(final String graphName, final Class<?> test, final String testMethodName,
                                                final LoadGraphWith.GraphData loadGraphWith) {
    final TinkerGraph.DefaultIdManager idManager = TinkerGraph.DefaultIdManager.UUID;
    final String idMaker = idManager.name();
    return new HashMap<String, Object>() {{
        put(Graph.GRAPH, TinkerGraph.class.getName());
        put(TinkerGraph.GREMLIN_TINKERGRAPH_VERTEX_ID_MANAGER, idMaker);
        put(TinkerGraph.GREMLIN_TINKERGRAPH_EDGE_ID_MANAGER, idMaker);
        put(TinkerGraph.GREMLIN_TINKERGRAPH_VERTEX_PROPERTY_ID_MANAGER, idMaker);
        if (requiresListCardinalityAsDefault(loadGraphWith, test, testMethodName))
            put(TinkerGraph.GREMLIN_TINKERGRAPH_DEFAULT_VERTEX_PROPERTY_CARDINALITY, VertexProperty.Cardinality.list.name());
        if (requiresPersistence(test, testMethodName)) {
            put(TinkerGraph.GREMLIN_TINKERGRAPH_GRAPH_FORMAT, "gryo");
            final File tempDir = TestHelper.makeTestDataPath(test, "temp");
            put(TinkerGraph.GREMLIN_TINKERGRAPH_GRAPH_LOCATION,
                    tempDir.getAbsolutePath() + File.separator + testMethodName + ".kryo");
        }
    }};
}
 
Example 3
Project: tinkergraph-gremlin   File: TinkerGraphProvider.java   Source Code and License 7 votes vote down vote up
@Override
public Map<String, Object> getBaseConfiguration(final String graphName, final Class<?> test, final String testMethodName,
                                                final LoadGraphWith.GraphData loadGraphWith) {
    final TinkerGraph.DefaultIdManager idManager = selectIdMakerFromGraphData(loadGraphWith);
    final String idMaker = (idManager.equals(TinkerGraph.DefaultIdManager.ANY) ? selectIdMakerFromTest(test, testMethodName) : idManager).name();
    return new HashMap<String, Object>() {{
        put(Graph.GRAPH, TinkerGraph.class.getName());
        put(TinkerGraph.GREMLIN_TINKERGRAPH_VERTEX_ID_MANAGER, idMaker);
        put(TinkerGraph.GREMLIN_TINKERGRAPH_EDGE_ID_MANAGER, idMaker);
        put(TinkerGraph.GREMLIN_TINKERGRAPH_VERTEX_PROPERTY_ID_MANAGER, idMaker);
        if (requiresListCardinalityAsDefault(loadGraphWith, test, testMethodName))
            put(TinkerGraph.GREMLIN_TINKERGRAPH_DEFAULT_VERTEX_PROPERTY_CARDINALITY, VertexProperty.Cardinality.list.name());
        if (requiresPersistence(test, testMethodName)) {
            put(TinkerGraph.GREMLIN_TINKERGRAPH_GRAPH_FORMAT, "gryo");
            final File tempDir = TestHelper.makeTestDataPath(test, "temp");
            put(TinkerGraph.GREMLIN_TINKERGRAPH_GRAPH_LOCATION,
                    tempDir.getAbsolutePath() + File.separator + testMethodName + ".kryo");
        }
    }};
}
 
Example 4
Project: LiteGraph   File: TinkerGraphProvider.java   Source Code and License 7 votes vote down vote up
@Override
public Map<String, Object> getBaseConfiguration(final String graphName, final Class<?> test, final String testMethodName,
                                                final LoadGraphWith.GraphData loadGraphWith) {
    final TinkerGraph.DefaultIdManager idManager = selectIdMakerFromGraphData(loadGraphWith);
    final String idMaker = (idManager.equals(TinkerGraph.DefaultIdManager.ANY) ? selectIdMakerFromTest(test, testMethodName) : idManager).name();
    return new HashMap<String, Object>() {{
        put(Graph.GRAPH, TinkerGraph.class.getName());
        put(TinkerGraph.GREMLIN_TINKERGRAPH_VERTEX_ID_MANAGER, idMaker);
        put(TinkerGraph.GREMLIN_TINKERGRAPH_EDGE_ID_MANAGER, idMaker);
        put(TinkerGraph.GREMLIN_TINKERGRAPH_VERTEX_PROPERTY_ID_MANAGER, idMaker);
        if (requiresListCardinalityAsDefault(loadGraphWith, test, testMethodName))
            put(TinkerGraph.GREMLIN_TINKERGRAPH_DEFAULT_VERTEX_PROPERTY_CARDINALITY, VertexProperty.Cardinality.list.name());
        if (requiresPersistence(test, testMethodName)) {
            put(TinkerGraph.GREMLIN_TINKERGRAPH_GRAPH_FORMAT, "gryo");
            final File tempDir = TestHelper.makeTestDataPath(test, "temp");
            put(TinkerGraph.GREMLIN_TINKERGRAPH_GRAPH_LOCATION,
                    tempDir.getAbsolutePath() + File.separator + testMethodName + ".kryo");
        }
    }};
}
 
Example 5
Project: mongodb-gremlin   File: MongoDBTest.java   Source Code and License 6 votes vote down vote up
@Test
public void shouldSupportFindDocuments() throws Exception {
    final Graph graph = TinkerFactory.createModern();
    final GraphTraversalSource g = graph.traversal(GraphTraversalSource.class);
    final MongoDBTraversalSource db = graph.traversal(MongoDBTraversalSource.class);

    // test find(name,marko)
    assertEquals(
            parser.parse("{\"~label\":\"person\",\"created\":{\"~label\":\"software\",\"~id\":3,\"name\":\"lop\",\"lang\":\"java\"}," +
                    "\"~id\":1,\"name\":\"marko\",\"age\":29,\"knows\":[{\"~label\":\"person\",\"~id\":2,\"name\":\"vadas\",\"age\":27}," +
                    "{\"~label\":\"person\",\"created\":{\"~label\":\"software\",\"~id\":5,\"name\":\"ripple\",\"lang\":\"java\"}," +
                    "\"~id\":4,\"name\":\"josh\",\"age\":32},{\"~label\":\"person\",\"created\":{\"~label\":\"software\",\"~id\":3,\"name\":\"lop\",\"lang\":\"java\"}," +
                    "\"~id\":4,\"name\":\"josh\",\"age\":32}]}"),
            parser.parse(db.find("{ \"name\": \"marko\" }").next().toString()));

    compareQueryTraversalSegment(g.V().has("age", P.gt(30)), db.find("{\"age\" : {\"$gt\" : 30}}"));
    compareQueryTraversalSegment(g.V().has("name", "vadas").has("age", 27), db.find("{\"age\" : 27, \"name\":\"vadas\"}"));


}
 
Example 6
Project: tinkergraph-gremlin   File: TinkerHelper.java   Source Code and License 6 votes vote down vote up
protected static Edge addEdge(final TinkerGraph graph, final TinkerVertex outVertex, final TinkerVertex inVertex, final String label, final Object... keyValues) {
    ElementHelper.validateLabel(label);
    ElementHelper.legalPropertyKeyValueArray(keyValues);

    Object idValue = graph.edgeIdManager.convert(ElementHelper.getIdValue(keyValues).orElse(null));

    final Edge edge;
    if (null != idValue) {
        if (graph.edges.containsKey(idValue))
            throw Graph.Exceptions.edgeWithIdAlreadyExists(idValue);
    } else {
        idValue = graph.edgeIdManager.getNextId(graph);
    }

    edge = new TinkerEdge(idValue, outVertex, label, inVertex);
    ElementHelper.attachProperties(edge, keyValues);
    graph.edges.put(edge.id(), edge);
    TinkerHelper.addOutEdge(outVertex, label, edge);
    TinkerHelper.addInEdge(inVertex, label, edge);
    return edge;

}
 
Example 7
Project: tinkergraph-gremlin   File: TinkerIndex.java   Source Code and License 6 votes vote down vote up
public void createKeyIndex(final String key) {
    if (null == key)
        throw Graph.Exceptions.argumentCanNotBeNull("key");
    if (key.isEmpty())
        throw new IllegalArgumentException("The key for the index cannot be an empty string");

    if (this.indexedKeys.contains(key))
        return;
    this.indexedKeys.add(key);

    (Vertex.class.isAssignableFrom(this.indexClass) ?
            this.graph.vertices.values().<T>stream() :
            this.graph.edges.values().<T>stream())
            .map(e -> new Object[]{((T) e).property(key), e})
            .filter(a -> ((Property) a[0]).isPresent())
            .forEach(a -> this.put(key, ((Property) a[0]).value(), (T) a[1]));
}
 
Example 8
Project: tinkergraph-gremlin   File: TinkerGraphGraphSONSerializerV2d0Test.java   Source Code and License 6 votes vote down vote up
/**
 * Thorough types verification for Vertex ids, Vertex props, Edge ids, Edge props
 */
@Test
public void shouldDeserializeGraphSONIntoTinkerGraphKeepingTypes() throws IOException {
    final GraphWriter writer = getWriter(defaultMapperV2d0);
    final GraphReader reader = getReader(defaultMapperV2d0);

    final Graph sampleGraph1 = TinkerFactory.createModern();
    final Vertex v1 = sampleGraph1.addVertex(T.id, 100, "name", "kevin", "theUUID", UUID.randomUUID());
    final Vertex v2 = sampleGraph1.addVertex(T.id, 101L, "name", "henri", "theUUID", UUID.randomUUID());
    v1.addEdge("hello", v2, T.id, 101L,
            "uuid", UUID.randomUUID());

    try (final ByteArrayOutputStream out = new ByteArrayOutputStream()) {
        writer.writeObject(out, sampleGraph1);
        final String json = out.toString();

        final TinkerGraph read = reader.readObject(new ByteArrayInputStream(json.getBytes()), TinkerGraph.class);
        assertTrue(approximateGraphsCheck(sampleGraph1, read));
    }
}
 
Example 9
Project: tinkergraph-gremlin   File: TinkerGraphGraphSONSerializerV2d0Test.java   Source Code and License 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 10
Project: tinkergraph-gremlin   File: TinkerGraphGraphSONSerializerV2d0Test.java   Source Code and License 6 votes vote down vote up
@Test
public void deserializersTestsTinkerGraph() {
    final TinkerGraph tg = TinkerGraph.open();

    final Vertex v = tg.addVertex("vertexTest");
    final Vertex v2 = tg.addVertex("vertexTest");

    v.addEdge("knows", v2);

    final GraphWriter writer = getWriter(defaultMapperV2d0);
    final GraphReader reader = getReader(defaultMapperV2d0);

    try (final ByteArrayOutputStream out = new ByteArrayOutputStream()) {
        writer.writeObject(out, tg);
        final String json = out.toString();

        final Graph gRead = (Graph)reader.readObject(new ByteArrayInputStream(json.getBytes()), Object.class);
        assertTrue(approximateGraphsCheck(tg, gRead));
    } catch (IOException e) {
        e.printStackTrace();
        fail("Should not have thrown exception: " + e.getMessage());
    }
}
 
Example 11
Project: tinkergraph-gremlin   File: TinkerGraphTest.java   Source Code and License 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 12
Project: tinkergraph-gremlin   File: TinkerGraphPlayTest.java   Source Code and License 6 votes vote down vote up
@Test
@Ignore
public void benchmarkStandardTraversals() throws Exception {
    Graph graph = TinkerGraph.open();
    GraphTraversalSource g = graph.traversal();
    graph.io(GraphMLIo.build()).readGraph("data/grateful-dead.xml");
    final List<Supplier<Traversal>> traversals = Arrays.asList(
            () -> g.V().outE().inV().outE().inV().outE().inV(),
            () -> g.V().out().out().out(),
            () -> g.V().out().out().out().path(),
            () -> g.V().repeat(out()).times(2),
            () -> g.V().repeat(out()).times(3),
            () -> g.V().local(out().out().values("name").fold()),
            () -> g.V().out().local(out().out().values("name").fold()),
            () -> g.V().out().map(v -> g.V(v.get()).out().out().values("name").toList())
    );
    traversals.forEach(traversal -> {
        logger.info("\nTESTING: {}", traversal.get());
        for (int i = 0; i < 7; i++) {
            final long t = System.currentTimeMillis();
            traversal.get().iterate();
            System.out.print("   " + (System.currentTimeMillis() - t));
        }
    });
}
 
Example 13
Project: tinkergraph-gremlin   File: TinkerGraphPlayTest.java   Source Code and License 6 votes vote down vote up
@Test
@Ignore
public void testPlay9() throws Exception {
    Graph graph = TinkerGraph.open();
    graph.io(GraphMLIo.build()).readGraph("../data/grateful-dead.xml");

    GraphTraversalSource g = graph.traversal().withComputer(Computer.compute().workers(4)).withStrategies(PathRetractionStrategy.instance());
    GraphTraversalSource h = graph.traversal().withComputer(Computer.compute().workers(4)).withoutStrategies(PathRetractionStrategy.class);

    for (final GraphTraversalSource source : Arrays.asList(g, h)) {
        System.out.println(source.V().match(
                __.as("a").in("sungBy").as("b"),
                __.as("a").in("sungBy").as("c"),
                __.as("b").out("writtenBy").as("d"),
                __.as("c").out("writtenBy").as("e"),
                __.as("d").has("name", "George_Harrison"),
                __.as("e").has("name", "Bob_Marley")).select("a").count().profile().next());
    }
}
 
Example 14
Project: tinkergraph-gremlin   File: TinkerGraphPlayTest.java   Source Code and License 6 votes vote down vote up
@Test
@Ignore
public void testPlay6() throws Exception {
    final Graph graph = TinkerGraph.open();
    final GraphTraversalSource g = graph.traversal();
    for (int i = 0; i < 1000; i++) {
        graph.addVertex(T.label, "person", T.id, i);
    }
    graph.vertices().forEachRemaining(a -> {
        graph.vertices().forEachRemaining(b -> {
            if (a != b) {
                a.addEdge("knows", b);
            }
        });
    });
    graph.vertices(50).next().addEdge("uncle", graph.vertices(70).next());
    logger.info(TimeUtil.clockWithResult(500, () -> g.V().match(as("a").out("knows").as("b"), as("a").out("uncle").as("b")).toList()).toString());
}
 
Example 15
Project: tinkergraph-gremlin   File: HaltedTraverserStrategyTest.java   Source Code and License 6 votes vote down vote up
@Test
public void shouldReturnDetachedElements() {
    final Graph graph = TinkerFactory.createModern();
    final GraphTraversalSource g = graph.traversal().withComputer().withStrategies(HaltedTraverserStrategy.create(new MapConfiguration(new HashMap<String, Object>() {{
        put(HaltedTraverserStrategy.HALTED_TRAVERSER_FACTORY, DetachedFactory.class.getCanonicalName());
    }})));
    g.V().out().forEachRemaining(vertex -> assertEquals(DetachedVertex.class, vertex.getClass()));
    g.V().out().properties("name").forEachRemaining(vertexProperty -> assertEquals(DetachedVertexProperty.class, vertexProperty.getClass()));
    g.V().out().values("name").forEachRemaining(value -> assertEquals(String.class, value.getClass()));
    g.V().out().outE().forEachRemaining(edge -> assertEquals(DetachedEdge.class, edge.getClass()));
    g.V().out().outE().properties("weight").forEachRemaining(property -> assertEquals(DetachedProperty.class, property.getClass()));
    g.V().out().outE().values("weight").forEachRemaining(value -> assertEquals(Double.class, value.getClass()));
    g.V().out().out().forEachRemaining(vertex -> assertEquals(DetachedVertex.class, vertex.getClass()));
    g.V().out().out().path().forEachRemaining(path -> assertEquals(DetachedPath.class, path.getClass()));
    g.V().out().pageRank().forEachRemaining(vertex -> assertEquals(DetachedVertex.class, vertex.getClass()));
    g.V().out().pageRank().out().forEachRemaining(vertex -> assertEquals(DetachedVertex.class, vertex.getClass()));
    // should handle nested collections
    g.V().out().fold().next().forEach(vertex -> assertEquals(DetachedVertex.class, vertex.getClass()));
}
 
Example 16
Project: bitsy   File: BitsyTestGraphProvider.java   Source Code and License 6 votes vote down vote up
@Override
	public void clear(Graph graph, Configuration configuration) throws Exception {
        if (graph != null) {
        	if (graph.tx().isOpen()) graph.tx().close();
        	graph.tx().onReadWrite(READ_WRITE_BEHAVIOR.MANUAL);
        	graph.tx().open();
        	System.out.println("Clearing graph");
        	graph.vertices().forEachRemaining(v -> v.remove());
        	graph.tx().commit();
        	System.out.println("Shutting down graph " + graph);
            graph.close();
        }

//		Thread.sleep(10);
//        File directory = new File(configuration.getString(BitsyGraph.DB_PATH_KEY));
//        wipeOut(directory);
//		Thread.sleep(10);
	}
 
Example 17
Project: bitsy   File: BitsyTestGraphProvider.java   Source Code and License 6 votes vote down vote up
@Override
public Map<String, Object> getBaseConfiguration(String graphName, Class<?> test, String testMethodName,
		GraphData loadGraphWith) {
	final String directory = makeTestDirectory(graphName, test, testMethodName);
	File testDataRootFile = new File(directory);
	testDataRootFile.mkdirs();

	try {
		if (testDataRootFile.exists()) {
			wipeOut(testDataRootFile);
		}
	} catch (Exception ex) {
		System.out.println("SETUP FAILED!!!");
		ex.printStackTrace();
	}

	String testDataRoot = testDataRootFile.getPath();

	return new HashMap<String, Object>() {{
           put(Graph.GRAPH, BitsyAutoReloadingGraph.class.getName());
           put(BitsyGraph.DB_PATH_KEY, testDataRoot);
           put(BitsyGraph.CREATE_DIR_IF_MISSING_KEY, true);
           put(BitsyGraph.DEFAULT_ISOLATION_LEVEL_KEY, BitsyIsolationLevel.READ_COMMITTED.toString());
           put(BitsyGraph.VERTEX_INDICES_KEY, "name, foo");
       }};
}
 
Example 18
Project: keti   File: GraphConfig.java   Source Code and License 6 votes vote down vote up
public static void createSchemaElements(final Graph newGraph) throws InterruptedException {
    createVertexLabel(newGraph, GraphResourceRepository.RESOURCE_LABEL);
    createVertexLabel(newGraph, GraphSubjectRepository.SUBJECT_LABEL);
    createVertexLabel(newGraph, GraphGenericRepository.VERSION_VERTEX_LABEL);

    createIndex(newGraph, BY_ZONE_INDEX_NAME, ZONE_ID_KEY);
    createUniqueCompositeIndex(newGraph, BY_ZONE_AND_RESOURCE_UNIQUE_INDEX_NAME,
            new String[] { ZONE_ID_KEY, RESOURCE_ID_KEY });

    createUniqueCompositeIndex(newGraph, BY_ZONE_AND_SUBJECT_UNIQUE_INDEX_NAME,
            new String[] { ZONE_ID_KEY, SUBJECT_ID_KEY });

    createUniqueCompositeIndex(newGraph, BY_VERSION_UNIQUE_INDEX_NAME,
            new String[] { GraphGenericRepository.VERSION_PROPERTY_KEY }, Integer.class);

    createEdgeIndex(newGraph, BY_SCOPE_INDEX_NAME, PARENT_EDGE_LABEL, SCOPE_PROPERTY_KEY);
}
 
Example 19
Project: keti   File: GraphConfig.java   Source Code and License 6 votes vote down vote up
public static void createUniqueCompositeIndex(final Graph newGraph, final String indexName,
        final String[] propertyKeyNames, final Class<?> propertyKeyType) throws InterruptedException {

    Assert.notEmpty(propertyKeyNames);
    newGraph.tx().rollback(); // Never create new indexes while a transaction is active
    TitanManagement mgmt = ((TitanGraph) newGraph).openManagement();
    IndexBuilder indexBuilder = mgmt.buildIndex(indexName, Vertex.class);
    if (!mgmt.containsGraphIndex(indexName)) {
        for (String propertyKeyName : propertyKeyNames) {
            PropertyKey indexPropertyKey = getOrCreatePropertyKey(propertyKeyName, propertyKeyType, mgmt);
            indexBuilder.addKey(indexPropertyKey);
        }
        indexBuilder.unique().buildCompositeIndex();
    }
    mgmt.commit();
    // Wait for the index to become available
    ManagementSystem.awaitGraphIndexStatus((TitanGraph) newGraph, indexName).status(SchemaStatus.ENABLED).call();
}
 
Example 20
Project: hdt-gremlin   File: HDTtoGremlin.java   Source Code and License 6 votes vote down vote up
private static void loadSection(long [] map, Iterator<? extends CharSequence> it, Graph graph, DictionarySectionRole role) {

		int count=0;
		while(it.hasNext()) {
			String str = it.next().toString();

			Vertex v = graph.addVertex(str);
//			v.property("node", str);
			map[count] = (long) v.id();

			if((count%1000000)==0) {
				System.out.println(role+" Vertex: "+(count/1000000)+"M");
			}
			count++;
		}
	}
 
Example 21
Project: hdt-gremlin   File: HDTtoGremlin.java   Source Code and License 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 22
Project: hdt-gremlin   File: HDTtoGremlin.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws Exception {		
		if(args.length!=2) {
			System.out.println("Usage: hdt2gremlin <file.hdt> <Gremlin Graph Config File>");
			System.out.println(" The config follows the syntax of gremlins factory Graph.open().");
			System.exit(-1);
		}
		
		// Create Graph
		Configuration p = new PropertiesConfiguration(args[1]);
		try(Graph gremlinGraph = GraphFactory.open(p)){
			
			// Open HDT
			try(HDT hdt = HDTManager.mapHDT("args[0]")){

				// Import HDT into Graph
				StopWatch st = new StopWatch();
				importGraph(hdt, gremlinGraph);
				System.out.println("Took "+st.stopAndShow());
			}
				
//			smallTest(gremlinGraph);
		}
		
		System.exit(0);
	}
 
Example 23
Project: LiteGraph   File: HugeZset.java   Source Code and License 6 votes vote down vote up
public static Iterator<Vertex> queryAllVertexOld(Graph graph, String zsetName) {
    Set<String> lampString = jedis.zrange(HUGEZSETLAMP + DOT + zsetName, 0, -1);
    Set<Vertex> vertexSet = new HashSet<>();

    Iterator<String> lampIterator = lampString.iterator();
    while (lampIterator.hasNext()) {
        String[] temp = split(lampIterator.next());
        Lamp lamp = new Lamp(temp[0], Long.valueOf(temp[1]), temp[2]);
        Set<String> allVertexString = jedis.zrange(zsetName + DOT + lamp.minValue, 0, -1);
        Iterator<String> allVertexStringIterator = allVertexString.iterator();
        while (allVertexStringIterator.hasNext()) {
            String vertexID = split(allVertexStringIterator.next())[1];
            Vertex vertex = queryVertexByID(vertexID, graph);
            vertexSet.add(vertex);
        }
    }
    return vertexSet.iterator();
}
 
Example 24
Project: LiteGraph   File: AddEdgeTest.java   Source Code and License 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_VX1X_asXaX_outXcreatedX_addEXcreatedByX_toXaX() {
    final Traversal<Vertex, Edge> traversal = get_g_VX1X_asXaX_outXcreatedX_addEXcreatedByX_toXaX(convertToVertexId("marko"));
    printTraversalForm(traversal);
    int count = 0;
    while (traversal.hasNext()) {
        final Edge edge = traversal.next();
        assertEquals("createdBy", edge.label());
        assertEquals(0, IteratorUtils.count(edge.properties()));
        count++;

    }
    assertEquals(1, count);
    assertEquals(7, IteratorUtils.count(g.E()));
    assertEquals(6, IteratorUtils.count(g.V()));
}
 
Example 25
Project: LiteGraph   File: IncrementalBulkLoader.java   Source Code and License 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Edge getOrCreateEdge(final Edge edge, final Vertex outVertex, final Vertex inVertex, final Graph graph, final GraphTraversalSource g) {
    final Edge e;
    final Traversal<Vertex, Edge> t = g.V(outVertex).outE(edge.label()).filter(__.inV().is(inVertex));
    if (t.hasNext()) {
        e = t.next();
        edge.properties().forEachRemaining(property -> {
            final Property<?> existing = e.property(property.key());
            if (!existing.isPresent() || !existing.value().equals(property.value())) {
                e.property(property.key(), property.value());
            }
        });
    } else {
        e = createEdge(edge, outVertex, inVertex, graph, g);
    }
    return e;
}
 
Example 26
Project: LiteGraph   File: PartitionStrategyProcessTest.java   Source Code and License 6 votes vote down vote up
@Test
@FeatureRequirementSet(FeatureRequirementSet.Package.VERTICES_ONLY)
@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)
public void shouldAppendPartitionToVertexPropertyOverMultiProperty() {
    final PartitionStrategy partitionStrategy = PartitionStrategy.build()
            .includeMetaProperties(true)
            .partitionKey(partition).writePartition("A").addReadPartition("A").create();
    final Vertex v = create(partitionStrategy).addV().property(VertexProperty.Cardinality.list, "any", "thing")
            .property(VertexProperty.Cardinality.list, "any", "more").next();

    assertNotNull(v);
    assertThat((List<String>) IteratorUtils.asList(v.properties("any")).stream().map(p -> ((VertexProperty) p).value()).collect(Collectors.toList()), containsInAnyOrder("thing", "more"));
    assertEquals("A", v.property(partition).value());
    assertThat((List<String>) IteratorUtils.asList(v.properties("any")).stream().map(p -> ((VertexProperty) p).value(partition)).collect(Collectors.toList()), containsInAnyOrder("A", "A"));
}
 
Example 27
Project: LiteGraph   File: GraphManager.java   Source Code and License 6 votes vote down vote up
/**
 * Selectively close transactions on the specified graphs or the graphs of traversal sources.
 */
private void closeTx(final Set<String> graphSourceNamesToCloseTxOn, final Transaction.Status tx) {
    final Set<Graph> graphsToCloseTxOn = new HashSet<>();

    // by the time this method has been called, it should be validated that the source/graph is present.
    // might be possible that it could have been removed dynamically, but that i'm not sure how one would do
    // that as of right now unless they were embedded in which case they'd need to know what they were doing
    // anyway
    graphSourceNamesToCloseTxOn.forEach(r -> {
        if (graphs.containsKey(r))
            graphsToCloseTxOn.add(graphs.get(r));
        else
            graphsToCloseTxOn.add(traversalSources.get(r).getGraph());
    });

    graphsToCloseTxOn.forEach(graph -> {
        if (graph.features().graph().supportsTransactions() && graph.tx().isOpen()) {
            if (tx == Transaction.Status.COMMIT)
                graph.tx().commit();
            else
                graph.tx().rollback();
        }
    });
}
 
Example 28
Project: LiteGraph   File: GraphTest.java   Source Code and License 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_hasLabelXpersonX_asXpX_VXsoftwareX_addInEXuses_pX() {
    final Traversal<Vertex, Edge> traversal = get_g_V_hasLabelXpersonX_asXpX_VXsoftwareX_addInEXuses_pX();
    printTraversalForm(traversal);
    int counter = 0;
    while (traversal.hasNext()) {
        final Edge edge = traversal.next();
        assertEquals("uses", edge.label());
        assertEquals("person", edge.outVertex().label());
        assertEquals("software", edge.inVertex().label());
        counter++;
    }
    assertEquals(8, counter);
}
 
Example 29
Project: LiteGraph   File: IncrementalBulkLoader.java   Source Code and License 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public VertexProperty getOrCreateVertexProperty(final VertexProperty<?> property, final Vertex vertex, final Graph graph, final GraphTraversalSource g) {
    final VertexProperty<?> vp;
    final VertexProperty<?> existing = vertex.property(property.key());
    if (!existing.isPresent()) {
        return createVertexProperty(property, vertex, graph, g);
    }
    if (!existing.value().equals(property.value())) {
        vp = vertex.property(property.key(), property.value());
    } else {
        vp = existing;
    }
    property.properties().forEachRemaining(metaProperty -> {
        final Property<?> existing2 = vp.property(metaProperty.key());
        if (!existing2.isPresent() || !existing2.value().equals(metaProperty.value())) {
            vp.property(metaProperty.key(), metaProperty.value());
        }
    });
    return vp;
}
 
Example 30
Project: LiteGraph   File: MultiMetaNeo4jTrait.java   Source Code and License 6 votes vote down vote up
@Override
public void removeVertexProperty(final Neo4jVertexProperty vertexProperty) {
    final Neo4jNode vertexPropertyNode = Neo4jHelper.getVertexPropertyNode(vertexProperty);
    final Neo4jNode vertexNode = ((Neo4jVertex) vertexProperty.element()).getBaseVertex();
    if (null == vertexPropertyNode) {
        if (vertexNode.degree(Neo4jDirection.OUTGOING, Graph.Hidden.hide(vertexProperty.key())) == 0) {
            if (vertexNode.hasProperty(vertexProperty.key()))
                vertexNode.removeProperty(vertexProperty.key());
        }
    } else {
        vertexPropertyNode.relationships(Neo4jDirection.BOTH).forEach(Neo4jRelationship::delete);
        vertexPropertyNode.delete();
        if (vertexNode.degree(Neo4jDirection.OUTGOING, Graph.Hidden.hide(vertexProperty.key())) == 0) {
            if (vertexNode.hasProperty(vertexProperty.key()))
                vertexNode.removeProperty(vertexProperty.key());
        }
    }
}
 
Example 31
Project: neo4j-gremlin-bolt   File: Neo4JSession.java   Source Code and License 6 votes vote down vote up
private static <T> void verifyIdentifiers(Class<T> elementClass, Object... ids) {
    // check length
    if (ids.length > 0) {
        // first element in array
        Object first = ids[0];
        // first element class
        Class<?> firstClass = first.getClass();
        // check it is an element
        if (elementClass.isAssignableFrom(firstClass)) {
            // all ids must be of the same class
            if (!Stream.of(ids).allMatch(id -> elementClass.isAssignableFrom(id.getClass())))
                throw Graph.Exceptions.idArgsMustBeEitherIdOrElement();
        }
        else if (!Stream.of(ids).map(Object::getClass).allMatch(firstClass::equals))
            throw Graph.Exceptions.idArgsMustBeEitherIdOrElement();
    }
}
 
Example 32
Project: LiteGraph   File: IoTest.java   Source Code and License 6 votes vote down vote up
@Test
@FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_EDGES)
@FeatureRequirement(featureClass = EdgePropertyFeatures.class, feature = FEATURE_STRING_VALUES)
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES)
public void shouldReadWriteSelfLoopingEdges() throws Exception {
    final Graph source = graph;
    final Vertex v1 = source.addVertex();
    final Vertex v2 = source.addVertex();
    v1.addEdge("CONTROL", v2);
    v1.addEdge("SELFLOOP", v1);

    final Configuration targetConf = graphProvider.newGraphConfiguration("target", this.getClass(), name.getMethodName(), null);
    final Graph target = graphProvider.openTestGraph(targetConf);
    try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
        source.io(IoCore.graphml()).writer().create().writeGraph(os, source);
        try (ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray())) {
            target.io(IoCore.graphml()).reader().create().readGraph(is, target);
        }
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }

    assertEquals(IteratorUtils.count(source.vertices()), IteratorUtils.count(target.vertices()));
    assertEquals(IteratorUtils.count(source.edges()), IteratorUtils.count(target.edges()));
}
 
Example 33
Project: act-platform   File: TraverseGraphDelegate.java   Source Code and License 5 votes vote down vote up
private Graph createGraph() {
  return ActGraph.builder()
          .setObjectManager(requestContext.getObjectManager())
          .setFactManager(requestContext.getFactManager())
          .setHasFactAccess(securityContext::hasReadPermission)
          .build();
}
 
Example 34
Project: debattons   File: ReactionService.java   Source Code and License 5 votes vote down vote up
private void loadReactedToByOriginalReactionAndVertexAndDepth(final Reaction originalReaction, Vertex originalVertex, final int depth, Graph graph) throws Exception {
  if (depth > 0) {
    Set<Reaction> reactedTo = new LinkedHashSet<>();
    originalReaction.setReactedTo(reactedTo);

    for (Iterator<Vertex> reactedToVertices = originalVertex.vertices(Direction.OUT, "reactedTo"); reactedToVertices.hasNext(); ) {
      Vertex reactedToVertex = reactedToVertices.next();
      Reaction reactedToReaction = Reaction.fromVertex(reactedToVertex, graphUtils);
      reactedTo.add(reactedToReaction);
      if (depth > 1) {
        loadReactedToByOriginalReactionAndVertexAndDepth(reactedToReaction, reactedToVertex, depth - 1, graph);
      }
    }
  }
}
 
Example 35
Project: debattons   File: GraphUtils.java   Source Code and License 5 votes vote down vote up
public GraphTraversal<Vertex, Vertex> getRootTraversal(Graph graph) {
  if (rootVertexId != null) {
    return graph.traversal().V(rootVertexId);
  } else {
    GraphTraversal<Vertex, Vertex> rootTraversal = graph.traversal().V().hasLabel("Root");
    if (rootTraversal.hasNext()) {
      rootVertexId = rootTraversal.next().id();
      return getRootTraversal(graph);
    } else {
      return rootTraversal;
    }
  }
}
 
Example 36
Project: mongodb-gremlin   File: MongoDBTest.java   Source Code and License 5 votes vote down vote up
@Test
public void shouldSupportInsertDocuments() throws Exception {
    final Graph graph = TinkerFactory.createModern();
    final GraphTraversalSource g = graph.traversal(GraphTraversalSource.class);
    final MongoDBTraversalSource db = graph.traversal(MongoDBTraversalSource.class);

    System.out.println(db.insertOne("{\"name\" : \"stephen\", \"~label\":\"person\", \"hobbies\":[\"art\",\"emails\",\"lame stuff\"], " +
            "\"created\" : {\"name\":\"Gremlin DSL\"}," +
            "\"likes\" : [{\"name\":\"Bob\", \"~label\":\"android\"},{\"name\":\"marko\",\"~id\":1}]}").toList());
    System.out.println(g.E().project("a", "b", "c").by(outV().values("name")).by(T.label).by(inV().values("name")).toList());
    System.out.println("##########");
    System.out.println(db.find("{\"name\" : \"stephen\"}").next());
}
 
Example 37
Project: tinkergraph-gremlin   File: TinkerGraph.java   Source Code and License 5 votes vote down vote up
private void validateHomogenousIds(final List<Object> ids) {
    final Iterator<Object> iterator = ids.iterator();
    Object id = iterator.next();
    if (id == null)
        throw Graph.Exceptions.idArgsMustBeEitherIdOrElement();
    final Class firstClass = id.getClass();
    while (iterator.hasNext()) {
        id = iterator.next();
        if (id == null || !id.getClass().equals(firstClass))
            throw Graph.Exceptions.idArgsMustBeEitherIdOrElement();
    }
}
 
Example 38
Project: tinkergraph-gremlin   File: TinkerGraphPlayTest.java   Source Code and License 5 votes vote down vote up
@Test
@Ignore
public void testPlay8() throws Exception {
    Graph graph = TinkerFactory.createModern();
    GraphTraversalSource g = graph.traversal();
    System.out.println(g.withSack(1).inject(1).repeat(__.sack((BiFunction)sum).by(__.constant(1))).times(10).emit().math("sin _").by(sack()).toList());
}
 
Example 39
Project: tinkergraph-gremlin   File: TinkerGraphPlayTest.java   Source Code and License 5 votes vote down vote up
@Test
@Ignore
public void testPlayDK() throws Exception {

    Graph graph = TinkerGraph.open();
    GraphTraversalSource g = graph.traversal();
    graph.io(GraphMLIo.build()).readGraph("/projects/apache/tinkerpop/data/grateful-dead.xml");
    System.out.println(g.V().filter(outE("sungBy").count().is(0)).explain());
    System.out.println(g.V().filter(outE("sungBy").count().is(lt(1))).explain());
    System.out.println(g.V().filter(outE("sungBy").count().is(1)).explain());
}
 
Example 40
Project: tinkergraph-gremlin   File: IoDataGenerationTest.java   Source Code and License 5 votes vote down vote up
@Test
public void shouldWriteSampleForGremlinServer() throws IOException {
    final Graph g = TinkerGraph.open();
    IntStream.range(0, 10000).forEach(i -> g.addVertex("oid", i));
    DistributionGenerator.build(g)
            .label("knows")
            .seedGenerator(() -> 987654321L)
            .outDistribution(new PowerLawDistribution(2.1))
            .inDistribution(new PowerLawDistribution(2.1))
            .expectedNumEdges(100000).create().generate();

    final OutputStream os = new FileOutputStream(tempPath + "sample.kryo");
    GryoWriter.build().mapper(GryoMapper.build().version(GryoVersion.V3_0).create()).create().writeGraph(os, g);
    os.close();
}
 
Example 41
Project: tinkergraph-gremlin   File: TinkerGraphIdManagerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void shouldUseLongIdManagerToCoerceTypes() {
    final Graph graph = TinkerGraph.open(longIdManagerConfig);
    final Vertex v = graph.addVertex(T.id, vertexIdValue);
    final VertexProperty vp = v.property(VertexProperty.Cardinality.single, "test", "value", T.id, vertexPropertyIdValue);
    final Edge e = v.addEdge("self", v, T.id, edgeIdValue);

    assertEquals(100l, v.id());
    assertEquals(200l, e.id());
    assertEquals(300l, vp.id());
}
 
Example 42
Project: tinkergraph-gremlin   File: TinkerGraphIdManagerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void shouldUseIntegerIdManagerToCoerceTypes() {
    final Graph graph = TinkerGraph.open(integerIdManagerConfig);
    final Vertex v = graph.addVertex(T.id, vertexIdValue);
    final VertexProperty vp = v.property(VertexProperty.Cardinality.single, "test", "value", T.id, vertexPropertyIdValue);
    final Edge e = v.addEdge("self", v, T.id, edgeIdValue);

    assertEquals(100, v.id());
    assertEquals(200, e.id());
    assertEquals(300, vp.id());
}
 
Example 43
Project: tinkergraph-gremlin   File: TinkerGraphIdManagerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void shouldUseIdManagerToCoerceTypes() {
    final Graph graph = TinkerGraph.open(idManagerConfig);
    final Vertex v = graph.addVertex(T.id, vertexIdValue);
    final VertexProperty vp = v.property(VertexProperty.Cardinality.single, "test", "value", T.id, vertexPropertyIdValue);
    final Edge e = v.addEdge("self", v, T.id, edgeIdValue);

    assertEquals(vertexId, v.id());
    assertEquals(edgeId, e.id());
    assertEquals(vertexPropertyId, vp.id());
}
 
Example 44
Project: tinkergraph-gremlin   File: TinkerGraphGryoTranslatorProvider.java   Source Code and License 5 votes vote down vote up
@Override
public GraphTraversalSource traversal(final Graph graph) {
    if ((Boolean) graph.configuration().getProperty("skipTest"))
        return graph.traversal();
        //throw new VerificationException("This test current does not work with Gremlin-Python", EmptyTraversal.instance());
    else {
        final GraphTraversalSource g = graph.traversal();
        return g.withStrategies(new TranslationStrategy(g, new GryoTranslator<>(JavaTranslator.of(g))));
    }
}
 
Example 45
Project: tinkergraph-gremlin   File: TinkerGraphGraphSONTranslatorProvider.java   Source Code and License 5 votes vote down vote up
@Override
public GraphTraversalSource traversal(final Graph graph) {
    if ((Boolean) graph.configuration().getProperty("skipTest"))
        return graph.traversal();
        //throw new VerificationException("This test current does not work with Gremlin-Python", EmptyTraversal.instance());
    else {
        final GraphTraversalSource g = graph.traversal();
        return g.withStrategies(new TranslationStrategy(g, new GraphSONTranslator<>(JavaTranslator.of(g))));
    }
}
 
Example 46
Project: tinkergraph-gremlin   File: TinkerGraphComputerProvider.java   Source Code and License 5 votes vote down vote up
@Override
public GraphTraversalSource traversal(final Graph graph) {
    return graph.traversal().withStrategies(VertexProgramStrategy.create(new MapConfiguration(new HashMap<String, Object>() {{
        put(VertexProgramStrategy.WORKERS, RANDOM.nextInt(Runtime.getRuntime().availableProcessors()) + 1);
        put(VertexProgramStrategy.GRAPH_COMPUTER, RANDOM.nextBoolean() ?
                GraphComputer.class.getCanonicalName() :
                TinkerGraphComputer.class.getCanonicalName());
    }})));
}
 
Example 47
Project: tinkergraph-gremlin   File: HaltedTraverserStrategyTest.java   Source Code and License 5 votes vote down vote up
@Test
public void shouldReturnReferenceElements() {
    final Graph graph = TinkerFactory.createModern();
    GraphTraversalSource g = graph.traversal().withComputer().withStrategies(HaltedTraverserStrategy.reference());
    g.V().out().forEachRemaining(vertex -> assertEquals(ReferenceVertex.class, vertex.getClass()));
    g.V().out().properties("name").forEachRemaining(vertexProperty -> assertEquals(ReferenceVertexProperty.class, vertexProperty.getClass()));
    g.V().out().values("name").forEachRemaining(value -> assertEquals(String.class, value.getClass()));
    g.V().out().outE().forEachRemaining(edge -> assertEquals(ReferenceEdge.class, edge.getClass()));
    g.V().out().outE().properties("weight").forEachRemaining(property -> assertEquals(ReferenceProperty.class, property.getClass()));
    g.V().out().outE().values("weight").forEachRemaining(value -> assertEquals(Double.class, value.getClass()));
    g.V().out().out().forEachRemaining(vertex -> assertEquals(ReferenceVertex.class, vertex.getClass()));
    g.V().out().out().path().forEachRemaining(path -> assertEquals(ReferencePath.class, path.getClass()));
    g.V().out().pageRank().forEachRemaining(vertex -> assertEquals(ReferenceVertex.class, vertex.getClass()));
    g.V().out().pageRank().out().forEachRemaining(vertex -> assertEquals(ReferenceVertex.class, vertex.getClass()));
    // the default should be reference elements
    g = graph.traversal().withComputer();
    g.V().out().forEachRemaining(vertex -> assertEquals(ReferenceVertex.class, vertex.getClass()));
    g.V().out().properties("name").forEachRemaining(vertexProperty -> assertEquals(ReferenceVertexProperty.class, vertexProperty.getClass()));
    g.V().out().values("name").forEachRemaining(value -> assertEquals(String.class, value.getClass()));
    g.V().out().outE().forEachRemaining(edge -> assertEquals(ReferenceEdge.class, edge.getClass()));
    g.V().out().outE().properties("weight").forEachRemaining(property -> assertEquals(ReferenceProperty.class, property.getClass()));
    g.V().out().outE().values("weight").forEachRemaining(value -> assertEquals(Double.class, value.getClass()));
    g.V().out().out().forEachRemaining(vertex -> assertEquals(ReferenceVertex.class, vertex.getClass()));
    g.V().out().out().path().forEachRemaining(path -> assertEquals(ReferencePath.class, path.getClass()));
    g.V().out().pageRank().forEachRemaining(vertex -> assertEquals(ReferenceVertex.class, vertex.getClass()));
    g.V().out().pageRank().out().forEachRemaining(vertex -> assertEquals(ReferenceVertex.class, vertex.getClass()));
    // should handle nested collections
    g.V().out().fold().next().forEach(vertex -> assertEquals(ReferenceVertex.class, vertex.getClass()));
}
 
Example 48
Project: tinkergraph-gremlin   File: TinkerGraphNoStrategyProvider.java   Source Code and License 5 votes vote down vote up
@Override
public GraphTraversalSource traversal(final Graph graph) {
    final List<Class> toRemove = TraversalStrategies.GlobalCache.getStrategies(TinkerGraph.class).toList().stream()
            .map(TraversalStrategy::getClass)
            .filter(clazz -> !REQUIRED_STRATEGIES.contains(clazz))
            .collect(Collectors.toList());
    return graph.traversal().withoutStrategies(toRemove.toArray(new Class[toRemove.size()]));
}
 
Example 49
Project: tinkergraph-gremlin   File: TinkerGraphNoStrategyComputerProvider.java   Source Code and License 5 votes vote down vote up
@Override
public GraphTraversalSource traversal(final Graph graph) {
    final List<Class> toRemove = TraversalStrategies.GlobalCache.getStrategies(TinkerGraph.class).toList().stream()
            .map(TraversalStrategy::getClass)
            .filter(clazz -> !REQUIRED_STRATEGIES.contains(clazz))
            .collect(Collectors.toList());
    return graph.traversal().withoutStrategies(toRemove.toArray(new Class[toRemove.size()])).withComputer();
}
 
Example 50
Project: tinkergraph-gremlin   File: TinkerGraphProvider.java   Source Code and License 5 votes vote down vote up
@Override
public void clear(final Graph graph, final Configuration configuration) throws Exception {
    if (graph != null)
        graph.close();

    // in the even the graph is persisted we need to clean up
    final String graphLocation = configuration.getString(TinkerGraph.GREMLIN_TINKERGRAPH_GRAPH_LOCATION, null);
    if (graphLocation != null) {
        final File f = new File(graphLocation);
        f.delete();
    }
}
 
Example 51
Project: graphsail   File: DataStore.java   Source Code and License 5 votes vote down vote up
DataStore(final Graph graph,
          final boolean readOnly,
          final Function<String, GraphIndex> indexFactory,
          final SailChangedHelper sailChangedHelper) {
    this.graph = graph;
    this.traversal = graph.traversal();
    this.readOnly = readOnly;
    this.sailChangedHelper = sailChangedHelper;

    valueIndex = indexFactory.apply(Schema.VertexProperties.VALUE);
    valueIndex.initialize();
}
 
Example 52
Project: graphsail   File: GraphSail.java   Source Code and License 5 votes vote down vote up
public GraphSail(final Graph graph, final Function<String, GraphIndex> indexFactory, final boolean readOnly) {
    this.dataStore = new DataStore(graph, readOnly, indexFactory, new DataStore.SailChangedHelper() {
        @Override
        public void notifyOfChanges(boolean statementsAdded, boolean statementsRemoved) {
            if (statementsAdded || statementsRemoved) {
                SailChangedEvent event = new SailChangedEvent() {
                    @Override
                    public Sail getSail() {
                        return GraphSail.this;
                    }

                    @Override
                    public boolean statementsAdded() {
                        return statementsAdded;
                    }

                    @Override
                    public boolean statementsRemoved() {
                        return statementsRemoved;
                    }
                };
                notifySailChanged(event);
            }
        }
    });
    this.sailStore = new GraphSailStore(dataStore);
}
 
Example 53
Project: bitsy   File: BitsyTransaction.java   Source Code and License 5 votes vote down vote up
@Override
public Graph createThreadedTx() {
	// TP3 behavior of threaded graphs are different than TP2
	throw new UnsupportedOperationException("Graph does not support threaded transactions");

	// TODO: Reintroduce threaded transactions
	// return new ThreadedBitsyGraph(graph);
}
 
Example 54
Project: bitsy   File: BitsyGraphStep.java   Source Code and License 5 votes vote down vote up
private BitsyGraph getBitsyGraph() {
	Graph baseGraph = this.getTraversal().getGraph().get();
       final BitsyGraph graph;
	if (baseGraph instanceof BitsyAutoReloadingGraph) {
		return ((BitsyAutoReloadingGraph)baseGraph).getBaseGraph();
	} else {
		return (BitsyGraph) baseGraph;
	}
}
 
Example 55
Project: bitsy   File: BitsyGraphIT.java   Source Code and License 5 votes vote down vote up
private Vertex getVertex(Graph graph, Object id) {
	Iterator<Vertex> iter = graph.vertices(id);
	if (iter.hasNext()) {
		return iter.next();
	} else {
		return null;
	}
}
 
Example 56
Project: bitsy   File: BitsyGraphIT.java   Source Code and License 5 votes vote down vote up
private Edge getEdge(Graph graph, Object id) {
	Iterator<Edge> iter = graph.edges(id);
	if (iter.hasNext()) {
		return iter.next();
	} else {
		return null;
	}
}
 
Example 57
Project: keti   File: GraphConfig.java   Source Code and License 5 votes vote down vote up
public static void createIndex(final Graph newGraph, final String indexName, final String indexKey)
        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(String.class).make();
        mgmt.buildIndex(indexName, Vertex.class).addKey(indexPropertyKey).buildCompositeIndex();
    }
    mgmt.commit();
    // Wait for the index to become available
    ManagementSystem.awaitGraphIndexStatus((TitanGraph) newGraph, indexName).status(SchemaStatus.ENABLED).call();
}
 
Example 58
Project: keti   File: GraphConfig.java   Source Code and License 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 59
Project: keti   File: GraphConfig.java   Source Code and License 5 votes vote down vote up
public static void createEdgeIndex(final Graph newGraph, final String indexName, final String label,
        final String indexKey) throws InterruptedException {
    newGraph.tx().rollback(); // Never create new indexes while a transaction is active
    TitanManagement mgmt = ((TitanGraph) newGraph).openManagement();
    EdgeLabel edgeLabel = mgmt.getOrCreateEdgeLabel(label);
    if (!mgmt.containsRelationIndex(edgeLabel, indexName)) {
        PropertyKey indexPropertyKey = getOrCreatePropertyKey(indexKey, String.class, mgmt);
        mgmt.buildEdgeIndex(edgeLabel, indexName, Direction.OUT, indexPropertyKey);
    }
    mgmt.commit();
    // Wait for the index to become available
    ManagementSystem.awaitRelationIndexStatus((TitanGraph) newGraph, indexName, label).status(SchemaStatus.ENABLED)
            .call();
}
 
Example 60
Project: keti   File: GraphSubjectRepositoryTest.java   Source Code and License 5 votes vote down vote up
@BeforeClass
public void setup() throws Exception {
    this.subjectRepository = new GraphSubjectRepository();
    Graph graph = TitanFactory.build().set("storage.backend", "inmemory").open();
    GraphConfig.createSchemaElements(graph);
    this.graphTraversalSource = graph.traversal();
    this.subjectRepository.setGraphTraversal(this.graphTraversalSource);
}