public void visit(SpatialIndexVisitor visitor, Node indexNode) { if (!visitor.needsToVisit(getIndexNodeEnvelope(indexNode))) { return; } try (Transaction tx = database.beginTx()) { if (indexNode.hasRelationship(RTreeRelationshipTypes.RTREE_CHILD, Direction.OUTGOING)) { // Node is not a leaf for (Relationship rel : indexNode.getRelationships(RTreeRelationshipTypes.RTREE_CHILD, Direction.OUTGOING)) { Node child = rel.getEndNode(); // collect children results visit(visitor, child); } } else if (indexNode.hasRelationship( RTreeRelationshipTypes.RTREE_REFERENCE, Direction.OUTGOING)) { // Node is a leaf for (Relationship rel : indexNode.getRelationships( RTreeRelationshipTypes.RTREE_REFERENCE, Direction.OUTGOING)) { visitor.onIndexReference(rel.getEndNode()); } } tx.success(); } }
private void visitInTx(SpatialIndexVisitor visitor, Long indexNodeId) { Node indexNode = database.getNodeById(indexNodeId); if (!visitor.needsToVisit(getIndexNodeEnvelope(indexNode))) { return; } if (indexNode.hasRelationship(RTreeRelationshipTypes.RTREE_CHILD, Direction.OUTGOING)) { // Node is not a leaf // collect children List<Long> children = new ArrayList<Long>(); for (Relationship rel : indexNode.getRelationships(RTreeRelationshipTypes.RTREE_CHILD, Direction.OUTGOING)) { children.add(rel.getEndNode().getId()); } // visit children for (Long child : children) { visitInTx(visitor, child); } } else if (indexNode.hasRelationship( RTreeRelationshipTypes.RTREE_REFERENCE, Direction.OUTGOING)) { // Node is a leaf try (Transaction tx = database.beginTx()) { for (Relationship rel : indexNode.getRelationships( RTreeRelationshipTypes.RTREE_REFERENCE, Direction.OUTGOING)) { visitor.onIndexReference(rel.getEndNode()); } tx.success(); } } }
@Test public void testSimple3() { Node node1 = getGraphDb().createNode(); Node node2 = getGraphDb().createNode(); for (int i = 0; i < 1; i++) { node1.createRelationshipTo(node2, MyRelTypes.TEST); node1.createRelationshipTo(node2, MyRelTypes.TEST_TRAVERSAL); node1.createRelationshipTo(node2, MyRelTypes.TEST2); } allGetRelationshipMethods2(node1, Direction.OUTGOING); allGetRelationshipMethods2(node2, Direction.INCOMING); newTransaction(); allGetRelationshipMethods2(node1, Direction.OUTGOING); allGetRelationshipMethods2(node2, Direction.INCOMING); node1.getRelationships(MyRelTypes.TEST, Direction.OUTGOING).iterator().next().delete(); node1 .getRelationships(MyRelTypes.TEST_TRAVERSAL, Direction.OUTGOING) .iterator() .next() .delete(); node1.getRelationships(MyRelTypes.TEST2, Direction.OUTGOING).iterator().next().delete(); node1.createRelationshipTo(node2, MyRelTypes.TEST); node1.createRelationshipTo(node2, MyRelTypes.TEST_TRAVERSAL); node1.createRelationshipTo(node2, MyRelTypes.TEST2); allGetRelationshipMethods2(node1, Direction.OUTGOING); allGetRelationshipMethods2(node2, Direction.INCOMING); newTransaction(); allGetRelationshipMethods2(node1, Direction.OUTGOING); allGetRelationshipMethods2(node2, Direction.INCOMING); for (Relationship rel : node1.getRelationships()) { rel.delete(); } node1.delete(); node2.delete(); }
/* * It will remove a property from an embedded node if it exists. * After deleting the property, if the node does not have any more properties and relationships (except for an incoming one), * it will delete the embedded node as well. */ private void removePropertyForEmbedded(Node embeddedNode, String[] embeddedColumnSplit, int i) { if (i == embeddedColumnSplit.length - 1) { // Property String property = embeddedColumnSplit[embeddedColumnSplit.length - 1]; if (embeddedNode.hasProperty(property)) { embeddedNode.removeProperty(property); } } else { Iterator<Relationship> iterator = embeddedNode .getRelationships(Direction.OUTGOING, withName(embeddedColumnSplit[i])) .iterator(); if (iterator.hasNext()) { removePropertyForEmbedded(iterator.next().getEndNode(), embeddedColumnSplit, i + 1); } } if (!embeddedNode.getPropertyKeys().iterator().hasNext()) { // Node without properties Iterator<Relationship> iterator = embeddedNode.getRelationships().iterator(); if (iterator.hasNext()) { Relationship relationship = iterator.next(); if (!iterator.hasNext()) { // Node with only one relationship and no properties, // we can remove it: // It means we have removed all the properties from the embedded node // and it is NOT an intermediate node like // (entity) --> (embedded1) --> (embedded2) relationship.delete(); embeddedNode.delete(); } } } }
@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(); }
private Iterator<Relationship> getRelationshipIterator( PatternNode fromNode, Node currentNode, PatternRelationship pRel) { Iterator<Relationship> relItr = null; if (pRel.anyRelType()) { relItr = currentNode.getRelationships(pRel.getDirectionFrom(fromNode)).iterator(); } else { relItr = currentNode.getRelationships(pRel.getType(), pRel.getDirectionFrom(fromNode)).iterator(); } return relItr; }
/** * Fetch relationships for the given source node. * * @param sourceNode * @param relType can be null * @param dir * @return a list of relationships * @throws FrameworkException */ public List<AbstractRelationship> execute( AbstractNode sourceNode, RelationshipType relType, Direction dir) throws FrameworkException { RelationshipFactory factory = new RelationshipFactory(securityContext); List<AbstractRelationship> result = new LinkedList<AbstractRelationship>(); Node node = sourceNode.getNode(); Iterable<Relationship> rels; if (node == null) { return Collections.EMPTY_LIST; } if (relType != null) { rels = node.getRelationships(relType, dir); } else { rels = node.getRelationships(dir); } try { for (Relationship r : rels) { result.add(factory.instantiate(r)); } } catch (RuntimeException e) { logger.log(Level.WARNING, "Exception occured: ", e.getMessage()); /** * ********* FIXME * * <p>Here an exception occurs: * * <p>org.neo4j.kernel.impl.nioneo.store.InvalidRecordException: Node[5] is neither * firstNode[37781] nor secondNode[37782] for Relationship[188125] at * org.neo4j.kernel.impl.nioneo.xa.ReadTransaction.getMoreRelationships(ReadTransaction.java:131) * at * org.neo4j.kernel.impl.nioneo.xa.NioNeoDbPersistenceSource$ReadOnlyResourceConnection.getMoreRelationships(NioNeoDbPersistenceSource.java:280) * at * org.neo4j.kernel.impl.persistence.PersistenceManager.getMoreRelationships(PersistenceManager.java:100) * at org.neo4j.kernel.impl.core.NodeManager.getMoreRelationships(NodeManager.java:585) at * org.neo4j.kernel.impl.core.NodeImpl.getMoreRelationships(NodeImpl.java:358) at * org.neo4j.kernel.impl.core.IntArrayIterator.hasNext(IntArrayIterator.java:115) */ } return result; }
@Test public void testRelCountInSameTx() { Node node1 = getGraphDb().createNode(); Node node2 = getGraphDb().createNode(); Relationship rel = node1.createRelationshipTo(node2, MyRelTypes.TEST); assertEquals(1, getRelationshipArray(node1.getRelationships()).length); assertEquals(1, getRelationshipArray(node2.getRelationships()).length); rel.delete(); assertEquals(0, getRelationshipArray(node1.getRelationships()).length); assertEquals(0, getRelationshipArray(node2.getRelationships()).length); node1.delete(); node2.delete(); }
@Test public void testRelationshipCreateAndDelete() { Node node1 = getGraphDb().createNode(); Node node2 = getGraphDb().createNode(); Relationship relationship = node1.createRelationshipTo(node2, MyRelTypes.TEST); Relationship relArray1[] = getRelationshipArray(node1.getRelationships()); Relationship relArray2[] = getRelationshipArray(node2.getRelationships()); assertEquals(1, relArray1.length); assertEquals(relationship, relArray1[0]); assertEquals(1, relArray2.length); assertEquals(relationship, relArray2[0]); relArray1 = getRelationshipArray(node1.getRelationships(MyRelTypes.TEST)); assertEquals(1, relArray1.length); assertEquals(relationship, relArray1[0]); relArray2 = getRelationshipArray(node2.getRelationships(MyRelTypes.TEST)); assertEquals(1, relArray2.length); assertEquals(relationship, relArray2[0]); relArray1 = getRelationshipArray(node1.getRelationships(MyRelTypes.TEST, Direction.OUTGOING)); assertEquals(1, relArray1.length); relArray2 = getRelationshipArray(node2.getRelationships(MyRelTypes.TEST, Direction.INCOMING)); assertEquals(1, relArray2.length); relArray1 = getRelationshipArray(node1.getRelationships(MyRelTypes.TEST, Direction.INCOMING)); assertEquals(0, relArray1.length); relArray2 = getRelationshipArray(node2.getRelationships(MyRelTypes.TEST, Direction.OUTGOING)); assertEquals(0, relArray2.length); relationship.delete(); node2.delete(); node1.delete(); }
@Test public void shouldLoadAllRelationships() throws Exception { // GIVEN GraphDatabaseAPI db = getGraphDbAPI(); Node node; try (Transaction tx = db.beginTx()) { node = db.createNode(); for (int i = 0; i < 112; i++) { node.createRelationshipTo(db.createNode(), MyRelTypes.TEST); db.createNode().createRelationshipTo(node, MyRelTypes.TEST); } tx.success(); } // WHEN db.getDependencyResolver().resolveDependency(NodeManager.class).clearCache(); int one, two; try (Transaction tx = db.beginTx()) { one = count(node.getRelationships(MyRelTypes.TEST, Direction.OUTGOING)); two = count(node.getRelationships(MyRelTypes.TEST, Direction.OUTGOING)); tx.success(); } // THEN assertEquals(two, one); }
@Test public void deleteRelsWithCommitInMiddle() throws Exception { Node node = getGraphDb().createNode(); Node otherNode = getGraphDb().createNode(); RelationshipType[] types = new RelationshipType[] {withName("r1"), withName("r2"), withName("r3"), withName("r4")}; int count = 30; // 30*4 > 100 (rel grabSize) for (int i = 0; i < types.length * count; i++) { node.createRelationshipTo(otherNode, types[i % types.length]); } newTransaction(); clearCache(); int delCount = 0; int loopCount = 0; while (delCount < count) { loopCount++; for (Relationship rel : node.getRelationships(types[1])) { rel.delete(); if (++delCount == count / 2) { newTransaction(); } } } assertEquals(1, loopCount); assertEquals(count, delCount); }
@Override public List<String> completionCandidates(String partOfLine, Session session) { String lastWord = TextUtil.lastWordOrQuoteOf(partOfLine, false); if (lastWord.startsWith("-")) { return super.completionCandidates(partOfLine, session); } try { TreeSet<String> result = new TreeSet<String>(); NodeOrRelationship current = getCurrent(session); if (current.isNode()) { // TODO Check if -r is supplied Node node = current.asNode(); for (Node otherNode : RelationshipToNodeIterable.wrap(node.getRelationships(), node)) { long otherNodeId = otherNode.getId(); String title = findTitle(getServer(), session, otherNode); if (title != null) { if (!result.contains(title)) { maybeAddCompletionCandidate(result, title + "," + otherNodeId, lastWord); } } maybeAddCompletionCandidate(result, "" + otherNodeId, lastWord); } } else { maybeAddCompletionCandidate(result, START_ALIAS, lastWord); maybeAddCompletionCandidate(result, END_ALIAS, lastWord); Relationship rel = current.asRelationship(); maybeAddCompletionCandidate(result, "" + rel.getStartNode().getId(), lastWord); maybeAddCompletionCandidate(result, "" + rel.getEndNode().getId(), lastWord); } return new ArrayList<String>(result); } catch (ShellException e) { e.printStackTrace(); return super.completionCandidates(partOfLine, session); } }
private boolean isConnected(NodeOrRelationship current, TypedId newId) throws ShellException { if (current.isNode()) { Node currentNode = current.asNode(); for (Relationship rel : currentNode.getRelationships()) { if (newId.isNode()) { if (rel.getOtherNode(currentNode).getId() == newId.getId()) { return true; } } else { if (rel.getId() == newId.getId()) { return true; } } } } else { if (newId.isRelationship()) { return false; } Relationship relationship = current.asRelationship(); if (relationship.getStartNode().getId() == newId.getId() || relationship.getEndNode().getId() == newId.getId()) { return true; } } return false; }
@Test public void testRelationshipCahinIterator() { Node node1 = getGraphDb().createNode(); Node node2 = getGraphDb().createNode(); Relationship rels[] = new Relationship[100]; for (int i = 0; i < rels.length; i++) { if (i < 50) { rels[i] = node1.createRelationshipTo(node2, MyRelTypes.TEST); } else { rels[i] = node2.createRelationshipTo(node1, MyRelTypes.TEST); } } newTransaction(); getNodeManager().clearCache(); Iterable<Relationship> relIterable = node1.getRelationships(); for (Relationship rel : rels) { rel.delete(); } newTransaction(); for (Relationship rel : relIterable) { System.out.println(rel); } node1.delete(); node2.delete(); }
private void appendRelationships(PrintWriter out) { for (Node node : graph.getNodes()) { for (Relationship rel : node.getRelationships(Direction.OUTGOING)) { appendRelationship(out, rel); } } }
/** * Removes all nodes with non-valid resource classes from the graph. * * @param docGraph * @param validResourceClasses */ private void preProcessGraph(DocGraph docGraph, Set<String> validResourceClasses) { log.info(String.format("Preprocessing DocGraph[%d]", docGraph.getId())); Node n; int cnt = 0; try (Transaction tx = graphDB.beginTx()) { for (Long nodeId : docGraph.getNodes()) { n = graphDB.getNodeById(nodeId); // node's class is resource class and it's not in the valid set if (n.hasProperty(Constants.NODE_SUPER_CLASS_KEY) && n.getProperty(Constants.NODE_SUPER_CLASS_KEY) .equals(Constants.NODE_SUPER_CLASS_RESOURCE_VALUE) && !validResourceClasses.contains(getNodeClass(n))) { try (Transaction innerTx = graphDB.beginTx()) { log.info("Deleting " + n); for (Relationship e : n.getRelationships()) { e.delete(); } n.delete(); innerTx.success(); cnt++; } } } tx.success(); } log.info( String.format("Preprocessing removed %d nodes from DocGraph[%d]", cnt, docGraph.getId())); }
public void delete(ConstructionZoneNode zone) { Node n = zone.getNode(); for (Relationship rel : n.getRelationships()) { rel.delete(); } n.delete(); }
private void removeTupleOperation( EntityKey entityKey, Node node, TupleOperation operation, TupleContext tupleContext, Set<String> processedAssociationRoles) { if (!tupleContext.getTupleTypeContext().isPartOfAssociation(operation.getColumn())) { if (isPartOfRegularEmbedded(entityKey.getColumnNames(), operation.getColumn())) { // Embedded node String[] split = split(operation.getColumn()); removePropertyForEmbedded(node, split, 0); } else if (node.hasProperty(operation.getColumn())) { node.removeProperty(operation.getColumn()); } } // if the column represents a to-one association, remove the relationship else { String associationRole = tupleContext.getTupleTypeContext().getRole(operation.getColumn()); if (!processedAssociationRoles.contains(associationRole)) { Iterator<Relationship> relationships = node.getRelationships(withName(associationRole)).iterator(); if (relationships.hasNext()) { relationships.next().delete(); } } } }
@Test public void removeNodesWithARelation() { int originalNodeCount = countNodesOf(graphDb); int removedNodeCount = 0; Transaction tx = graphDb.beginTx(); try { Set<Node> toRemove = new HashSet<Node>(); for (Node node : graphDb.getAllNodes()) { for (Relationship relationship : node.getRelationships(RelationType.ON)) { toRemove.add(relationship.getStartNode()); toRemove.add(relationship.getEndNode()); relationship.delete(); } } for (Node node : toRemove) { node.delete(); removedNodeCount++; } tx.success(); } finally { tx.finish(); } int finalNodeCount = countNodesOf(graphDb); assertEquals( Integer.valueOf(originalNodeCount), Integer.valueOf(finalNodeCount + removedNodeCount)); }
private void putOneToOneAssociation( Tuple tuple, Node node, TupleOperation operation, TupleContext tupleContext, Set<String> processedAssociationRoles) { String associationRole = tupleContext.getTupleTypeContext().getRole(operation.getColumn()); if (!processedAssociationRoles.contains(associationRole)) { processedAssociationRoles.add(associationRole); EntityKey targetKey = getEntityKey( tuple, tupleContext .getTupleTypeContext() .getAssociatedEntityKeyMetadata(operation.getColumn())); // delete the previous relationship if there is one; for a to-one association, the // relationship won't have any // properties, so the type is uniquely identifying it Iterator<Relationship> relationships = node.getRelationships(withName(associationRole)).iterator(); if (relationships.hasNext()) { relationships.next().delete(); } // create a new relationship Node targetNode = entityQueries .get(targetKey.getMetadata()) .findEntity(dataBase, targetKey.getColumnValues()); node.createRelationshipTo(targetNode, withName(associationRole)); } }
protected List<Node> getRelatedNodes(Node startNode, String type, Direction direction) { List<Node> result = new ArrayList<Node>(); for (Relationship relationship : startNode.getRelationships(DynamicRelationshipType.withName(type), direction)) { result.add(relationship.getOtherNode(startNode)); } return result; }
@Test public void createAndClearCacheBeforeCommit() { Node node = getGraphDb().createNode(); clearCache(); node.createRelationshipTo(getGraphDb().createNode(), TEST); clearCache(); assertEquals(1, IteratorUtil.count(node.getRelationships())); }
@Test public void testCreateRelationshipWithCommitts() // throws NotFoundException { Node n1 = getGraphDb().createNode(); newTransaction(); clearCache(); n1 = getGraphDb().getNodeById((int) n1.getId()); Node n2 = getGraphDb().createNode(); n1.createRelationshipTo(n2, MyRelTypes.TEST); newTransaction(); Relationship[] relArray = getRelationshipArray(n1.getRelationships()); assertEquals(1, relArray.length); relArray = getRelationshipArray(n1.getRelationships()); relArray[0].delete(); n1.delete(); n2.delete(); }
private void countRelationships(Node node) { Transaction transaction = db.beginTx(); try { count(node.getRelationships()); } finally { transaction.finish(); } }
private Node chooseSubTree(Node parentIndexNode, Node geomRootNode) { // children that can contain the new geometry List<Node> indexNodes = new ArrayList<Node>(); // pick the child that contains the new geometry bounding box Iterable<Relationship> relationships = parentIndexNode.getRelationships(RTreeRelationshipTypes.RTREE_CHILD, Direction.OUTGOING); for (Relationship relation : relationships) { Node indexNode = relation.getEndNode(); if (getIndexNodeEnvelope(indexNode).contains(getLeafNodeEnvelope(geomRootNode))) { indexNodes.add(indexNode); } } if (indexNodes.size() > 1) { return chooseIndexNodeWithSmallestArea(indexNodes); } else if (indexNodes.size() == 1) { return indexNodes.get(0); } // pick the child that needs the minimum enlargement to include the new geometry double minimumEnlargement = Double.POSITIVE_INFINITY; relationships = parentIndexNode.getRelationships(RTreeRelationshipTypes.RTREE_CHILD, Direction.OUTGOING); for (Relationship relation : relationships) { Node indexNode = relation.getEndNode(); double enlargementNeeded = getAreaEnlargement(indexNode, geomRootNode); if (enlargementNeeded < minimumEnlargement) { indexNodes.clear(); indexNodes.add(indexNode); minimumEnlargement = enlargementNeeded; } else if (enlargementNeeded == minimumEnlargement) { indexNodes.add(indexNode); } } if (indexNodes.size() > 1) { return chooseIndexNodeWithSmallestArea(indexNodes); } else if (indexNodes.size() == 1) { return indexNodes.get(0); } else { // this shouldn't happen throw new RuntimeException("No IndexNode found for new geometry"); } }
@Test @Transactional public void shouldGetDirectRelationshipForTypeAndDirection() throws Exception { assertSingleResult( "rel1", neo4jTemplate .convert(referenceNode.getRelationships(KNOWS, Direction.OUTGOING)) .to(String.class, new RelationshipNameConverter())); }
@Test @Transactional public void shouldGetDirectRelationship() throws Exception { assertSingleResult( "rel1", neo4jTemplate .convert(referenceNode.getRelationships(DynamicRelationshipType.withName("knows"))) .to(String.class, new RelationshipNameConverter())); }
public void removeVertex(final Vertex vertex) { this.autoStartTransaction(); final Node node = ((Neo4jVertex) vertex).getRawVertex(); for (final Relationship relationship : node.getRelationships(org.neo4j.graphdb.Direction.BOTH)) { relationship.delete(); } node.delete(); }
private boolean isSuggestionRelationshipPresent(final Node node, final Node otherNode) { for (final Relationship relationship : node.getRelationships(ConnectionType.SUGGESTED, Direction.BOTH)) { if (relationship.getOtherNode(node).equals(otherNode)) { return true; } } return false; }
private int loadRelationships(Node node, RelationshipType type, Direction direction) { int count; try (Transaction tx = db.beginTx()) { count = count(node.getRelationships(type, direction)); int pCount = node.getDegree(type, direction); assertEquals(count, pCount); tx.success(); } return count; }