Java Code Examples for org.neo4j.graphdb.Node#getRelationships()
The following examples show how to use
org.neo4j.graphdb.Node#getRelationships() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Traversals.java From EvilCoder with MIT License | 6 votes |
public static List<Node> getChildrenConnectedBy(Node node, String edgeType) { List<Node> retval = new LinkedList<Node>(); long nodeId = node.getId(); Iterable<Relationship> rels = node.getRelationships(); for (Relationship rel : rels) { if (!rel.getType().name().equals(edgeType)) continue; Node childNode = rel.getEndNode(); if (childNode.getId() == nodeId) continue; retval.add(childNode); } return retval; }
Example 2
Source File: Clique.java From SciGraph with Apache License 2.0 | 6 votes |
private void deleteEdges(Node n, Transaction tx) { int edgesDeleted = 0; Iterable<Relationship> rels = n.getRelationships(); for (Relationship rel : rels) { if (rel.hasProperty(REL_TO_REMOVE)) { rel.delete(); edgesDeleted += 1; } // if (edgesDeleted >= 100) { // Commit for nodes with many edges // logger.fine("rel delete batch commit for " + n.getProperty(NodeProperties.IRI)); // tx.success(); // tx.close(); // tx = graphDb.beginTx(); // edgesDeleted = 0; // } } }
Example 3
Source File: Neo4JApiQuerySemaphoreNeighborInject.java From trainbenchmark with Eclipse Public License 1.0 | 6 votes |
@Override public Collection<Neo4jSemaphoreNeighborInjectMatch> evaluate() { final Collection<Neo4jSemaphoreNeighborInjectMatch> matches = new ArrayList<>(); final GraphDatabaseService graphDb = driver.getGraphDb(); try (Transaction tx = graphDb.beginTx()) { // (route:Route) final Iterable<Node> routes = () -> graphDb.findNodes(Neo4jConstants.labelRoute); for (final Node route : routes) { Iterable<Relationship> entries = route.getRelationships(Direction.OUTGOING, Neo4jConstants.relationshipTypeEntry); for (Relationship entry : entries) { final Node semaphore = entry.getEndNode(); final Map<String, Object> match = new HashMap<>(); match.put(QueryConstants.VAR_ROUTE, route); match.put(QueryConstants.VAR_SEMAPHORE, semaphore); matches.add(new Neo4jSemaphoreNeighborInjectMatch(match)); } } } return matches; }
Example 4
Source File: Neo4jUtil.java From trainbenchmark with Eclipse Public License 1.0 | 6 votes |
public static Iterable<Node> getAdjacentNodes(final Node sourceNode, final RelationshipType relationshipType, final Direction direction, final Label targetNodeLabel) { final Collection<Node> nodes = new ArrayList<>(); final Iterable<Relationship> relationships = sourceNode.getRelationships(relationshipType, direction); for (final Relationship relationship : relationships) { final Node candidate; switch (direction) { case INCOMING: candidate = relationship.getStartNode(); break; case OUTGOING: candidate = relationship.getEndNode(); break; default: throw new UnsupportedOperationException("Direction: " + direction + " not supported."); } if (!candidate.hasLabel(targetNodeLabel)) { continue; } nodes.add(candidate); } return nodes; }
Example 5
Source File: LabelPropagation.java From Neo4jSNA with Apache License 2.0 | 6 votes |
protected long getMostFrequentLabel(Node node) { Long2LongMap commMap = new Long2LongOpenHashMap(); Iterable<Relationship> relationships = relType == null ? node.getRelationships() : node.getRelationships(relType); for (Relationship r : relationships) { Node other = r.getOtherNode(node); long otherCommunity = (long) other.getProperty(attName); // commMap.put(other.getId(), otherCommunity); WRONG long count = commMap.getOrDefault(otherCommunity, 0L); commMap.put(otherCommunity, count+1); } long mostFrequentLabel = -1; long mostFrequentLabelCount = -1; for( Entry<Long, Long> e : commMap.entrySet() ) { if( e.getValue() > mostFrequentLabelCount ) { mostFrequentLabelCount = e.getValue(); mostFrequentLabel = e.getKey(); } } return mostFrequentLabel; }
Example 6
Source File: UniqueRelationshipFactory.java From neo4jena with Apache License 2.0 | 6 votes |
/** * Finds relationship of given type between subject and object nodes. * * @return Relationship if exists or null. */ public Relationship get(Node subject, RelationshipType type, Node object) { try { // FIXME Use relationship index instead of iterating over all relationships Iterable<Relationship> relations = subject.getRelationships(Direction.OUTGOING, type); for(Relationship relation: relations) { org.neo4j.graphdb.Node target = relation.getEndNode(); // Match object with target node in the existing triple Iterable<Label> labels = object.getLabels(); for(Label label:labels) { if(label.name().equals(NeoGraph.LABEL_LITERAL)) { // Match literal value of object and target in existing triple if(object.getProperty(NeoGraph.PROPERTY_VALUE).equals(target.getProperty(NeoGraph.PROPERTY_VALUE))) return relation; else return null; } } // Now match URI of object and target in existing triple // FIXME Blank Nodes? if(object.getProperty(NeoGraph.PROPERTY_URI).equals(target.getProperty(NeoGraph.PROPERTY_URI))) return relation; } } catch(RuntimeException exception) { } return null; }
Example 7
Source File: Neo4jGraphDatabase.java From graphdb-benchmarks with Apache License 2.0 | 5 votes |
@Override public Set<Integer> getCommunitiesConnectedToNodeCommunities(int nodeCommunities) { Set<Integer> communities = new HashSet<Integer>(); try (final Transaction tx = beginUnforcedTransaction()) { try { ResourceIterable<Node> nodes = neo4jGraph.findNodesByLabelAndProperty(Neo4jGraphDatabase.NODE_LABEL, NODE_COMMUNITY, nodeCommunities); for (Node n : nodes) { for (Relationship r : n.getRelationships(RelTypes.SIMILAR, Direction.OUTGOING)) { Node neighbour = r.getOtherNode(n); Integer community = (Integer) (neighbour.getProperty(COMMUNITY)); communities.add(community); } } tx.success(); } catch (Exception e) { tx.failure(); throw new BenchmarkingException("unable to get communities connected to node communities", e); } } return communities; }
Example 8
Source File: Traversals.java From EvilCoder with MIT License | 5 votes |
public static String getCalleeFromCall(Long nodeId) { Node node = Neo4JDBInterface.getNodeById(nodeId); Iterable<Relationship> rels = node.getRelationships(); for (Relationship rel : rels) { if (!rel.getType().name().equals(EdgeTypes.IS_AST_PARENT)) continue; Node endNode = rel.getEndNode(); if (endNode.getId() == node.getId()) continue; try { String childNumStr = (String) endNode .getProperty(NodeKeys.CHILD_NUMBER); if (childNumStr.equals("0")) return endNode.getProperty(NodeKeys.CODE).toString(); } catch (RuntimeException ex) { return endNode.getProperty(NodeKeys.CODE).toString(); } } return ""; }
Example 9
Source File: DDGPatcher.java From EvilCoder with MIT License | 5 votes |
private void removeOldEdges(DDGDifference diff) { List<DefUseRelation> relsToRemove = diff.getRelsToRemove(); for (DefUseRelation rel : relsToRemove) { Node srcStatement = Neo4JDBInterface.getNodeById((Long) rel.src); Iterable<Relationship> rels = srcStatement .getRelationships(Direction.OUTGOING); for (Relationship reachRel : rels) { if (!reachRel.getType().name().equals(EdgeTypes.REACHES)) continue; if (reachRel.getEndNode().getId() != (Long) rel.dst) continue; Object var = reachRel.getProperty("var"); if (var == null || !var.toString().equals(rel.symbol)) continue; Neo4JDBInterface.removeEdge(reachRel.getId()); } } }
Example 10
Source File: Clique.java From SciGraph with Apache License 2.0 | 5 votes |
private void moveEdgesToLeader(Node leader, List<Node> clique, Transaction tx) { for (Node n : clique) { logger.fine("Processing underNode - " + n.getProperty(NodeProperties.IRI)); // int edgesMoved = 0; Iterable<Relationship> rels = n.getRelationships(); for (Relationship rel : rels) { if ((isOneOfType(rel, relationships)) && (rel.getStartNode().getId() == leader.getId() || rel.getEndNode().getId() == leader.getId())) { logger.fine("equivalence relation which is already attached to the leader, do nothing"); } else { if ((rel.getEndNode().getId() == n.getId())) { logger.fine("MOVE TARGET " + rel.getId() + " FROM " + n.getProperty(NodeProperties.IRI) + " TO " + leader.getProperty(NodeProperties.IRI)); moveRelationship(n, leader, rel, ORIGINAL_REFERENCE_KEY_TARGET); } else if ((rel.getStartNode().getId() == n.getId())) { logger.fine("MOVE SOURCE " + rel.getId() + " FROM " + n.getProperty(NodeProperties.IRI) + " TO " + leader.getProperty(NodeProperties.IRI)); moveRelationship(n, leader, rel, ORIGINAL_REFERENCE_KEY_SOURCE); } } // edgesMoved += 1; // // if (edgesMoved >= 100) { // Commit for nodes with many edges // logger.fine("rel batch commit for leader " + leader.getProperty(NodeProperties.IRI) + // " and peasant " + n.getProperty(NodeProperties.IRI)); // tx.success(); // tx.close(); // tx = graphDb.beginTx(); // edgesMoved = 0; // } } deleteEdges(n, tx); } }
Example 11
Source File: Neo4JApiQuerySwitchMonitored.java From trainbenchmark with Eclipse Public License 1.0 | 5 votes |
@Override public Collection<Neo4jSwitchMonitoredMatch> evaluate() { final Collection<Neo4jSwitchMonitoredMatch> matches = new ArrayList<>(); final GraphDatabaseService graphDb = driver.getGraphDb(); try (Transaction tx = graphDb.beginTx()) { final Iterable<Node> sws = () -> graphDb.findNodes(Neo4jConstants.labelSwitch); // (sw:Switch) for (final Node sw : sws) { // (sw)-[:sensor]->(Sensor) NAC final Iterable<Relationship> relationshipSensors = sw.getRelationships(Direction.OUTGOING, Neo4jConstants.relationshipTypeMonitoredBy); boolean hasSensor = false; for (final Relationship relationshipSensor : relationshipSensors) { final Node sensor = relationshipSensor.getEndNode(); if (sensor.hasLabel(Neo4jConstants.labelSensor)) { hasSensor = true; break; } } if (!hasSensor) { final Map<String, Object> match = new HashMap<>(); match.put(VAR_SW, sw); matches.add(new Neo4jSwitchMonitoredMatch(match)); } } } return matches; }
Example 12
Source File: Neo4jGraphDatabase.java From graphdb-benchmarks with Apache License 2.0 | 5 votes |
@Override public Set<Integer> getNeighborsIds(int nodeId) { Set<Integer> neighbors = new HashSet<Integer>(); try (final Transaction tx = beginUnforcedTransaction()) { try { Node n = neo4jGraph.findNodesByLabelAndProperty(NODE_LABEL, NODE_ID, String.valueOf(nodeId)).iterator() .next(); for (Relationship relationship : n.getRelationships(RelTypes.SIMILAR, Direction.OUTGOING)) { Node neighbour = relationship.getOtherNode(n); String neighbourId = (String) neighbour.getProperty(NODE_ID); neighbors.add(Integer.valueOf(neighbourId)); } tx.success(); } catch (Exception e) { tx.failure(); throw new BenchmarkingException("unable to get neighbors ids", e); } } return neighbors; }
Example 13
Source File: ConnectedComponents.java From Neo4jSNA with Apache License 2.0 | 5 votes |
protected long getLowestComponent(Node n) { long minComponent = (long) n.getProperty(attName); for(Relationship r : n.getRelationships(direction)) { long otherComponent = (long) r.getOtherNode(n).getProperty(attName); minComponent = minComponent < otherComponent ? minComponent : otherComponent; } return minComponent; }
Example 14
Source File: PageRank.java From Neo4jSNA with Apache License 2.0 | 5 votes |
@Override public void apply(Node node) { double secondMember = 0.0; for( Relationship rin : node.getRelationships() ) { Node neigh = rin.getOtherNode(node); double neighRank = (double) neigh.getProperty(attName); secondMember += neighRank / neigh.getDegree(); } secondMember *= this.dampingFactor; node.setProperty(attName, firstMember + secondMember); }
Example 15
Source File: OwlPostprocessor.java From SciGraph with Apache License 2.0 | 5 votes |
public void processSomeValuesFrom() { logger.info("Processing someValuesFrom classes"); try (Transaction tx = graphDb.beginTx()) { Result results = graphDb.execute("MATCH (n)-[relationship]->(svf:someValuesFrom)-[:property]->(p) " + "RETURN n, relationship, svf, p"); while (results.hasNext()) { Map<String, Object> result = results.next(); Node subject = (Node) result.get("n"); Relationship relationship = (Relationship) result.get("relationship"); Node svf = (Node) result.get("svf"); Node property = (Node) result.get("p"); for (Relationship r : svf.getRelationships(OwlRelationships.FILLER)) { Node object = r.getEndNode(); String relationshipName = GraphUtil.getProperty(property, CommonProperties.IRI, String.class).get(); RelationshipType type = RelationshipType.withName(relationshipName); String propertyUri = GraphUtil.getProperty(property, CommonProperties.IRI, String.class).get(); Relationship inferred = subject.createRelationshipTo(object, type); inferred.setProperty(CommonProperties.IRI, propertyUri); inferred.setProperty(CommonProperties.CONVENIENCE, true); inferred.setProperty(CommonProperties.OWL_TYPE, relationship.getType().name()); } } tx.success(); tx.close(); } }
Example 16
Source File: Neo4jGraphDatabase.java From graphdb-benchmarks with Apache License 2.0 | 4 votes |
public double getNodeInDegree(Node node) { Iterable<Relationship> rel = node.getRelationships(Direction.OUTGOING, RelTypes.SIMILAR); return (double) (IteratorUtil.count(rel)); }
Example 17
Source File: GraphUtil.java From SnowGraph with Apache License 2.0 | 4 votes |
private static boolean hasRelationShip(Node nodeA, Node nodeB, RelationshipType t) { for (Relationship relationship : nodeA.getRelationships(t)) { if (relationship.getOtherNode(nodeA).equals(nodeB)) return true; } return false; }
Example 18
Source File: ReadOptimizedGraphity.java From metalcon with GNU General Public License v3.0 | 4 votes |
/** * update the replica layer for status update deletion * * @param user * owner of the status update being deleted * @param statusUpdate * status update being deleted */ private void updateReplicaLayerStatusUpdateDeletion(final Node user, final Node statusUpdate) { final Node lastUpdate = NeoUtils.getNextSingleNode(user, SocialGraphRelationshipType.UPDATE); // update the ego network if the removal targets the last recent status // update if (statusUpdate.equals(lastUpdate)) { // get timestamp of the last recent status update in future long newTimestamp = 0; final Node nextStatusUpdate = NeoUtils.getNextSingleNode( statusUpdate, SocialGraphRelationshipType.UPDATE); if (nextStatusUpdate != null) { newTimestamp = (long) nextStatusUpdate .getProperty(Properties.StatusUpdate.TIMESTAMP); } // loop through followers Node replicaNode, following; for (Relationship replicated : user.getRelationships( SocialGraphRelationshipType.REPLICA, Direction.INCOMING)) { replicaNode = replicated.getEndNode(); following = NeoUtils.getPrevSingleNode(replicaNode, SocialGraphRelationshipType.FOLLOW); // search for insertion index within following replica layer long crrTimestamp; Node prevReplica = following; Node nextReplica = null; while (true) { // get next user nextReplica = NeoUtils.getNextSingleNode(prevReplica, SocialGraphRelationshipType.GRAPHITY); if (nextReplica != null) { // ignore replica of the status update owner if (nextReplica.equals(replicaNode)) { prevReplica = nextReplica; continue; } crrTimestamp = getLastUpdateByReplica(nextReplica); // step on if current user has newer status updates if (crrTimestamp > newTimestamp) { prevReplica = nextReplica; continue; } } // insertion position has been found break; } // insert the replica if (nextReplica != null) { // bride the replica node final Node oldPrevReplica = NeoUtils.getNextSingleNode( replicaNode, SocialGraphRelationshipType.GRAPHITY); final Node oldNextReplica = NeoUtils.getNextSingleNode( replicaNode, SocialGraphRelationshipType.GRAPHITY); replicaNode.getSingleRelationship( SocialGraphRelationshipType.GRAPHITY, Direction.INCOMING).delete(); if (oldNextReplica != null) { oldNextReplica.getSingleRelationship( SocialGraphRelationshipType.GRAPHITY, Direction.INCOMING).delete(); oldPrevReplica.createRelationshipTo(oldNextReplica, SocialGraphRelationshipType.GRAPHITY); } // link to new neighbored nodes if (nextReplica != null) { replicaNode.createRelationshipTo(nextReplica, SocialGraphRelationshipType.GRAPHITY); prevReplica.getSingleRelationship( SocialGraphRelationshipType.GRAPHITY, Direction.OUTGOING); } prevReplica.createRelationshipTo(replicaNode, SocialGraphRelationshipType.GRAPHITY); } } } }
Example 19
Source File: ReadOptimizedGraphity.java From metalcon with GNU General Public License v3.0 | 4 votes |
/** * update the ego network of a user * * @param user * user where changes have occurred */ private void updateEgoNetwork(final Node user) { Node followedReplica, followingUser, lastPosterReplica; Node prevReplica, nextReplica; // loop through users following for (Relationship relationship : user.getRelationships( SocialGraphRelationshipType.REPLICA, Direction.INCOMING)) { // load each replica and the user corresponding followedReplica = relationship.getStartNode(); followingUser = NeoUtils.getPrevSingleNode(followedReplica, SocialGraphRelationshipType.FOLLOW); // bridge user node prevReplica = NeoUtils.getPrevSingleNode(followedReplica, SocialGraphRelationshipType.GRAPHITY); if (!prevReplica.equals(followingUser)) { followedReplica.getSingleRelationship( SocialGraphRelationshipType.GRAPHITY, Direction.INCOMING).delete(); nextReplica = NeoUtils.getNextSingleNode(followedReplica, SocialGraphRelationshipType.GRAPHITY); if (nextReplica != null) { followedReplica.getSingleRelationship( SocialGraphRelationshipType.GRAPHITY, Direction.OUTGOING).delete(); prevReplica.createRelationshipTo(nextReplica, SocialGraphRelationshipType.GRAPHITY); } } // insert user's replica at its new position lastPosterReplica = NeoUtils.getNextSingleNode(followingUser, SocialGraphRelationshipType.GRAPHITY); if (!lastPosterReplica.equals(followedReplica)) { followingUser.getSingleRelationship( SocialGraphRelationshipType.GRAPHITY, Direction.OUTGOING).delete(); followingUser.createRelationshipTo(followedReplica, SocialGraphRelationshipType.GRAPHITY); followedReplica.createRelationshipTo(lastPosterReplica, SocialGraphRelationshipType.GRAPHITY); } } }
Example 20
Source File: NeoUtils.java From metalcon with GNU General Public License v3.0 | 3 votes |
/** * Search for a relationship between two nodes * * @param source * source node to loop through relationships * @param target * target node of the relationship * @param relationshipType * relationship type of the relation being searched * @param direction * direction of the relationship being searched * @return relationship instance matching the passed arguments if existing<br> * <b>null</b> - otherwise */ public static Relationship getRelationshipBetween(final Node source, final Node target, final RelationshipType relationshipType, final Direction direction) { for (Relationship relationship : source.getRelationships( relationshipType, direction)) { if (relationship.getEndNode().equals(target)) { return relationship; } } return null; }