private Set<DirectedRelationshipType> resolveRelationships(String key, String value) { Set<DirectedRelationshipType> rels = new HashSet<>(); String cypherIn = String.format("[%s:%s]", key, value); String cypherOut = cypherUtil.resolveRelationships(cypherIn); Matcher m = ENTAILMENT_PATTERN.matcher(cypherOut); while (m.find()) { String types = m.group(2); String[] cypherRels = types.split("\\|"); for (String cypherRel : cypherRels) { String unquotedCypherRel = cypherRel.replaceAll("^`|`$",""); RelationshipType relType = RelationshipType.withName(unquotedCypherRel); DirectedRelationshipType dirRelType = new DirectedRelationshipType(relType, Direction.OUTGOING); rels.add(dirRelType); } } return rels; }
@Procedure(value = "graph.versioner.diff.from.current", mode = DEFAULT) @Description("graph.versioner.diff.from.current(state) - Get a list of differences that must be applied to the given state in order to become the current entity state") public Stream<DiffOutput> diffFromCurrent( @Name("state") Node state) { Optional<Node> currentState = Optional.ofNullable(state.getSingleRelationship(RelationshipType.withName(Utility.HAS_STATE_TYPE), Direction.INCOMING)) .map(Relationship::getStartNode).map(entity -> entity.getSingleRelationship(RelationshipType.withName(Utility.CURRENT_TYPE), Direction.OUTGOING)) .map(Relationship::getEndNode); Stream<DiffOutput> result = Stream.empty(); if(currentState.isPresent() && !currentState.equals(Optional.of(state))){ result = diffBetweenStates(Optional.of(state), currentState); } return result; }
private void fromTextToJira(){ Map<String, Node> jiraMap=new HashMap<>(); try (Transaction tx = db.beginTx()) { for (Node node:db.getAllNodes()){ if (node.hasLabel(Label.label(JiraExtractor.ISSUE))){ String name=(String) node.getProperty(JiraExtractor.ISSUE_NAME); jiraMap.put(name, node); } } tx.success(); } try (Transaction tx = db.beginTx()) { for (Node srcNode : textNodes) { String content = text(srcNode); Set<String> tokenSet=new HashSet<>(); for (String e:content.split("[^A-Za-z0-9\\-_]+")) tokenSet.add(e); for (String jiraName:jiraMap.keySet()){ if (tokenSet.contains(jiraName)) srcNode.createRelationshipTo(jiraMap.get(jiraName), RelationshipType.withName(REFERENCE)); } } tx.success(); } }
public void run(GraphDatabaseService db) { this.db = db; MboxHandler myHandler = new MboxHandler(); myHandler.setDb(db); MimeConfig config=new MimeConfig(); config.setMaxLineLen(-1); parser = new MimeStreamParser(config); parser.setContentHandler(myHandler); parse(new File(mboxPath)); try (Transaction tx = db.beginTx()) { for (String address : myHandler.getMailUserNameMap().keySet()) { Node node = myHandler.getMailUserMap().get(address); node.setProperty(MAILUSER_NAMES, String.join(", ", myHandler.getMailUserNameMap().get(address))); } tx.success(); } try (Transaction tx = db.beginTx()) { for (String mailId : myHandler.getMailReplyMap().keySet()) { Node mailNode = myHandler.getMailMap().get(mailId); Node replyNode = myHandler.getMailMap().get(myHandler.getMailReplyMap().get(mailId)); if (mailNode != null & replyNode != null) mailNode.createRelationshipTo(replyNode, RelationshipType.withName(MailListExtractor.MAIL_IN_REPLY_TO)); } tx.success(); } }
private void createUserNode(Node mailNode, String userName, String userAddress, boolean sender) { Node userNode; if (!mailUserMap.containsKey(userAddress)) { userNode = db.createNode(); userNode.addLabel(Label.label(MailListExtractor.MAILUSER)); userNode.setProperty(MailListExtractor.MAILUSER_MAIL, userAddress); mailUserMap.put(userAddress, userNode); } userNode = mailUserMap.get(userAddress); if (!mailUserNameMap.containsKey(userAddress)) mailUserNameMap.put(userAddress, new HashSet<>()); mailUserNameMap.get(userAddress).add(userName); if (sender) mailNode.createRelationshipTo(userNode, RelationshipType.withName(MailListExtractor.MAIL_SENDER)); else mailNode.createRelationshipTo(userNode, RelationshipType.withName(MailListExtractor.MAIL_RECEIVER)); }
@Override public <R, E extends Throwable> R accept(Visitor<R, E> visitor) throws E { for (Node node : dbServices.getAllNodes()) { if (node.hasLabel(Label.label("CompilationUnit"))) { continue; } if (node.hasLabel(Label.label("SourceSpan"))) { continue; } if (node.hasLabel(Label.label("SourceLocation"))) { continue; } visitor.visitNode(node); for (Relationship edge : node.getRelationships(Direction.OUTGOING)) { if (edge.isType(RelationshipType.withName("location"))) { continue; } visitor.visitRelationship(edge); } } return visitor.done(); }
public final Relationship add(RelationshipType type, Node tail, Node head, double prob) { if (null == type) throw new IllegalArgumentException("Illegal 'type' argument in Problem.add(RelationshipType, Node, Node, double): " + type); if (null == tail) throw new IllegalArgumentException("Illegal 'tail' argument in Problem.add(RelationshipType, Node, Node, double): " + tail); if (null == head) throw new IllegalArgumentException("Illegal 'head' argument in Problem.add(RelationshipType, Node, Node, double): " + head); if (prob < 0.0 || prob > 1.0) throw new IllegalArgumentException("Illegal 'prob' argument in Problem.add(RelationshipType, Node, Node, double): " + prob); Relationship result = null; try (Transaction tx = graph.beginTx()) { result = tail.createRelationshipTo(head, type); result.setProperty("prob", prob); count += 1; tx.success(); } return result; }
@Test public void shouldNotSeeDeletedRelationshipWhenQueryingWithStartAndEndNode() { // GIVEN RelationshipIndex index = relationshipIndex( EXACT_CONFIG ); Node start = graphDb.createNode(); Node end = graphDb.createNode(); RelationshipType type = withName( "REL" ); Relationship rel = start.createRelationshipTo( end, type ); index.add( rel, "Type", type.name() ); finishTx( true ); beginTx(); // WHEN IndexHits<Relationship> hits = index.get( "Type", type.name(), start, end ); assertEquals( 1, count( (Iterator<Relationship>)hits ) ); assertEquals( 1, hits.size() ); index.remove( rel ); // THEN hits = index.get( "Type", type.name(), start, end ); assertEquals( 0, count( (Iterator<Relationship>)hits ) ); assertEquals( 0, hits.size() ); }
/** * * @param properties * @param labels * @return */ public static long createRelationship(long startNodeId, long endNodeId, RelationshipType relationshipType, Map<String, Object> properties) { GraphDatabaseService graphDatabaseService = getGraphDatabaseService(); Node startNode = graphDatabaseService.getNodeById(startNodeId); Node endNode = graphDatabaseService.getNodeById(endNodeId); Relationship relationship = startNode.createRelationshipTo(endNode, relationshipType); for (String key : properties.keySet()) { relationship.setProperty(key, properties.get(key)); } return relationship.getId(); }
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; }
/** * 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; }
@Override public long createRelationship(long start, long end, RelationshipType type) { Optional<Long> relationshipId = getRelationship(start, end, type); if (relationshipId.isPresent()) { return relationshipId.get(); } else { try (Transaction tx = graphDb.beginTx()) { Node startNode = graphDb.getNodeById(start); Node endNode = graphDb.getNodeById(end); Relationship relationship; synchronized (graphLock) { relationship = startNode.createRelationshipTo(endNode, type); relationshipMap.put(start, end, type, relationship.getId()); } tx.success(); return relationship.getId(); } } }
@Override public Collection<Long> createRelationshipsPairwise(Collection<Long> nodeIds, RelationshipType type) { Set<Long> relationships = new HashSet<>(); for (Long start : nodeIds) { for (Long end : nodeIds) { if (start.equals(end)) { continue; } else { if (!getRelationship(end, start, type).isPresent()) { relationships.add(createRelationship(start, end, type)); } } } } return relationships; }
@Override public Collection<Long> createRelationshipsPairwise(Collection<Long> nodes, RelationshipType type) { Set<Long> relationships = new HashSet<>(); for (Long start : nodes) { for (Long end : nodes) { if (start.equals(end)) { continue; } else { synchronized (graphLock) { if (!getRelationship(end, start, type).isPresent()) { relationships.add(createRelationship(start, end, type)); } } } } } return relationships; }
long processCategory(Node root, RelationshipType type, Direction direction, String category) { long count = 0; int batchSize = 100_000; Label label = Label.label(category); Transaction tx = graphDb.beginTx(); for (Path position : graphDb.traversalDescription().uniqueness(Uniqueness.NODE_GLOBAL) .depthFirst().relationships(type, direction) .relationships(OwlRelationships.RDF_TYPE, Direction.INCOMING) .relationships(OwlRelationships.OWL_EQUIVALENT_CLASS, Direction.BOTH).traverse(root)) { Node end = position.endNode(); GraphUtil.addProperty(end, Concept.CATEGORY, category); end.addLabel(label); if (0 == ++count % batchSize) { logger.fine("Commiting " + count); tx.success(); tx.close(); tx = graphDb.beginTx(); } } tx.success(); tx.close(); return count; }
@Inject public Clique(GraphDatabaseService graphDb, CliqueConfiguration cliqueConfiguration) { this.graphDb = graphDb; this.prefixLeaderPriority = cliqueConfiguration.getLeaderPriority(); this.leaderAnnotationProperty = cliqueConfiguration.getLeaderAnnotation(); Set<Label> tmpLabels = new HashSet<Label>(); for (String l : cliqueConfiguration.getLeaderForbiddenLabels()) { tmpLabels.add(Label.label(l)); } this.forbiddenLabels = tmpLabels; Set<RelationshipType> tmpRelationships = new HashSet<RelationshipType>(); for (String r : cliqueConfiguration.getRelationships()) { tmpRelationships.add(RelationshipType.withName(r)); } this.relationships = tmpRelationships; this.batchCommitSize = cliqueConfiguration.getBatchCommitSize(); }
public Graph getEdges(RelationshipType type, boolean entail, long skip, long limit) { String query = "MATCH path = (start)-[r:" + type.name() + (entail ? "!" : "") + "]->(end) " + " RETURN path " // TODO: This slows down the query dramatically. // + " ORDER BY ID(r) " + " SKIP " + skip + " LIMIT " + limit; Graph graph = new TinkerGraph(); TinkerGraphUtil tgu = new TinkerGraphUtil(graph, curieUtil); Result result; try { result = cypherUtil.execute(query); while (result.hasNext()) { Map<String, Object> map = result.next(); Path path = (Path) map.get("path"); tgu.addPath(path); } } catch (ArrayIndexOutOfBoundsException e) { // Return and empty graph if the limit is too high... } return graph; }
@Before public void setup() { clique11 = createNode("http://x.org/a"); clique12 = createNode("http://x.org/b"); clique13 = createNode("http://x.org/c"); clique21 = createNode("http://x.org/d"); clique22 = createNode("http://x.org/e"); Relationship r1 = clique11.createRelationshipTo(clique12, IS_EQUIVALENT); Relationship r2 = clique12.createRelationshipTo(clique13, IS_EQUIVALENT); Relationship r3 = clique21.createRelationshipTo(clique22, IS_EQUIVALENT); Relationship r4 = clique12.createRelationshipTo(clique22, RelationshipType.withName("hasPhenotype")); Relationship r5 = clique13.createRelationshipTo(clique21, RelationshipType.withName("hasPhenotype")); CliqueConfiguration cliqueConfiguration = new CliqueConfiguration(); Set<String> rel = new HashSet<String>(); rel.add(IS_EQUIVALENT.name()); cliqueConfiguration.setRelationships(rel); Set<String> forbidden = new HashSet<String>(); forbidden.add("anonymous"); cliqueConfiguration.setLeaderForbiddenLabels(forbidden); cliqueConfiguration.setLeaderAnnotation(leaderAnnotation); clique = new Clique(graphDb, cliqueConfiguration); }
/** * See https://github.com/SciCrunch/SciGraph/wiki/MappingToOWL#subclassof-axioms * * Reduction step should give us a simple edge {sub p super} */ @Test public void testSubclass() { Node subclass = getNode("http://example.org/subclass"); Node superclass = getNode("http://example.org/superclass"); RelationshipType p = RelationshipType.withName("http://example.org/p"); Relationship relationship = getOnlyElement(GraphUtil.getRelationships(subclass, superclass, p)); assertThat("subclassOf relationship should start with the subclass.", relationship.getStartNode(), is(subclass)); assertThat("subclassOf relationship should end with the superclass.", relationship.getEndNode(), is(superclass)); assertThat("relationship has the correct iri", GraphUtil.getProperty(relationship, CommonProperties.IRI, String.class), is(Optional.of("http://example.org/p"))); assertThat("relationship is asserted", GraphUtil.getProperty(relationship, CommonProperties.CONVENIENCE, Boolean.class), is(Optional.of(true))); assertThat("owltype is added", GraphUtil.getProperty(relationship, CommonProperties.OWL_TYPE, String.class), is(Optional.of(OwlRelationships.RDFS_SUBCLASS_OF.name()))); }
@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 = RelationshipType.withName("http://example.org/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))); }
@Test public void relationshipsAreTranslated() { TinkerGraphUtil tgu = new TinkerGraphUtil(curieUtil); Vertex u = tgu.addNode(node); Vertex v = tgu.addNode(otherNode); Relationship relationship = mock(Relationship.class); when(relationship.getEndNode()).thenReturn(node); when(relationship.getStartNode()).thenReturn(otherNode); when(relationship.getType()).thenReturn(RelationshipType.withName("foo")); when(relationship.getPropertyKeys()).thenReturn(newHashSet("bar")); when(relationship.getProperty("bar")).thenReturn("baz"); Edge edge = tgu.addEdge(relationship); assertThat(edge.getVertex(Direction.IN), is(u)); assertThat(edge.getVertex(Direction.OUT), is(v)); assertThat(edge.getLabel(), is("foo")); assertThat((String)edge.getProperty("bar"), is("baz")); Edge edge2 = tgu.addEdge(relationship); assertThat(edge, is(edge2)); }
@Before public void setup() { CypherUtil cypherUtil = new CypherUtil(graphDb, curieUtil); addRelationship("http://x.org/#foo", "http://x.org/#fizz", OwlRelationships.RDFS_SUB_PROPERTY_OF); addRelationship("http://x.org/#bar", "http://x.org/#baz", OwlRelationships.RDFS_SUB_PROPERTY_OF); addRelationship("http://x.org/#1", "http://x.org/#2", RelationshipType.withName("http://x.org/#fizz")); when(context.getUriInfo()).thenReturn(uriInfo); MultivaluedHashMap<String, String> map = new MultivaluedHashMap<>(); map.put("rel_id", newArrayList("http://x.org/#fizz")); when(uriInfo.getQueryParameters()).thenReturn(map); map = new MultivaluedHashMap<>(); map.put("pathParam", newArrayList("pathValue")); when(uriInfo.getPathParameters()).thenReturn(map); when(curieUtil.getIri(anyString())).thenReturn(Optional.<String>empty()); when(curieUtil.getCurie(anyString())).thenReturn(Optional.<String>empty()); when(curieUtil.getIri("X:foo")).thenReturn(Optional.of("http://x.org/#foo")); inflector = new CypherInflector(graphDb, cypherUtil, curieUtil, "dynamic", path, new HashMap<String, GraphAspect>()); }
public void initializeWith(String treeSpec, Map<String,ColumnSpec> columns, List<String> leafProperties, String leafPropertiesColumn) throws UnsupportedEncodingException { TreeNodeBuilder parentBuilder = null; for (String columnSpec : URLDecoder.decode(treeSpec,"US-ASCII").split("->")) { String[] cs = columnSpec.split("-"); String columnLabel = cs[0]; RelationshipType child = cs.length > 1 ? DynamicRelationshipType.withName(cs[1]) : DEFAULT_CHILD; ColumnSpec column = columns.get(columnLabel); if (column == null) { throw new RuntimeException("Invalid tree '" + name + "': no such column '" + columnLabel + "'"); } else { TreeNodeBuilder builder = TreeNodeBuilder.makeFor(column, parentBuilder, child, db, engine); this.builders.add(builder); parentBuilder = builder; } } if (parentBuilder != null) { parentBuilder.addProperties(leafProperties, leafPropertiesColumn); } }
private static long getOrCreateRelatinshipID(final String timestamp, final long userNodeid, final long itemNodeid, final Map<String, Long> relationshipsMap, final BatchInserterIndex relationshipIndex, final BatchInserter inserter, final RelationshipType relType) { long relationID; String uniqueRelationID = userNodeid + itemNodeid + timestamp; if (relationshipsMap.containsKey(uniqueRelationID)) { relationID = relationshipsMap.get(uniqueRelationID); } else { relationID = inserter.createRelationship(userNodeid, itemNodeid, relType, MapUtil.map("timestamp", timestamp)); relationshipsMap.put(uniqueRelationID, relationID); relationshipIndex.add(relationID, MapUtil.map("useritem", uniqueRelationID)); } return relationID; }
/** * @param startCost Starting cost for both the start node and the end node * @param startNode the start node * @param endNode the end node * @param costRelationTypes the relationship that should be included in the * path * @param relationDirection relationship direction to follow * @param costEvaluator the cost function per relationship * @param costAccumulator adding up the path cost * @param costComparator comparing to path costs */ public Dijkstra( CostType startCost, Node startNode, Node endNode, CostEvaluator<CostType> costEvaluator, CostAccumulator<CostType> costAccumulator, Comparator<CostType> costComparator, Direction relationDirection, RelationshipType... costRelationTypes ) { super(); this.startCost = startCost; this.startNode = startNode; this.endNode = endNode; this.costRelationTypes = costRelationTypes; this.relationDirection = relationDirection; this.costEvaluator = costEvaluator; this.costAccumulator = costAccumulator; this.costComparator = costComparator; }
@Override Iterator<Relationship> doExpand( final Node start ) { if ( types.isEmpty() ) { return start.getRelationships().iterator(); } else if ( types.size() == 1 ) { Entry<Direction, RelationshipType[]> entry = types.entrySet().iterator().next(); return start.getRelationships( entry.getKey(), entry.getValue() ).iterator(); } else { return new NestingIterator<Relationship, Entry<Direction, RelationshipType[]>>( types.entrySet().iterator()) { @Override protected Iterator<Relationship> createNestedIterator( Entry<Direction, RelationshipType[]> item ) { return start.getRelationships( item.getKey(), item.getValue() ).iterator(); } }; } }
private static Map<Direction, RelationshipType[]> toTypeMap( Map<Direction, Collection<RelationshipType>> tempMap ) { // Remove OUT/IN where there is a BOTH Collection<RelationshipType> both = tempMap.get( Direction.BOTH ); tempMap.get( Direction.OUTGOING ).removeAll( both ); tempMap.get( Direction.INCOMING ).removeAll( both ); // Convert into a final map Map<Direction, RelationshipType[]> map = new EnumMap<Direction, RelationshipType[]>( Direction.class ); for ( Map.Entry<Direction, Collection<RelationshipType>> entry : tempMap.entrySet() ) { if ( !entry.getValue().isEmpty() ) { map.put( entry.getKey(), entry.getValue().toArray( new RelationshipType[entry.getValue().size()] ) ); } } return map; }
public long createRelationship( long node1, long node2, RelationshipType type, Map<String,Object> properties ) { NodeRecord firstNode = getNodeRecord( node1 ); NodeRecord secondNode = getNodeRecord( node2 ); int typeId = typeHolder.getTypeId( type.name() ); if ( typeId == -1 ) { typeId = createNewRelationshipType( type.name() ); } long id = getRelationshipStore().nextId(); RelationshipRecord record = new RelationshipRecord( id, node1, node2, typeId ); record.setInUse( true ); record.setCreated(); connectRelationship( firstNode, secondNode, record ); getNodeStore().updateRecord( firstNode ); getNodeStore().updateRecord( secondNode ); record.setNextProp( createPropertyChain( properties ) ); getRelationshipStore().updateRecord( record ); return id; }
public RelationshipType addValidRelationshipType( String name, boolean create ) { Integer id = relTypes.get( name ); if ( id == null ) { if ( !create ) { return null; } id = createRelationshipType( name ); RelationshipTypeImpl type = new RelationshipTypeImpl( name ); relTranslation.put( id, type ); return type; } RelationshipTypeImpl relType = relTranslation.get( id ); if ( relType == null ) { relType = new RelationshipTypeImpl( name ); relTranslation.put( id, relType ); } return relType; }
@Override public List<String> getRelationshipTypes(ParcelableError err) throws RemoteException { try { resumeTrxIfExists(); try { ArrayList<String> names = new ArrayList<String>(); for (RelationshipType type : mDb.getRelationshipTypes()) { names.add(type.name()); } return names; } finally { suspendCurrentTrx("getRelationshipTypes"); } } catch (Exception e) { Log.e(TAG, "Error accessing relationship types", e); err.setError(Errors.TRANSACTION, e.getMessage()); return null; } }
private void addNewEdges(DDGDifference diff) { List<DefUseRelation> relsToAdd = diff.getRelsToAdd(); for (DefUseRelation rel : relsToAdd) { Map<String, Object> properties = new HashMap<String, Object>(); properties.put("var", rel.symbol); RelationshipType relType = DynamicRelationshipType .withName(EdgeTypes.REACHES); Neo4JDBInterface.addRelationship((Long) rel.src, (Long) rel.dst, relType, properties, true); //JANNIK: added flag } }
public void writeChangesToDatabase() { if (defUseCFG == null) { return; } for (DefUseLink link : newlyAddedLinks) { Long fromId = link.statement; Long toId = (Long) defUseCFG.getIdForSymbol(link.symbol); if (toId == null) { Map<String, Object> properties = new HashMap<String, Object>(); Node statementNode = Neo4JDBInterface.getNodeById(link.statement); properties.put("functionId", statementNode.getProperty("functionId")); properties.put("type", "Symbol"); properties.put("code", link.symbol); Node symbolNode = Neo4JDBInterface.addNode(properties); toId = (Long) symbolNode.getId(); } RelationshipType relType = DynamicRelationshipType .withName(EdgeTypes.DEF); Neo4JDBInterface.addRelationship(fromId, toId, relType, null, true); //JANNIK: added flag } }
/** * This method returns the first available State node, by a given State node to rollback * * @param state state to rollback * @return the first available rollback node */ private Optional<Node> getFirstAvailableRollbackNode(Node state) { return StreamSupport.stream(state.getRelationships(RelationshipType.withName(Utility.ROLLBACK_TYPE), Direction.OUTGOING).spliterator(), false).findFirst() // Recursive iteration for ROLLBACKed State node .map(e -> getFirstAvailableRollbackNode(e.getEndNode())) // No ROLLBACK relationship found .orElse(StreamSupport.stream(state.getRelationships(RelationshipType.withName(Utility.PREVIOUS_TYPE), Direction.OUTGOING).spliterator(), false) .findFirst().map(Relationship::getEndNode)); }
@Procedure(value = "graph.versioner.patch.from", mode = Mode.WRITE) @Description("graph.versioner.patch.from(entity, state, date) - Add a new State to the given Entity, starting from the given one. It will update all the properties, not labels.") public Stream<NodeOutput> patchFrom( @Name("entity") Node entity, @Name("state") Node state, @Name(value = "date", defaultValue = "0") long date) { long instantDate = (date == 0) ? Calendar.getInstance().getTimeInMillis() : date; Utility.checkRelationship(entity, state); // Getting the CURRENT rel if it exist Spliterator<Relationship> currentRelIterator = entity.getRelationships(RelationshipType.withName(Utility.CURRENT_TYPE), Direction.OUTGOING).spliterator(); Node newState = StreamSupport.stream(currentRelIterator, false).map(currentRel -> { Node currentState = currentRel.getEndNode(); Long currentDate = (Long) currentRel.getProperty("date"); // Creating the new node Map<String, Object> patchedProps = currentState.getAllProperties(); patchedProps.putAll(state.getAllProperties()); Node result = Utility.setProperties(db.createNode(Utility.labels(state.getLabels())), patchedProps); // Updating CURRENT state result = Utility.currentStateUpdate(entity, instantDate, currentRel, currentState, currentDate, result); return result; }).findFirst().orElseGet(() -> { throw new VersionerCoreException("Can't find any current State node for the given entity."); }); log.info(Utility.LOGGER_TAG + "Patched Entity with id {}, adding a State with id {}", entity.getId(), newState.getId()); return Stream.of(new NodeOutput(newState)); }
@Procedure(value = "graph.versioner.diff.from.previous", mode = DEFAULT) @Description("graph.versioner.diff.from.previous(state) - Get a list of differences that must be applied to the previous statusof the given one in order to become the given state") public Stream<DiffOutput> diffFromPrevious( @Name("state") Node state) { Optional<Node> stateFrom = Optional.ofNullable(state.getSingleRelationship(RelationshipType.withName(Utility.PREVIOUS_TYPE), Direction.OUTGOING)).map(Relationship::getEndNode); Stream<DiffOutput> result = Stream.empty(); if(stateFrom.isPresent()){ result = diffBetweenStates(stateFrom, Optional.of(state)); } return result; }
private void createRelationship(long nodeId, String link, RelationshipType type) { Long linkNodeId = findNodeId(link); if (linkNodeId != null) { inserter.createRelationship(nodeId, linkNodeId, type, null); linkCounter.increment(); } else { badLinkCount++; } }
private void dfs(WordDocumentInfo doc) { Node node = db.createNode(); GraphNodeUtil.createDocumentNode(doc, node); for(DocumentElementInfo elementInfo : doc.getSubElements()) { Node subNode = dfs_ele(elementInfo); node.createRelationshipTo(subNode, RelationshipType.withName(HAVE_SUB_ELEMENT)); } }
public static boolean isJavaCodeRelationship(Relationship rel){ return rel.isType(RelationshipType.withName(EXTEND)) ||rel.isType(RelationshipType.withName(IMPLEMENT)) ||rel.isType(RelationshipType.withName(THROW)) ||rel.isType(RelationshipType.withName(PARAM)) ||rel.isType(RelationshipType.withName(RT)) ||rel.isType(RelationshipType.withName(HAVE_METHOD)) ||rel.isType(RelationshipType.withName(HAVE_FIELD)) ||rel.isType(RelationshipType.withName(CALL_METHOD)) ||rel.isType(RelationshipType.withName(CALL_FIELD)) ||rel.isType(RelationshipType.withName(TYPE)) ||rel.isType(RelationshipType.withName(VARIABLE)); }
@Override public Relationship buildRelation(Node parent, Node child, DocumentRelationContext context) { String documentKey = context.getDocumentKey(); if(StringUtils.isBlank(documentKey)) { return null; } RelationshipType relationType = RelationshipType.withName( documentKey ); //check if already exists Iterable<Relationship> relationships = child.getRelationships(Direction.INCOMING,relationType); //find only relation between parent and child node List<Relationship> rels = StreamSupport.stream(relationships.spliterator(), false) .filter(rel -> rel.getStartNode().getId() == parent.getId()) .collect(Collectors.toList()); Relationship relationship; if(rels.isEmpty()) { relationship = parent.createRelationshipTo(child, relationType); if(log.isDebugEnabled()) log.debug("Create new Relation "+relationship); }else { relationship = rels.get(0); if(log.isDebugEnabled()) log.debug("Update Relation "+relationship); } return relationship; }
public double correlate(Node source, Node target, RelationshipType type, Direction dir, Object... more) { if (null == source) throw new IllegalArgumentException("Illegal 'source' argument in Problem.correlate(Node, Node, RelationshipType, Direction, Object...): " + source); if (null == target) throw new IllegalArgumentException("Illegal 'target' argument in Problem.correlate(Node, Node, RelationshipType, Direction, Object...): " + target); if (null == type) throw new IllegalArgumentException("Illegal 'type' argument in Problem.correlate(Node, Node, RelationshipType, Direction, Object...): " + type); if (null == dir) throw new IllegalArgumentException("Illegal 'dir' argument in Problem.correlate(Node, Node, RelationshipType, Direction, Object...): " + dir); if (source.equals(target)) return 1.0; try (Transaction ignore = graph.beginTx()) { PathExpander<Object> expander = null; if (null == more || 0 == more.length) expander = PathExpanders.forTypeAndDirection(type, dir); else { RelationshipType t = (RelationshipType) more[0]; Direction d = (Direction) more[1]; expander = PathExpanders.forTypesAndDirections(type, dir, t, d, Arrays.copyOfRange(more, 2, more.length)); } PathFinder<Path> finder = GraphAlgoFactory.allPaths(expander, 1 + count); Iterable<Path> paths = finder.findAllPaths(source, target); Set<Relationship> relationships = new HashSet<>(); Set<Set<Relationship>> expression = new HashSet<>(); for (Path path : paths) { Set<Relationship> item = new HashSet<>(); for (Relationship relationship : path.relationships()) { relationships.add(relationship); item.add(relationship); } expression.add(item); } BDD bdd = new BDD(expression, relationships); bdd.dump("bdd.gv"); return bdd.traverse(); } }