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 testGetOrCreateRelationship() throws Exception { final Transaction tx = gdb.beginTx(); final Node david = graphDatabase.createNode(map("name", "David")); final Node michael = graphDatabase.createNode(map("name", "Michael")); final Relationship rel1 = graphDatabase.getOrCreateRelationship( "knows", "whom", "david_michael", david, michael, "KNOWS", map("whom", "david_michael")); final Relationship rel2 = graphDatabase.getOrCreateRelationship( "knows", "whom", "david_michael", david, michael, "KNOWS", map("whom", "david_michael")); assertEquals("david_michael", rel1.getProperty("whom")); assertEquals("KNOWS", rel1.getType().name()); assertEquals(david, rel1.getStartNode()); assertEquals(michael, rel1.getEndNode()); assertEquals(rel1, rel2); assertEquals( rel1, gdb.index().forRelationships("knows").get("whom", "david_michael").getSingle()); tx.success(); tx.finish(); }
private Object toJsonCompatible(Object value) { if (value instanceof Node) { final Node node = (Node) value; final Map<String, Object> result = SubGraph.toMap(node); result.put("_id", node.getId()); return result; } if (value instanceof Relationship) { final Relationship relationship = (Relationship) value; final Map<String, Object> result = SubGraph.toMap(relationship); result.put("_id", relationship.getId()); result.put("_start", relationship.getStartNode().getId()); result.put("_end", relationship.getEndNode().getId()); result.put("_type", relationship.getType().name()); return result; } if (value instanceof Iterable) { final List<Object> result = new ArrayList<Object>(); for (Object inner : (Iterable) value) { result.add(toJsonCompatible(inner)); } return result; } return value; }
private void putAssociationOperation( Association association, AssociationKey associationKey, AssociationOperation action, AssociatedEntityKeyMetadata associatedEntityKeyMetadata) { Relationship relationship = associationQueries .get(associationKey.getMetadata()) .findRelationship(dataBase, associationKey, action.getKey()); if (relationship != null) { for (String relationshipProperty : associationKey.getMetadata().getRowKeyIndexColumnNames()) { relationship.setProperty(relationshipProperty, action.getValue().get(relationshipProperty)); } for (String column : associationKey .getMetadata() .getColumnsWithoutKeyColumns(action.getValue().getColumnNames())) { if (!isRowKeyColumn(associationKey.getMetadata(), column)) { relationship.getEndNode().setProperty(column, action.getValue().get(column)); } } GraphLogger.log("Updated relationship: %1$s", relationship); } else { relationship = createRelationship(associationKey, action.getValue(), associatedEntityKeyMetadata); GraphLogger.log("Created relationship: %1$s", relationship); } }
@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)); }
@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; }
TreeNode getAfterSubTree() { Relationship subTreeRel = getEndNode().getSingleRelationship(RelTypes.SUB_TREE, Direction.OUTGOING); if (subTreeRel != null) { return new TreeNode(getBTree(), subTreeRel.getEndNode()); } return null; }
public boolean accept(Path item) { for (Relationship rel : item.endNode().getRelationships(Direction.OUTGOING)) { if (rel.getEndNode().equals(node)) { return true; } } return false; }
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"); } }
public Relationship _findRelationship( Iterable<Relationship> rels, long nodeId, Direction direction) { for (Relationship rel : rels) { switch (direction) { case INCOMING: if (rel.getStartNode().getId() == nodeId) return rel; break; case OUTGOING: if (rel.getEndNode().getId() == nodeId) return rel; case BOTH: if (rel.getStartNode().getId() == nodeId || rel.getEndNode().getId() == nodeId) return rel; } } return null; }
public static String withArrows(Relationship relationship, String displayName, Node leftNode) { if (relationship.getStartNode().equals(leftNode)) { return "-" + displayName + "->"; } else if (relationship.getEndNode().equals(leftNode)) { return "<-" + displayName + "-"; } throw new IllegalArgumentException( leftNode + " is neither start nor end node to " + relationship); }
private void appendRelationship(PrintWriter out, Relationship rel) { out.print("create "); out.print(identifier(rel.getStartNode())); out.print("-[:"); out.print(quote(rel.getType().name())); formatProperties(out, rel); out.print("]->"); out.print(identifier(rel.getEndNode())); out.println(); }
@Test public void testTraverseToNeighbour() { final Relationship rel = relationship(); final TraversalDescription traversalDescription = RestTraversal.description().maxDepth(1).breadthFirst(); System.out.println("traversalDescription = " + traversalDescription); final Traverser traverser = traversalDescription.traverse(rel.getStartNode()); final Iterable<Node> nodes = traverser.nodes(); Assert.assertEquals(rel.getEndNode(), nodes.iterator().next()); }
private Relationship findMemberRelationshipTo(Principal principal) { for (Relationship rel : principal .getUnderlyingNode() .getRelationships(SecurityRelationshipTypes.MEMBER, Direction.OUTGOING)) { if (rel.getEndNode().equals(getUnderlyingNode())) { return rel; } } return null; }
static boolean matchDirection(Direction dir, Node start, Relationship rel) { switch (dir) { case INCOMING: return rel.getEndNode().equals(start); case OUTGOING: return rel.getStartNode().equals(start); case BOTH: return true; } return true; }
@Test @Transactional public void shouldCreateRelationshipWithProperty() throws Exception { Relationship relationship = neo4jTemplate.createRelationshipBetween(referenceNode, node1, "has", map("name", "rel2")); assertNotNull(relationship); assertEquals(referenceNode, relationship.getStartNode()); assertEquals(node1, relationship.getEndNode()); assertEquals(HAS.name(), relationship.getType().name()); assertEquals("rel2", relationship.getProperty("name", "not set")); }
public String sumNodeContents(Node node) { StringBuffer result = new StringBuffer(); for (Relationship rel : node.getRelationships()) { if (rel.getStartNode().equals(node)) { result.append( rel.getStartNode() + " ---[" + rel.getType().name() + "]--> " + rel.getEndNode()); } else { result.append( rel.getStartNode() + " <--[" + rel.getType().name() + "]--- " + rel.getEndNode()); } result.append("\n"); } for (String key : node.getPropertyKeys()) { for (Object value : propertyValueAsArray(node.getProperty(key))) { result.append("*" + key + "=[" + value + "]"); result.append("\n"); } } return result.toString(); }
private synchronized Map<String, Layer> getLayerMap() { if (layers == null) { layers = new LinkedHashMap<String, Layer>(); layers.put(getName(), this); for (Relationship rel : layerNode.getRelationships(SpatialRelationshipTypes.LAYER_CONFIG, Direction.OUTGOING)) { DynamicLayerConfig config = new DynamicLayerConfig(this, rel.getEndNode()); layers.put(config.getName(), config); } } return layers; }
private void assertPathIsCorrect(Path path) { Node a = node("A"); Relationship to1 = a.getRelationships(Direction.OUTGOING).iterator().next(); Node b = to1.getEndNode(); Relationship to2 = b.getRelationships(Direction.OUTGOING).iterator().next(); Node c = to2.getEndNode(); Relationship to3 = c.getRelationships(Direction.OUTGOING).iterator().next(); Node d = to3.getEndNode(); Relationship to4 = d.getRelationships(Direction.OUTGOING).iterator().next(); Node e = to4.getEndNode(); assertEquals((Integer) 4, (Integer) path.length()); assertEquals(a, path.startNode()); assertEquals(e, path.endNode()); assertEquals(to4, path.lastRelationship()); assertContainsInOrder(path, a, to1, b, to2, c, to3, d, to4, e); assertContainsInOrder(path.nodes(), a, b, c, d, e); assertContainsInOrder(path.relationships(), to1, to2, to3, to4); assertContainsInOrder(path.reverseNodes(), e, d, c, b, a); assertContainsInOrder(path.reverseRelationships(), to4, to3, to2, to1); }
@Test public void reverseRelationships() throws Exception { Path path = first(traversal().evaluator(atDepth(0)).traverse(a)); assertFalse(path.reverseRelationships().iterator().hasNext()); path = first(traversal().evaluator(atDepth(4)).traverse(a)); Node[] expectedNodes = new Node[] {e, d, c, b, a}; int index = 0; for (Relationship rel : path.reverseRelationships()) assertEquals("For index " + index, expectedNodes[index++], rel.getEndNode()); assertEquals(4, index); }
static Edge addEdge(Graph graph, Relationship relationship) { Edge edge = graph.getEdge(relationship.getId()); if (null == edge) { Vertex outVertex = addNode(graph, relationship.getStartNode()); Vertex inVertex = addNode(graph, relationship.getEndNode()); String label = relationship.getType().name(); // TODO #152 add CurieUtil to resolve IRI to Curie edge = graph.addEdge(relationship.getId(), outVertex, inVertex, label); copyProperties(relationship, edge); } return edge; }
@Test public void testPun() { Node i = getNode("http://example.org/i"); Node j = getNode("http://example.org/j"); Node k = getNode("http://example.org/k"); RelationshipType p = DynamicRelationshipType.withName("p"); Relationship relationship = getOnlyElement(GraphUtil.getRelationships(i, j, p)); assertThat("OPE edge should start with the subject.", relationship.getStartNode(), is(i)); assertThat("OPE edge should end with the target.", relationship.getEndNode(), is(j)); relationship = getOnlyElement(GraphUtil.getRelationships(i, k, OwlRelationships.RDFS_SUBCLASS_OF)); assertThat("Subclass edge should start with i.", relationship.getStartNode(), is(i)); assertThat("Subclass edge should end with k.", relationship.getEndNode(), is(k)); assertThat( "i is both a class an a named individual", i.getLabels(), is( IsIterableContainingInAnyOrder.containsInAnyOrder( OwlLabels.OWL_CLASS, OwlLabels.OWL_NAMED_INDIVIDUAL))); }
@Override public void removeAll(final boolean deleteGeomNodes, final Listener monitor) { Node indexRoot = getIndexRoot(); monitor.begin(count()); try { // delete all geometry nodes visitInTx( new SpatialIndexVisitor() { public boolean needsToVisit(Envelope indexNodeEnvelope) { return true; } public void onIndexReference(Node geomNode) { geomNode .getSingleRelationship(RTreeRelationshipTypes.RTREE_REFERENCE, Direction.INCOMING) .delete(); if (deleteGeomNodes) { deleteNode(geomNode); } monitor.worked(1); } }, indexRoot.getId()); } finally { monitor.done(); } try (Transaction tx = database.beginTx()) { // delete index root relationship indexRoot .getSingleRelationship(RTreeRelationshipTypes.RTREE_ROOT, Direction.INCOMING) .delete(); // delete tree deleteRecursivelySubtree(indexRoot); // delete tree metadata Relationship metadataNodeRelationship = getRootNode() .getSingleRelationship(RTreeRelationshipTypes.RTREE_METADATA, Direction.OUTGOING); Node metadataNode = metadataNodeRelationship.getEndNode(); metadataNodeRelationship.delete(); metadataNode.delete(); tx.success(); } countSaved = false; totalGeometryCount = 0; }
public void testNeo4jRaw() throws Exception { double totalTime = 0.0d; Graph graph = graphTest.getGraphInstance(); GraphMLReader.inputGraph(graph, GraphMLReader.class.getResourceAsStream("graph-example-2.xml")); graph.shutdown(); for (int i = 0; i < TOTAL_RUNS; i++) { graph = graphTest.getGraphInstance(); GraphDatabaseService neo4j = ((Neo4jGraph) graph).getRawGraph(); int counter = 0; this.stopWatch(); for (final Node node : neo4j.getAllNodes()) { counter++; for (final Relationship relationship : node.getRelationships(Direction.OUTGOING)) { counter++; final Node node2 = relationship.getEndNode(); counter++; for (final Relationship relationship2 : node2.getRelationships(Direction.OUTGOING)) { counter++; final Node node3 = relationship2.getEndNode(); counter++; for (final Relationship relationship3 : node3.getRelationships(Direction.OUTGOING)) { counter++; relationship3.getEndNode(); counter++; } } } } double currentTime = this.stopWatch(); totalTime = totalTime + currentTime; BaseTest.printPerformance( neo4j.toString(), counter, "Neo4j raw elements touched", currentTime); graph.shutdown(); } BaseTest.printPerformance( "Neo4jRaw", 1, "Neo4j Raw experiment average", totalTime / (double) TOTAL_RUNS); }
/** * Default constructor * * @param relationship the relation */ public DotEdge(Relationship relationship) { Node startNode = relationship.getStartNode(); this.startId = ShapeIdPrefix.fromNode(startNode) + startNode.getId(); Node endNode = relationship.getEndNode(); this.endId = ShapeIdPrefix.fromNode(endNode) + endNode.getId(); if (NodeUtils.isScoperelation(relationship.getType())) { this.edgeStyle = EdgeStyle.dotted; } else { this.edgeStyle = EdgeStyle.solid; } this.label = relationship.getType().toString(); }
@Override public T getTargetNode() { try { NodeFactory<T> nodeFactory = new NodeFactory<>(securityContext); return nodeFactory.instantiate(dbRelationship.getEndNode()); } catch (FrameworkException t) { // ignore FrameworkException but let NotInTransactionException pass } return null; }
@Test public void testDirectedRelationship() { Node node1 = getGraphDb().createNode(); Node node2 = getGraphDb().createNode(); Relationship rel2 = node1.createRelationshipTo(node2, MyRelTypes.TEST); Relationship rel3 = node2.createRelationshipTo(node1, MyRelTypes.TEST); Node[] nodes = rel2.getNodes(); assertEquals(2, nodes.length); assertTrue(nodes[0].equals(node1) && nodes[1].equals(node2)); nodes = rel3.getNodes(); assertEquals(2, nodes.length); assertTrue(nodes[0].equals(node2) && nodes[1].equals(node1)); assertEquals(node1, rel2.getStartNode()); assertEquals(node2, rel2.getEndNode()); assertEquals(node2, rel3.getStartNode()); assertEquals(node1, rel3.getEndNode()); Relationship relArray[] = getRelationshipArray(node1.getRelationships(MyRelTypes.TEST, Direction.OUTGOING)); assertEquals(1, relArray.length); assertEquals(rel2, relArray[0]); relArray = getRelationshipArray(node1.getRelationships(MyRelTypes.TEST, Direction.INCOMING)); assertEquals(1, relArray.length); assertEquals(rel3, relArray[0]); relArray = getRelationshipArray(node2.getRelationships(MyRelTypes.TEST, Direction.OUTGOING)); assertEquals(1, relArray.length); assertEquals(rel3, relArray[0]); relArray = getRelationshipArray(node2.getRelationships(MyRelTypes.TEST, Direction.INCOMING)); assertEquals(1, relArray.length); assertEquals(rel2, relArray[0]); rel2.delete(); rel3.delete(); node1.delete(); node2.delete(); }
private void deleteRecursivelySubtree(Node indexNode) { for (Relationship relationship : indexNode.getRelationships(RTreeRelationshipTypes.RTREE_CHILD, Direction.OUTGOING)) { deleteRecursivelySubtree(relationship.getEndNode()); } Relationship relationshipWithFather = indexNode.getSingleRelationship(RTreeRelationshipTypes.RTREE_CHILD, Direction.INCOMING); // the following check is needed because rootNode doesn't have this relationship if (relationshipWithFather != null) { relationshipWithFather.delete(); } indexNode.delete(); }