@Override public void generate(String dbPath) { GraphDatabaseService graphDb = new EmbeddedGraphDatabase(dbPath); Index<Node> nodeIndex = graphDb .index() .forNodes("nodes", MapUtil.stringMap("provider", "lucene", "type", "fulltext")); Index<Relationship> relationshipIndex = graphDb .index() .forRelationships( "relationships", MapUtil.stringMap("provider", "lucene", "type", "fulltext")); Transaction tx = graphDb.beginTx(); try { Node n = graphDb.createNode(); Node n2 = graphDb.createNode(); Relationship rel = n.createRelationshipTo(n2, REL_TYPE); nodeIndex.add(n, "name", "alpha bravo"); nodeIndex.add(n2, "name", "charlie delta"); relationshipIndex.add(rel, "name", "echo foxtrot"); tx.success(); } finally { tx.finish(); } graphDb.shutdown(); }
private long createDb() { GraphDatabaseService graphDb = new GraphDatabaseFactory().newEmbeddedDatabase(DB_PATH); long firstNodeId = -1; Transaction tx = graphDb.beginTx(); try { Node firstNode = graphDb.createNode(); firstNodeId = firstNode.getId(); firstNode.setProperty("message", "Hello, "); firstNode.setProperty( "someJson", "{\n \"is\" : \"vcard\",\n \"name\" : \"Jim Barritt\"\n}"); Node secondNode = graphDb.createNode(); secondNode.setProperty("message", "World!"); Relationship relationship = firstNode.createRelationshipTo(secondNode, KNOWS); relationship.setProperty("message", "brave Neo4j "); tx.success(); return firstNodeId; } finally { tx.finish(); graphDb.shutdown(); } }
public void rn() throws IOException { List<RoadLink> links = loadToDatabase("/Users/duduba/gj.mif", "/Users/duduba/gj.mid", false); GraphDatabaseService graphDb = neo.getDb(); Index<Node> nodeIndex = neo.getNodeIndex(); for (RoadLink link : links) { Transaction tx = graphDb.beginTx(); try { Node fromNode = nodeIndex.get("id", link.fromNode).getSingle(); if (fromNode == null) { fromNode = graphDb.createNode(); fromNode.setProperty("id", link.fromNode); nodeIndex.add(fromNode, "id", link.fromNode); } Node toNode = nodeIndex.get("id", link.toNode).getSingle(); if (toNode == null) { toNode = graphDb.createNode(); toNode.setProperty("id", link.toNode); nodeIndex.add(toNode, "id", link.toNode); } Relationship r = fromNode.createRelationshipTo(toNode, Neo.RelTypes.TO); r.setProperty("no", link.no); r.setProperty("name", link.name); tx.success(); } finally { tx.finish(); } } logger.debug("haha, it's ok!"); }
@Test public void shouldAccessAssignedLabels() throws Exception { // given GraphDatabaseService db = dbRule.getGraphDatabaseService(); ChangedLabels labels = (ChangedLabels) db.registerTransactionEventHandler(new ChangedLabels()); try { // when try (Transaction tx = db.beginTx()) { Node node1 = db.createNode(), node2 = db.createNode(), node3 = db.createNode(); labels.add(node1, "Foo"); labels.add(node2, "Bar"); labels.add(node3, "Baz"); labels.add(node3, "Bar"); labels.activate(); tx.success(); } // then assertTrue(labels.isEmpty()); } finally { db.unregisterTransactionEventHandler(labels); } }
@Test public void shouldBeAbleToImplementAnonymousGraphQuery() throws Exception { // given GraphDatabaseService db = Db.impermanentDb(); Transaction tx = db.beginTx(); Node firstNode = db.createNode(); Node secondNode = db.createNode(); firstNode.createRelationshipTo(secondNode, withName("CONNECTED_TO")); tx.success(); tx.finish(); GraphQuery query = new GraphQuery() { @Override public Iterable<Node> execute(Node startNode) { return startNode.traverse( Traverser.Order.DEPTH_FIRST, StopEvaluator.DEPTH_ONE, ReturnableEvaluator.ALL_BUT_START_NODE, withName("CONNECTED_TO"), Direction.OUTGOING); } }; // when Iterable<Node> result = query.execute(firstNode); // then Iterator<Node> iterator = result.iterator(); assertEquals(secondNode, iterator.next()); assertFalse(iterator.hasNext()); }
@Test public void canAddShortStringToRelationship() throws Exception { long recordCount = dynamicRecordsInUse(); GraphDatabaseService db = graphdb.getGraphDatabaseService(); Relationship rel = db.createNode().createRelationshipTo(db.createNode(), withName("REL_TYPE")); rel.setProperty("type", "dimsedut"); commit(); assertEquals(recordCount, dynamicRecordsInUse()); assertThat(rel, inTx(db, hasProperty("type").withValue("dimsedut"))); }
@Test public void nodesCanBeRelatedByARelationship() { Transaction tx = graphDb.beginTx(); try { Node zero = graphDb.createNode(); Node one = graphDb.createNode(); zero.createRelationshipTo(one, RelationType.SUCCESOR); tx.success(); } finally { tx.finish(); } }
@Test public void shouldProvideTheCorrectRelationshipData() { GraphDatabaseService db = dbRule.getGraphDatabaseService(); // create a rel type so the next type id is non zero try (Transaction tx = db.beginTx()) { db.createNode() .createRelationshipTo(db.createNode(), DynamicRelationshipType.withName("TYPE")); } RelationshipType livesIn = DynamicRelationshipType.withName("LIVES_IN"); long relId; try (Transaction tx = db.beginTx()) { Node person = db.createNode(DynamicLabel.label("Person")); Node city = db.createNode(DynamicLabel.label("City")); Relationship rel = person.createRelationshipTo(city, livesIn); rel.setProperty("since", 2009); relId = rel.getId(); tx.success(); } final Set<String> changedRelationships = new HashSet<>(); db.registerTransactionEventHandler( new TransactionEventHandler.Adapter<Void>() { @Override public Void beforeCommit(TransactionData data) throws Exception { for (PropertyEntry<Relationship> entry : data.assignedRelationshipProperties()) { changedRelationships.add(entry.entity().getType().name()); } return null; } }); try (Transaction tx = db.beginTx()) { Relationship rel = db.getRelationshipById(relId); rel.setProperty("since", 2010); tx.success(); } assertEquals(1, changedRelationships.size()); assertTrue( livesIn + " not in " + changedRelationships.toString(), changedRelationships.contains(livesIn.name())); }
@Test public void shouldBeAbleToAccessExceptionThrownInEventHook() { class MyFancyException extends Exception {} ExceptionThrowingEventHandler handler = new ExceptionThrowingEventHandler(new MyFancyException(), null, null); GraphDatabaseService db = dbRule.getGraphDatabaseService(); db.registerTransactionEventHandler(handler); try { Transaction tx = db.beginTx(); try { db.createNode().delete(); tx.success(); tx.close(); fail("Should fail commit"); } catch (TransactionFailureException e) { Throwable currentEx = e; do { currentEx = currentEx.getCause(); if (currentEx instanceof MyFancyException) { return; } } while (currentEx.getCause() != null); fail( "Expected to find the exception thrown in the event hook as the cause of transaction failure."); } } finally { db.unregisterTransactionEventHandler(handler); } }
private void addMutantToDB( Individual original, Individual mutant, int generationNumber, Location location) { final GraphDatabaseService graphDB = GraphDB.graphDB(); IndexManager index = graphDB.index(); Index<Node> individualNodes = index.forNodes("individuals"); Index<Node> locationNodes = index.forNodes("locations"); Transaction tx = graphDB.beginTx(); Relationship mutantRelationship; Relationship node; Node individualNode; try { individualNode = graphDB.createNode(); individualNode.setProperty("fitness", mutant.getGlobalFitness()); individualNode.setProperty("id", mutant.uid.toString()); Node locationNode = locationNodes.get("locationID", location.getPosition()).next(); node = individualNode.createRelationshipTo(locationNode, RelTypes.LOCATEDIN); node.setProperty("generation", generationNumber); Node originalNode = individualNodes.get("id", original.uid.toString()).next(); mutantRelationship = individualNode.createRelationshipTo(originalNode, RelTypes.MUTANTOF); mutantRelationship.setProperty("generation", generationNumber); individualNodes.add(individualNode, "id", mutant.uid.toString()); tx.success(); } finally { tx.finish(); } }
@Test public void bugTest() { final Label label = Label.label("TEST"); try (Transaction tx = database.beginTx()) { database.createNode(label); database.createNode(label); tx.success(); } final AtomicInteger count = new AtomicInteger(0); new IterableInputBatchTransactionExecutor<>( database, 100, new AllNodesWithLabel(database, 100, label), new UnitOfWork<Node>() { @Override public void execute( GraphDatabaseService database, Node input, int batchNumber, int stepNumber) { count.incrementAndGet(); } }) .execute(); assertEquals(2, count.get()); }
@Test public void modulesShouldBeDelegatedToInCorrectOrder() throws InterruptedException { GraphDatabaseService database = builder() .setConfig( "com.graphaware.module.test1.1", TestModuleBootstrapper.MODULE_ENABLED.getDefaultValue()) .setConfig( "com.graphaware.module.test3.3", TestModuleBootstrapper.MODULE_ENABLED.getDefaultValue()) .setConfig( "com.graphaware.module.test2.2", TestModuleBootstrapper.MODULE_ENABLED.getDefaultValue()) .newGraphDatabase(); registerShutdownHook(database); try (Transaction tx = database.beginTx()) { database.createNode(); tx.success(); } assertEquals(3, TEST_RUNTIME_MODULES.size()); assertEquals("test1", TEST_RUNTIME_MODULES.get(0).getId()); assertEquals("test2", TEST_RUNTIME_MODULES.get(1).getId()); assertEquals("test3", TEST_RUNTIME_MODULES.get(2).getId()); }
@Test public void modulesShouldBeDelegatedToInRandomOrderWhenOrderClashes() throws InterruptedException { GraphDatabaseService database = builder() .setConfig( "com.graphaware.module.test1.1", TestModuleBootstrapper.MODULE_ENABLED.getDefaultValue()) .setConfig( "com.graphaware.module.test3.1", TestModuleBootstrapper.MODULE_ENABLED.getDefaultValue()) .setConfig( "com.graphaware.module.test2.1", TestModuleBootstrapper.MODULE_ENABLED.getDefaultValue()) .newGraphDatabase(); registerShutdownHook(database); try (Transaction tx = database.beginTx()) { database.createNode(); tx.success(); } assertEquals(3, TEST_RUNTIME_MODULES.size()); Set<String> remaining = new HashSet<>(Arrays.asList("test1", "test2", "test3")); assertTrue(remaining.remove(TEST_RUNTIME_MODULES.get(0).getId())); assertTrue(remaining.remove(TEST_RUNTIME_MODULES.get(1).getId())); assertTrue(remaining.remove(TEST_RUNTIME_MODULES.get(2).getId())); assertTrue(remaining.isEmpty()); }
@Test public void moduleShouldBeInitializedWhenRuntimeIsEnabled() throws InterruptedException { GraphDatabaseService database = builder() .setConfig( TestModuleBootstrapper.MODULE_ENABLED, TestModuleBootstrapper.MODULE_ENABLED.getDefaultValue()) .setConfig( TestModuleBootstrapper.MODULE_CONFIG, TestModuleBootstrapper.MODULE_CONFIG.getDefaultValue()) .newGraphDatabase(); registerShutdownHook(database); try (Transaction tx = database.beginTx()) { database.createNode(); // tx just to kick off Runtime init tx.success(); } assertEquals(1, TEST_RUNTIME_MODULES.size()); assertTrue(TEST_RUNTIME_MODULES.get(0).isInitialized()); assertEquals("configValue", TEST_RUNTIME_MODULES.get(0).getConfig().get("configKey")); database.shutdown(); assertFalse(TEST_RUNTIME_MODULES.get(0).isInitialized()); }
@Test public void moduleShouldBeInitializedWhenAnotherModuleIsMisConfigured() throws InterruptedException { GraphDatabaseService database = builder() .setConfig("com.graphaware.module.wrong1.enabled", "com.not.existent.Bootstrapper") .setConfig("com.graphaware.module.wrong2.2", "com.not.existent.Bootstrapper") .setConfig( TestModuleBootstrapper.MODULE_ENABLED, TestModuleBootstrapper.MODULE_ENABLED.getDefaultValue()) .setConfig( TestModuleBootstrapper.MODULE_CONFIG, TestModuleBootstrapper.MODULE_CONFIG.getDefaultValue()) .newGraphDatabase(); registerShutdownHook(database); try (Transaction tx = database.beginTx()) { database.createNode(); tx.success(); } assertEquals(1, TEST_RUNTIME_MODULES.size()); assertTrue(TEST_RUNTIME_MODULES.get(0).isInitialized()); assertEquals("configValue", TEST_RUNTIME_MODULES.get(0).getConfig().get("configKey")); database.shutdown(); assertFalse(TEST_RUNTIME_MODULES.get(0).isInitialized()); }
@Test public void iterableAcquiredInTransactionShouldBeProcessed() { try (Transaction tx = database.beginTx()) { for (int i = 0; i < 100; i++) { database.createNode(); } tx.success(); } BatchTransactionExecutor executor = new IterableInputBatchTransactionExecutor<>( database, 10, new AllNodes(database, 10), new UnitOfWork<Node>() { @Override public void execute( GraphDatabaseService database, Node node, int batchNumber, int stepNumber) { node.setProperty("name", "Name" + batchNumber + stepNumber); } }); executor.execute(); try (Transaction tx = database.beginTx()) { assertEquals("Name11", database.getNodeById(0).getProperty("name")); assertEquals("Name12", database.getNodeById(1).getProperty("name")); assertEquals("Name13", database.getNodeById(2).getProperty("name")); assertEquals("Name108", database.getNodeById(97).getProperty("name")); assertEquals("Name109", database.getNodeById(98).getProperty("name")); assertEquals("Name1010", database.getNodeById(99).getProperty("name")); } }
public Node _createNode(String[] labels, Map<String, Object> properties) { ++nodesCreated; Node node = graphDb.createNode(); _addLabels(node, labels); if (null != properties) _setProperties(node, properties); return node; }
@Override public Map<String, Node> create(GraphDatabaseService graphdb) { Map<String, Node> result = new HashMap<String, Node>(); Transaction tx = graphdb.beginTx(); try { graphdb.index().getRelationshipAutoIndexer().setEnabled(autoIndexRelationships); for (NODE def : nodes) { result.put( def.name(), init( graphdb.createNode(), def.setNameProperty() ? def.name() : null, def.properties(), graphdb.index().getNodeAutoIndexer(), autoIndexNodes)); } for (REL def : rels) { init( result .get(def.start()) .createRelationshipTo( result.get(def.end()), DynamicRelationshipType.withName(def.type())), def.setNameProperty() ? def.name() : null, def.properties(), graphdb.index().getRelationshipAutoIndexer(), autoIndexRelationships); } tx.success(); } finally { tx.finish(); } return result; }
private void createSomeTransactions(GraphDatabaseService db) { Transaction tx = db.beginTx(); Node node1 = db.createNode(); Node node2 = db.createNode(); node1.createRelationshipTo(node2, DynamicRelationshipType.withName("relType1")); tx.success(); tx.finish(); tx = db.beginTx(); node1.delete(); tx.success(); try { // Will throw exception, causing the tx to be rolledback. tx.finish(); } catch (Exception nothingToSeeHereMoveAlong) { // InvalidRecordException coming, node1 has rels } /* * The damage has already been done. The following just makes sure * the corrupting tx is flushed to disk, since we will exit * uncleanly. */ tx = db.beginTx(); node1.setProperty("foo", "bar"); tx.success(); tx.finish(); }
public static void main(String[] args) { GraphDatabaseFactory neodb = new GraphDatabaseFactory(); // Direccion de la Base de datos Neo4j GraphDatabaseService graphDb = neodb.newEmbeddedDatabase("C:\\Users\\Administrador\\Documents\\Neo4j\\default.graphdb"); try (Transaction tx = graphDb.beginTx()) { // Creacion de nodos con sus propiedades Node bobNode = graphDb.createNode(NodeType.Person); // Tipo del nodo Person bobNode.setProperty("Pid", 5001); bobNode.setProperty("Name", "Bob"); bobNode.setProperty("Age", 23); Node aliceNode = graphDb.createNode(NodeType.Person); aliceNode.setProperty("Pid", 5002); aliceNode.setProperty("Name", "Eve"); Node eveNode = graphDb.createNode(NodeType.Person); eveNode.setProperty("Name", "Eve"); Node itNode = graphDb.createNode(NodeType.Course); // TIpo del nodo Course itNode.setProperty("Id", 1); itNode.setProperty("Name", "IT Beginners"); itNode.setProperty("Location", "Room 153"); Node electronicNode = graphDb.createNode(NodeType.Course); electronicNode.setProperty("Name", "Electronics Advanced"); // Creacion de relaciones entre los nodos bobNode.createRelationshipTo(aliceNode, RelationType.Knows); // Tipo de relacion Knows Relationship bobRelIt = bobNode.createRelationshipTo( itNode, RelationType.BelongsTo); // Tipo de relacion BelongsTo bobRelIt.setProperty("Function", "Student"); Relationship bobRelElectronics = bobNode.createRelationshipTo(electronicNode, RelationType.BelongsTo); bobRelElectronics.setProperty("Function", "Supply Teacher"); Relationship aliceRelIt = aliceNode.createRelationshipTo(itNode, RelationType.BelongsTo); aliceRelIt.setProperty("Function", "Teacher"); tx.success(); // Proceso termino de forma exitosa } graphDb.shutdown(); // Cerrar base }
@Test public void makeSureLazyLoadingRelationshipsWorksEvenIfOtherIteratorAlsoLoadsInTheSameIteration() { int numEdges = 100; /* create 256 nodes */ GraphDatabaseService graphDB = getGraphDb(); Node[] nodes = new Node[256]; for (int num_nodes = 0; num_nodes < nodes.length; num_nodes += 1) { nodes[num_nodes] = graphDB.createNode(); } newTransaction(); /* create random outgoing relationships from node 5 */ Node hub = nodes[4]; int nextID = 7; RelationshipType outtie = withName("outtie"); RelationshipType innie = withName("innie"); for (int k = 0; k < numEdges; k++) { Node neighbor = nodes[nextID]; nextID += 7; nextID &= 255; if (nextID == 0) { nextID = 1; } hub.createRelationshipTo(neighbor, outtie); } newTransaction(); /* create random incoming relationships to node 5 */ for (int k = 0; k < numEdges; k += 1) { Node neighbor = nodes[nextID]; nextID += 7; nextID &= 255; if (nextID == 0) { nextID = 1; } neighbor.createRelationshipTo(hub, innie); } commit(); clearCache(); newTransaction(); hub = graphDB.getNodeById(hub.getId()); int count = 0; for (@SuppressWarnings("unused") Relationship r1 : hub.getRelationships()) { count += count(hub.getRelationships()); } assertEquals(40000, count); count = 0; for (@SuppressWarnings("unused") Relationship r1 : hub.getRelationships()) { count += count(hub.getRelationships()); } assertEquals(40000, count); commit(); }
@Test public void deletedNewLabelShouldNotInfluenceEquality() { // bug test try (Transaction tx = database.beginTx()) { database.createNode(DynamicLabel.label("Accident")); database.createNode(DynamicLabel.label("RealLabel")); tx.success(); } try (Transaction tx = database.beginTx()) { database.getNodeById(0).delete(); tx.success(); } String cypher = "CREATE (n:RealLabel)"; assertSameGraph(database, cypher); }
public static Node ensureCharacterIsInDb(String name, GraphDatabaseService db) { Node theCharacterNode = db.index().forNodes("characters").get("name", name).getSingle(); if (theCharacterNode == null) { theCharacterNode = db.createNode(); theCharacterNode.setProperty("name", name); ensureCharacterIsIndexed(theCharacterNode, db); } return theCharacterNode; }
private void createRelationships( BatchTransaction tx, Node node, RelationshipType type, Direction direction, int count) { for (int i = 0; i < count; i++) { Node firstNode = direction == OUTGOING || direction == BOTH ? node : db.createNode(); Node otherNode = direction == INCOMING || direction == BOTH ? node : db.createNode(); firstNode.createRelationshipTo(otherNode, type); tx.increment(); } }
private static Node createNodeWithNameProperty(GraphDatabaseService db, String name) { try (Transaction tx = db.beginTx()) { Node node = db.createNode(); node.setProperty("name", name); db.index().forNodes("index").add(node, "name", name); tx.success(); return node; } }
@Override protected void generateInitialData(GraphDatabaseService graphDb) { // TODO: create bigger sample graph here try (org.neo4j.graphdb.Transaction tx = graphDb.beginTx()) { Node node1 = set(graphDb.createNode()); Node node2 = set(graphDb.createNode(), property("key", "value")); node1.createRelationshipTo(node2, DynamicRelationshipType.withName("C")); tx.success(); } }
private static Node ensureThingInDb(String thing, GraphDatabaseService database) { Node theThingNode = database.index().forNodes("things").get("thing", thing).getSingle(); if (theThingNode == null) { theThingNode = database.createNode(); theThingNode.setProperty("thing", thing); ensureThingIsIndexed(theThingNode, database); } return theThingNode; }
private static Node addNode(String name) { Node userNode; try (Transaction tx = graphDb.beginTx()) { Label label = DynamicLabel.label("Nome"); userNode = graphDb.createNode(label); userNode.setProperty("name", name); System.out.println("node created"); tx.success(); } return userNode; }
@Test public void equalArraysWithDifferentTypeShouldBeEqual() { try (Transaction tx = database.beginTx()) { database.createNode().setProperty("number", new int[] {123, 124}); tx.success(); } String cypher = "CREATE (n {number:[123,124]})"; assertSameGraph(database, cypher); }
@Test public void testDistance() { double lon1 = 32.32; double lat1 = 32.32; Transaction tx = graphDb.beginTx(); String query; System.out.println("delete all nodes"); String deleteQuery = "MATCH n-[r]-() DELETE n, r"; graphDb.execute(deleteQuery); root = PrefixTree.getOrCreateRoot(INDEXLABEL, graphDb); Node node = graphDb.createNode(); node.setProperty(LON, lon1); node.setProperty(LAT, lat1); List<Node> candidate1 = gendata.insertNode(graphDb, 2, lon1, lat1, 0.1); List<Node> candidate2 = gendata.insertNode(graphDb, 2, lon1, lat1, 0.2); PrefixTree.addNode(graphDb, root, candidate1.get(0)); query = "MATCH (n {PrefixTreeRoot:'root'})-[*8..8]-(x {geohash: 'stz030gzmygt'}) RETURN x"; PrefixTree.addNode(graphDb, root, candidate1.get(1)); query = "MATCH (n {PrefixTreeRoot:'root'})-[*8..8]-(x {geohash: 'stz00001z0d7'}) RETURN x"; PrefixTree.addNode(graphDb, root, candidate2.get(0)); query = "MATCH (n {PrefixTreeRoot:'root'})-[*8..8]-(x {geohash: 'stz0dy31m1hs'}) RETURN x"; PrefixTree.addNode(graphDb, root, candidate2.get(1)); query = "MATCH (n {PrefixTreeRoot:'root'})-[*8..8]-(x {geohash: 'stz00s3tzsd0'}) RETURN x"; // for (Node can : candidate1) { // PrefixTree.addNode(graphDb, root, can); // query = "MATCH (n {PrefixTreeRoot:'root'})-[*8..8]-(n {geohash: ''}) RETURN x"; // getAllNodes(query, "tag"); // System.out.println("lat:" + can.getProperty("lat") + " lon:" // + can.getProperty("lon") + " geohash:" + can.getProperty("geohash") + " dis:" + // CalDistance // .calculateDistance((double) can.getProperty("lon"), (double) can.getProperty("lat"), // node) // + " value:" + can); // } // for (Node can : candidate2) { // PrefixTree.addNode(graphDb, root, can); // query = "MATCH (n {PrefixTreeRoot:'root'})-[*8..8]-(x) RETURN x"; // getAllNodes(query, "tag"); // System.out.println("lat:" + can.getProperty("lat") + " lon:" // + can.getProperty("lon") + " geohash:" + can.getProperty("geohash") + " dis:" + // CalDistance // .calculateDistance((double) can.getProperty("lon"), (double) can.getProperty("lat"), // node) // + " value:" + can); // } getWithDistance(20.0, root, node); getWithDistance(4.0, root, node); tx.close(); graphDb.shutdown(); }