@Test public void clearGraphWithoutRuntimeShouldDeleteBasedOnRelInclusionPolicy() { try (Transaction tx = database.beginTx()) { String cypher = "CREATE " + "(purple:Purple {name:'Purple'})<-[:REL]-(red1:Red {name:'Red'})-[:REL]->(black1:Black {name:'Black'})-[:REL]->(green:Green {name:'Green'})," + "(red2:Red {name:'Red'})-[:REL]->(black2:Black {name:'Black'}), (blue1:Blue)-[:REL2]->(blue2:Blue)"; populateDatabase(cypher); tx.success(); } InclusionPolicies inclusionPolicies = InclusionPolicies.all().with(new BlueNodeInclusionPolicy()).with(new Rel2InclusionPolicy()); try (Transaction tx = database.beginTx()) { clearGraph(database, inclusionPolicies); tx.success(); } try (Transaction tx = database.beginTx()) { assertEquals(6, count(at(database).getAllNodes())); assertEquals(4, count(at(database).getAllRelationships())); tx.success(); } }
@Test public void shouldRetrieveMultipleNodesWithSameValueFromIndex() throws Exception { // this test was included here for now as a precondition for the following test // given GraphDatabaseService graph = dbRule.getGraphDatabaseService(); createIndex(graph, LABEL1, "name"); Node node1, node2; try (Transaction tx = graph.beginTx()) { node1 = graph.createNode(LABEL1); node1.setProperty("name", "Stefan"); node2 = graph.createNode(LABEL1); node2.setProperty("name", "Stefan"); tx.success(); } try (Transaction tx = graph.beginTx()) { ResourceIterator<Node> result = graph.findNodes(LABEL1, "name", "Stefan"); assertEquals(asSet(node1, node2), asSet(result)); tx.success(); } }
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 shouldCorrectlyUpdateIndexesWhenChangingLabelsAndPropertyAtTheSameTime() throws Exception { // Given GraphDatabaseService beansAPI = dbRule.getGraphDatabaseService(); Node myNode = createNode(beansAPI, map("name", "Hawking"), LABEL1, LABEL2); createIndex(beansAPI, LABEL1, "name"); createIndex(beansAPI, LABEL2, "name"); createIndex(beansAPI, LABEL3, "name"); // When try (Transaction tx = beansAPI.beginTx()) { myNode.removeLabel(LABEL1); myNode.addLabel(LABEL3); myNode.setProperty("name", "Einstein"); tx.success(); } // Then assertThat(myNode, inTx(beansAPI, hasProperty("name").withValue("Einstein"))); assertThat(labels(myNode), containsOnly(LABEL2, LABEL3)); assertThat(findNodesByLabelAndProperty(LABEL1, "name", "Hawking", beansAPI), isEmpty()); assertThat(findNodesByLabelAndProperty(LABEL1, "name", "Einstein", beansAPI), isEmpty()); assertThat(findNodesByLabelAndProperty(LABEL2, "name", "Hawking", beansAPI), isEmpty()); assertThat( findNodesByLabelAndProperty(LABEL2, "name", "Einstein", beansAPI), containsOnly(myNode)); assertThat(findNodesByLabelAndProperty(LABEL3, "name", "Hawking", beansAPI), isEmpty()); assertThat( findNodesByLabelAndProperty(LABEL3, "name", "Einstein", beansAPI), containsOnly(myNode)); }
private CypherResult doExecuteQuery(String query, boolean canProfile) { long time = System.currentTimeMillis(); Transaction tx = gdb.beginTx(); javax.transaction.Transaction resumeTx; try { resumeTx = suspendTx(query); ExecutionResult result = canProfile ? executionEngine.profile(query) : executionEngine.execute(query); final Collection<Map<String, Object>> data = IteratorUtil.asCollection(result); time = System.currentTimeMillis() - time; resumeTransaction(resumeTx); CypherResult cypherResult = new CypherResult( result.columns(), data, result.getQueryStatistics(), time, canProfile ? result.executionPlanDescription() : null, prettify(query)); tx.success(); return cypherResult; } finally { tx.close(); } }
private static List<Double> getWeightVectorForClass( Map<String, List<LinkedHashMap<String, Object>>> documents, String key, List<Integer> featureIndexList, GraphDatabaseService db) { List<Double> weightVector; Transaction tx = db.beginTx(); // Get class id Long classId = db.findNodesByLabelAndProperty(DynamicLabel.label("Class"), "name", key) .iterator() .next() .getId(); // Get weight vector for class List<Long> longs = documents .get(key) .stream() .map(a -> ((Integer) a.get("feature")).longValue()) .collect(Collectors.toList()); weightVector = featureIndexList .stream() .map(i -> longs.contains(i.longValue()) ? tfidf(db, i.longValue(), classId) : 0.0) .collect(Collectors.toList()); tx.success(); tx.close(); return weightVector; }
@Test public void listing3_2_create_single_user() { usersAndMovies.createSingleUser(); try (Transaction tx = graphDb.beginTx()) { assertNotNull(graphDb.getNodeById(0)); tx.success(); } }
@Test public void listing3_4_create_realationships_between_users() { usersAndMovies.createSimpleRelationshipsBetweenUsers(); try (Transaction tx = graphDb.beginTx()) { assertTrue(usersAndMovies.user1.hasRelationship(MyRelationshipTypes.IS_FRIEND_OF)); tx.success(); } }
@Test public void shouldUseDynamicPropertiesToIndexANodeWhenAddedAlongsideExistingPropertiesInASeparateTransaction() throws Exception { // Given GraphDatabaseService beansAPI = dbRule.getGraphDatabaseAPI(); // When long id; { try (Transaction tx = beansAPI.beginTx()) { Node myNode = beansAPI.createNode(); id = myNode.getId(); myNode.setProperty("key0", true); myNode.setProperty("key1", true); tx.success(); } } { IndexDefinition indexDefinition; try (Transaction tx = beansAPI.beginTx()) { indexDefinition = beansAPI.schema().indexFor(LABEL1).on("key2").create(); tx.success(); } waitForIndex(beansAPI, indexDefinition); } Node myNode; { try (Transaction tx = beansAPI.beginTx()) { myNode = beansAPI.getNodeById(id); myNode.addLabel(LABEL1); myNode.setProperty("key2", LONG_STRING); myNode.setProperty("key3", LONG_STRING); tx.success(); } } // Then assertThat(myNode, inTx(beansAPI, hasProperty("key2").withValue(LONG_STRING))); assertThat(myNode, inTx(beansAPI, hasProperty("key3").withValue(LONG_STRING))); assertThat( findNodesByLabelAndProperty(LABEL1, "key2", LONG_STRING, beansAPI), containsOnly(myNode)); }
@Test public void deletedNewPropsShouldNotInfluenceEquality() { // bug test try (Transaction tx = database.beginTx()) { database.createNode().setProperty("accident", "dummy"); database.createNode(); tx.success(); } try (Transaction tx = database.beginTx()) { database.getNodeById(0).delete(); tx.success(); } String cypher = "CREATE (n)"; assertSameGraph(database, cypher); }
@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); }
@Test public void listing3_8_add_type_properties_to_all_nodes() { usersAndMovies.addTypePropertiesToNodes(); try (Transaction tx = graphDb.beginTx()) { assertEquals("User", usersAndMovies.user1.getProperty("type")); assertEquals("Movie", usersAndMovies.movie1.getProperty("type")); tx.success(); } }
@Test public void deletedRelationshipWithNewTypeShouldNotInfluenceEquality() { // bug test try (Transaction tx = database.beginTx()) { Node node1 = database.createNode(); Node node2 = database.createNode(); node1.createRelationshipTo(node2, DynamicRelationshipType.withName("ACCIDENT")); tx.success(); } try (Transaction tx = database.beginTx()) { GlobalGraphOperations.at(database).getAllRelationships().iterator().next().delete(); tx.success(); } String cypher = "CREATE (n), (m)"; assertSameGraph(database, cypher); }
@Test public void listing3_3_create_multiple_users() { usersAndMovies.createMultipleUsersInSingleTransaction(); try (Transaction tx = graphDb.beginTx()) { assertNotNull(graphDb.getNodeById(1)); assertNotNull(graphDb.getNodeById(2)); tx.success(); } }
@Test public void listing3_7_create_movies() { try (Transaction tx = graphDb.beginTx()) { assertNotNull(graphDb.getNodeById(3)); assertNotNull(graphDb.getNodeById(4)); assertNotNull(graphDb.getNodeById(5)); tx.success(); } }
@Test public void listing3_6_add_more_properties_to_user_nodes() { usersAndMovies.addMorePropertiesToUsers(); try (Transaction tx = graphDb.beginTx()) { assertTrue(usersAndMovies.user1.hasProperty("year_of_birth")); assertEquals(1982, usersAndMovies.user1.getProperty("year_of_birth")); tx.success(); } }
@Test public void listing3_5_add_properties_to_user_nodes() { usersAndMovies.addPropertiesToUserNodes(); try (Transaction tx = graphDb.beginTx()) { assertTrue(usersAndMovies.user1.hasProperty("name")); assertEquals("John Johnson", usersAndMovies.user1.getProperty("name")); tx.success(); } }
private Node createNode( GraphDatabaseService beansAPI, Map<String, Object> properties, Label... labels) { try (Transaction tx = beansAPI.beginTx()) { Node node = beansAPI.createNode(labels); for (Map.Entry<String, Object> property : properties.entrySet()) node.setProperty(property.getKey(), property.getValue()); tx.success(); return node; } }
@Test public void listing3_10_node_labels() { usersAndMovies.addLabelToMovies(); try (Transaction tx = graphDb.beginTx()) { ResourceIterable<Node> movies = GlobalGraphOperations.at(graphDb).getAllNodesWithLabel(DynamicLabel.label("MOVIES")); assertEquals(3, IteratorUtil.count(movies)); tx.success(); } }
private void assertCanCreateAndFind( GraphDatabaseService db, Label label, String propertyKey, Object value) { Node created = createNode(db, map(propertyKey, value), label); try (Transaction tx = db.beginTx()) { Node found = db.findNode(label, propertyKey, value); assertThat(found, equalTo(created)); found.delete(); tx.success(); } }
@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(expected = MultipleFoundException.class) public void shouldThrowWhenMulitpleResultsForSingleNode() throws Exception { // given GraphDatabaseService graph = dbRule.getGraphDatabaseService(); createIndex(graph, LABEL1, "name"); Node node1, node2; try (Transaction tx = graph.beginTx()) { node1 = graph.createNode(LABEL1); node1.setProperty("name", "Stefan"); node2 = graph.createNode(LABEL1); node2.setProperty("name", "Stefan"); tx.success(); } try (Transaction tx = graph.beginTx()) { graph.findNode(LABEL1, "name", "Stefan"); } }
@Test public void listing3_9_add_properties_to_relationships() { usersAndMovies.addPropertiesToRelationships(); try (Transaction tx = graphDb.beginTx()) { Relationship hasSeen = usersAndMovies.user1.getSingleRelationship( MyRelationshipTypes.HAS_SEEN, Direction.OUTGOING); assertEquals(5, hasSeen.getProperty("stars")); tx.success(); } }
/* This test is a bit interesting. It tests a case where we've got a property that sits in one * property block and the value is of a long type. So given that plus that there's an index for that * label/property, do an update that changes the long value into a value that requires two property blocks. * This is interesting because the transaction logic compares before/after views per property record and * not per node as a whole. * * In this case this change will be converted into one "add" and one "remove" property updates instead of * a single "change" property update. At the very basic level it's nice to test for this corner-case so * that the externally observed behavior is correct, even if this test doesn't assert anything about * the underlying add/remove vs. change internal details. */ @Test public void shouldInterpretPropertyAsChangedEvenIfPropertyMovesFromOneRecordToAnother() throws Exception { // GIVEN GraphDatabaseService beansAPI = dbRule.getGraphDatabaseAPI(); long smallValue = 10L, bigValue = 1L << 62; Node myNode; { try (Transaction tx = beansAPI.beginTx()) { myNode = beansAPI.createNode(LABEL1); myNode.setProperty("pad0", true); myNode.setProperty("pad1", true); myNode.setProperty("pad2", true); // Use a small long here which will only occupy one property block myNode.setProperty("key", smallValue); tx.success(); } } { IndexDefinition indexDefinition; try (Transaction tx = beansAPI.beginTx()) { indexDefinition = beansAPI.schema().indexFor(LABEL1).on("key").create(); tx.success(); } waitForIndex(beansAPI, indexDefinition); } // WHEN try (Transaction tx = beansAPI.beginTx()) { // A big long value which will occupy two property blocks myNode.setProperty("key", bigValue); tx.success(); } // THEN assertThat( findNodesByLabelAndProperty(LABEL1, "key", bigValue, beansAPI), containsOnly(myNode)); assertThat(findNodesByLabelAndProperty(LABEL1, "key", smallValue, beansAPI), isEmpty()); }
private static List<Node> getAllClasses(GraphDatabaseService db) { Transaction tx = db.beginTx(); // Get classes using Java API final List<Node> finalClasses = new ArrayList<>(); GlobalGraphOperations.at(db) .getAllNodesWithLabel(DynamicLabel.label("Class")) .forEach(a -> finalClasses.add(a)); tx.success(); tx.close(); return finalClasses.stream().map(a -> a).collect(Collectors.toList()); }
@Test public void clearGraphWithoutRuntimeShouldDeleteAllNodesAndRels() { try (Transaction tx = database.beginTx()) { String cypher = "CREATE " + "(blue {name:'Blue'})<-[:REL]-(red1 {name:'Red'})-[:REL]->(black1 {name:'Black'})-[:REL]->(green {name:'Green'})," + "(red2 {name:'Red'})-[:REL]->(black2 {name:'Black'})"; populateDatabase(cypher); tx.success(); } try (Transaction tx = database.beginTx()) { clearGraph(database); tx.success(); } try (Transaction tx = database.beginTx()) { assertEquals(0, count(at(database).getAllNodes())); tx.success(); } }
@Test public void listing3_11_node_labels_and_property() { try { usersAndMovies.addLabelToMovies(); } catch (Exception e) { // ignore if index already exist } try (Transaction tx = graphDb.beginTx()) { ResourceIterable<Node> movies = graphDb.findNodesByLabelAndProperty(DynamicLabel.label("MOVIES"), "name", "Fargo"); assertEquals(1, IteratorUtil.count(movies)); tx.success(); } }
private static Map<String, List<LinkedHashMap<String, Object>>> getFeaturesForAllClasses( GraphDatabaseService db) { List<Node> classes = getAllClasses(db); Map<String, List<LinkedHashMap<String, Object>>> featureMap = new HashMap<>(); Transaction tx = db.beginTx(); for (Node thisClass : classes) { featureMap.put((String) thisClass.getProperty("name"), getFeaturesForClass(db, thisClass)); } tx.success(); tx.close(); return featureMap; }
/** {@inheritDoc} */ @Override public NodeBasedContext createInitialContext(GraphDatabaseService database) { Node node; try (Transaction tx = database.beginTx()) { initializeSelectorIfNeeded(null, database); node = selector.selectNode(database); tx.success(); } if (node == null) { LOG.warn( "RecommendationModule did not find a node to start with. There are no nodes matching the configuration."); return null; } LOG.info("Starting RecommendationModule with node " + node); return new NodeBasedContext(node.getId()); }
@Test public void createdNodeShouldShowUpInIndexQuery() throws Exception { // GIVEN GraphDatabaseService beansAPI = dbRule.getGraphDatabaseService(); createIndex(beansAPI, LABEL1, "name"); createNode(beansAPI, map("name", "Mattias"), LABEL1); // WHEN Transaction tx = beansAPI.beginTx(); long sizeBeforeDelete = count(beansAPI.findNodes(LABEL1, "name", "Mattias")); createNode(beansAPI, map("name", "Mattias"), LABEL1); long sizeAfterDelete = count(beansAPI.findNodes(LABEL1, "name", "Mattias")); tx.close(); // THEN assertThat(sizeBeforeDelete, equalTo(1l)); assertThat(sizeAfterDelete, equalTo(2l)); }