/** * 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(); }
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; }
@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(); }
String getTitle(Relationship edge) { if (edgeTitle != null) { return edgeTitle.getTitle(edge); } else { return edge.getType().name(); } }
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(); }
@Override public RelationshipType getRelType() { if (dbRelationship != null) { return dbRelationship.getType(); } return null; }
private void loadGraphNodeMemory() { Node refNode = GraphDB.getReferenceNode(); LinkedList<Node> queue = new LinkedList<Node>(); queue.offer(refNode); int key = (Integer) refNode.getProperty("id"); GNode gNode = new GNode(refNode, null, null); graphNodesMemomry.put(key, gNode); System.out.println(key + " " + gNode.getNode().getProperty("name")); while (!queue.isEmpty()) { Node node = queue.poll(); GNode gSourceNode = graphNodesMemomry.get(node.getProperty("id")); for (Relationship rel : node.getRelationships(Direction.OUTGOING)) { Node endNode = rel.getEndNode(); queue.offer(endNode); GNode gEndNode = new GNode(endNode, null, rel.getType()); key = (Integer) endNode.getProperty("id"); if (graphNodesMemomry.get(key) == null) { gNode = new GNode(endNode, null, null); graphNodesMemomry.put(key, gNode); } while (gSourceNode.getConnectedTo() != null) { gSourceNode = gSourceNode.getConnectedTo(); } gSourceNode.setConnectedTo(gEndNode); System.out.println( node.getProperty("name") + " " + rel.getType() + " " + endNode.getProperty("name")); } } }
@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(); }
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 testCreateRelationshipToNodeOutsideofBatch() throws Exception { final Node node1 = restAPI.createNode(map()); final Transaction tx = restAPI.beginTx(); Node node2 = restAPI.createNode(map()); final Relationship relationship = node1.createRelationshipTo(node2, DynamicRelationshipType.withName("foo")); tx.success(); tx.finish(); assertEquals("foo", relationship.getType().name()); assertEquals( "foo", getGraphDatabase().getRelationshipById(relationship.getId()).getType().name()); }
@Override public String relationshipRepresentation(Path path, Node from, Relationship relationship) { String prefix = "--", suffix = "--"; if (from.equals(relationship.getEndNode())) { prefix = "<--"; } else { suffix = "-->"; } return prefix + "[" + relationship.getType().name() + "," + relationship.getId() + "]" + suffix; }
/** * @param server the {@link GraphDatabaseShellServer} to run at. * @param session the {@link Session} used by the client. * @param relationship the {@link Relationship} to get a display name for. * @param verbose whether or not to include the relationship id as well. * @return a display string for the {@code relationship}. */ public static String getDisplayName( GraphDatabaseShellServer server, Session session, Relationship relationship, boolean verbose, boolean checkForMe) throws ShellException { if (checkForMe && isCurrent(session, NodeOrRelationship.wrap(relationship))) { return getDisplayNameForCurrent(server, session); } StringBuilder result = new StringBuilder("["); result.append(":" + relationship.getType().name()); result.append(verbose ? "," + relationship.getId() : ""); result.append("]"); return result.toString(); }
private Object toJsonCompatible(Object value) { if (value instanceof Node) { final Node node = (Node) value; final Map<String, Object> result = SubGraph.toMap((PropertyContainer) node); result.put("_id", node.getId()); final List<String> labelNames = SubGraph.getLabelNames(node); if (!labelNames.isEmpty()) result.put("_labels", labelNames); return result; } if (value instanceof Relationship) { final Relationship relationship = (Relationship) value; final Map<String, Object> result = SubGraph.toMap((PropertyContainer) 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 Map) { @SuppressWarnings("unchecked") Map<String, Object> map = (Map<String, Object>) value; final Map<String, Object> result = new LinkedHashMap<>(map.size()); for (Map.Entry<String, Object> entry : map.entrySet()) { result.put(entry.getKey(), toJsonCompatible(entry.getValue())); } return result; } if (value instanceof Iterable) { final List<Object> result = new ArrayList<>(); for (Object inner : (Iterable) value) { result.add(toJsonCompatible(inner)); } return result; } return value; }
@Override public boolean include(Relationship relationship) { return !(relationship.getType().name().equals("NEXT")); }
@Override public boolean include(Relationship relationship) { return relationship.getType().name().equals("REL2"); }
@Test public void shouldAccessRelationshipDataInAfterCommit() throws Exception { // GIVEN final GraphDatabaseService db = dbRule.getGraphDatabaseService(); final AtomicInteger accessCount = new AtomicInteger(); final Map<Long, Triplet<Node, String, Node>> expectedRelationshipData = new HashMap<>(); TransactionEventHandler<Void> handler = new TransactionEventHandler.Adapter<Void>() { @Override public void afterCommit(TransactionData data, Void state) { accessCount.set(0); try (Transaction tx = db.beginTx()) { for (Relationship relationship : data.createdRelationships()) { accessData(relationship); } for (PropertyEntry<Relationship> change : data.assignedRelationshipProperties()) { accessData(change.entity()); } for (PropertyEntry<Relationship> change : data.removedRelationshipProperties()) { accessData(change.entity()); } tx.success(); } } private void accessData(Relationship relationship) { accessCount.incrementAndGet(); Triplet<Node, String, Node> expectancy = expectedRelationshipData.get(relationship.getId()); assertNotNull(expectancy); assertEquals(expectancy.first(), relationship.getStartNode()); assertEquals(expectancy.second(), relationship.getType().name()); assertEquals(expectancy.third(), relationship.getEndNode()); } }; db.registerTransactionEventHandler(handler); // WHEN try { Relationship relationship; try (Transaction tx = db.beginTx()) { relationship = db.createNode().createRelationshipTo(db.createNode(), MyRelTypes.TEST); expectedRelationshipData.put( relationship.getId(), Triplet.of( relationship.getStartNode(), relationship.getType().name(), relationship.getEndNode())); tx.success(); } // THEN assertEquals(1, accessCount.get()); // and WHEN try (Transaction tx = db.beginTx()) { relationship.setProperty("name", "Smith"); Relationship otherRelationship = db.createNode().createRelationshipTo(db.createNode(), MyRelTypes.TEST2); expectedRelationshipData.put( otherRelationship.getId(), Triplet.of( otherRelationship.getStartNode(), otherRelationship.getType().name(), otherRelationship.getEndNode())); tx.success(); } // THEN assertEquals(2, accessCount.get()); // and WHEN try (Transaction tx = db.beginTx()) { relationship.delete(); tx.success(); } // THEN assertEquals(1, accessCount.get()); } finally { db.unregisterTransactionEventHandler(handler); } }
@Override public Map<String, Set<Long>> extract( List<DocGraph> docGraphs, DocGraphFilterFunction filterFunc, Set<String> resourceClasses, Set<String> documentClasses) { // pattern-document graph associations R_D Map<String, Set<Long>> associations = new HashMap<String, Set<Long>>(); // init path finder initFinder(); // G_D(filtered) <- G_D.where({G_d|filter(G_D)}) Set<DocGraph> filteredDocGraphs = new HashSet<DocGraph>(); if (filterFunc == null) { filteredDocGraphs.addAll(docGraphs); } else { for (DocGraph docGraph : docGraphs) { if (filterFunc.filter(docGraph)) { filteredDocGraphs.add(docGraph); } } } Set<Node> relevantResources = null; Set<Node> relevantDocuments = null; String r = null; Node v_p = null; boolean validPath = true; int pCnt = 0; log.info(String.format("Starting analysis of %d document graphs", filteredDocGraphs.size())); for (DocGraph docGraph : filteredDocGraphs) { log.info( String.format( "Analyzing DocGraph[%d] (%d, %d)", docGraph.getId(), docGraph.getNodeCount(), docGraph.getEdgeCount())); pCnt = 0; // V_R <- G_d.V.where({v|tau(mu(v)) in C_R}) relevantResources = filterNodesByClass(docGraph.getNodes(), resourceClasses); // V_R <- G_d.V.where({v|tau(mu(v)) in C_D}) relevantDocuments = filterNodesByClass(docGraph.getNodes(), documentClasses); preProcessGraph(docGraph, resourceClasses); try (Transaction tx = graphDB.beginTx()) { for (Node v_r : relevantResources) { for (Node v_d : relevantDocuments) { // P <- G_d.paths(v_R,v_D) for (Path p : finder.findAllPaths(v_r, v_d)) { validPath = true; r = String.format("%s", v_r.getProperty(Constants.ID_KEY)); v_p = v_r; for (Relationship e : p.relationships()) { if (e.getStartNode().getId() == v_p.getId()) { if (getNodeSuperClass(e.getEndNode()) .equals(Constants.NODE_SUPER_CLASS_RESOURCE_VALUE)) { validPath = false; break; } r = String.format( "%s-%s->%s", r, e.getType().name(), getNodeClass(e.getEndNode())); v_p = e.getEndNode(); } else { if (getNodeSuperClass(e.getStartNode()) .equals(Constants.NODE_SUPER_CLASS_RESOURCE_VALUE)) { validPath = false; break; } r = String.format( "%s<-%s-%s", r, e.getType().name(), getNodeClass(e.getStartNode())); v_p = e.getStartNode(); } } // R_D.add(<r, G_d>) if (validPath) { associations = addPatternDocGraphAssociation(associations, r, docGraph); pCnt++; } } } } tx.success(); } log.info(String.format("%d patterns in DocGraph[%d]", pCnt, docGraph.getId())); } return associations; }
/** * Construct a representation from a Neo4j relationship. * * @param relationship to create the representation from. Must not be <code>null</code>. * @param properties keys of properties to be included in the representation. Can be <code>null * </code>, which represents all. Empty array represents none. */ public RelationshipRepresentation(Relationship relationship, String[] properties) { super(relationship, properties); startNodeGraphId = relationship.getStartNode().getId(); endNodeGraphId = relationship.getEndNode().getId(); setType(relationship.getType().name()); }
public Double shortestPath() { s1nodes = Neo4jGraphUtils.getSourceNodes(graph, s1); s2nodes = Neo4jGraphUtils.getSourceNodes(graph, s2); log.info( "Compute pairwise cheapest path: S{} ({} nodes), S{} ({} nodes)", s1.getSnippetId(), s1nodes.size(), s2.getSnippetId(), s2nodes.size()); int pathLenghtSum = 0; int pathCount = 0; int commonNodeCount = 0; int cacheCounter = 0; for (Vertex v1 : s1nodes) { for (Vertex v2 : s2nodes) { Long v1id = (Long) (v1.getId()); Long v2id = (Long) (v2.getId()); if (v1id.compareTo(v2id) == 0) { commonNodeCount++; // pathCount++; // pathLenghtSum += 0 continue; } log.debug("Processing Node {} and Node {}", v1id, v2id); Node n1 = graph.getRawGraph().getNodeById(v1id); Node n2 = graph.getRawGraph().getNodeById(v2id); // Get shortest path Integer pathLen = null; // p.length(); Tuple<Integer, Double> path = pathCache.getPath(v1id, v2id, log.isDebugEnabled()); if (path != null) { pathLen = path.k; cacheCounter++; log.debug( "Path between Node{} and Node{} found, Length {}, Weight {} (from mysql cache)", v1id, v2id, pathLen); } else { log.debug("Start ShortestPath Node {} and Node {}", v1id, v2id); PathFinder<Path> shortestPathAlgo = GraphAlgoFactory.shortestPath( (PathExpander<?>) Traversal.expanderForAllTypes(), maxPathLen.intValue()); Path shortestPath = shortestPathAlgo.findSinglePath(n1, n2); StringBuffer shorestPathSteps = null; if (shortestPath != null) { pathLen = shortestPath.length(); // Constructing path for debug logging if (log.isDebugEnabled()) { Iterator<PropertyContainer> iter = shortestPath.iterator(); shorestPathSteps = new StringBuffer(); while (iter.hasNext()) { Object e = iter.next(); if (e instanceof NodeProxy) { Node n = (Node) e; shorestPathSteps.append("(" + n.getProperty("label") + ")"); } else if (e instanceof RelationshipProxy) { Relationship r = (Relationship) e; shorestPathSteps.append("-[" + r.getType() + "]-"); } else { log.error("ERROR"); } } log.debug( "Path between Node{} and Node{} found, Length {}, Path {}", v1id, v2id, pathLen, shorestPathSteps); } } else { log.debug("Path between Node{} and Node{} not found.", v1id, v2id); } // Update mysql db cache if (log.isDebugEnabled()) { pathCache.setPath(v1id, v2id, pathLen, null, shorestPathSteps); } else { pathCache.setPath(v1id, v2id, pathLen, null); } } // Getting shortest path data if (pathLen != null) { if (pathLen <= maxPathLen) { pathLenghtSum += pathLen; pathCount++; } } } } log.info( "Similarity measures S{}, S{}: CommonNodes {}, PathCnt {}, MaxTheoPathCnt {}, SumPathLen {}, CacheCnt {}", s1.getSnippetId(), s2.getSnippetId(), commonNodeCount, pathCount, s1nodes.size() * s2nodes.size(), pathLenghtSum, cacheCounter); // log.info("Total path score S{}, S{}: {}", s1.getSnippetId(), s2.getSnippetId(), sim); return Double.valueOf(pathLenghtSum); }
/** * Create a JSON-serializable representation from a Neo4j node. * * @param relationship to create JSON from. * @param jsonInput specifying what to include in the produced JSON. */ public JsonRelationship(Relationship relationship, JsonInput jsonInput) { super(relationship, jsonInput.getRelationshipProperties()); startNodeId = relationship.getStartNode().getId(); endNodeId = relationship.getEndNode().getId(); setType(relationship.getType().name()); }