Java Code Examples for org.neo4j.graphdb.Node#createRelationshipTo()

The following examples show how to use org.neo4j.graphdb.Node#createRelationshipTo() . 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: Neo4jSingleInsertion.java    From graphdb-benchmarks with Apache License 2.0 6 votes vote down vote up
@Override
public void relateNodes(Node src, Node dest)
{
    try (final Transaction tx = ((GraphDatabaseAPI) neo4jGraph).tx().unforced().begin())
    {
        try
        {
            src.createRelationshipTo(dest, Neo4jGraphDatabase.RelTypes.SIMILAR);
            tx.success();
        }
        catch (Exception e)
        {
            tx.failure();
            throw new BenchmarkingException("unable to relate nodes", e);
        }
    }
}
 
Example 2
Source File: ReferenceExtractor.java    From SnowGraph with Apache License 2.0 6 votes vote down vote up
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();
	}
}
 
Example 3
Source File: GraphTransactionalImpl.java    From SciGraph with Apache License 2.0 6 votes vote down vote up
@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();
    }
  }
}
 
Example 4
Source File: Neo4jApiTransformationInjectConnectedSegments.java    From trainbenchmark with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void activate(final Collection<Neo4jConnectedSegmentsInjectMatch> matches) {
	for (final Neo4jConnectedSegmentsInjectMatch match : matches) {
		// create (segment2) node
		final Node segment2 = driver.getGraphDb().createNode(Neo4jConstants.labelSegment);
		segment2.setProperty(ModelConstants.ID, driver.generateNewVertexId());
		segment2.setProperty(ModelConstants.LENGTH, TrainBenchmarkConstants.DEFAULT_SEGMENT_LENGTH);

		// (segment2)-[:monitoredBy]->(sensor)
		segment2.createRelationshipTo(match.getSensor(), Neo4jConstants.relationshipTypeMonitoredBy);

		// (segment1)-[:connectsTo]->(segment2)
		match.getSegment1().createRelationshipTo(segment2, Neo4jConstants.relationshipTypeConnectsTo);
		// (segment2)-[:connectsTo]->(segment3)
		segment2.createRelationshipTo(match.getSegment3(), Neo4jConstants.relationshipTypeConnectsTo);

		// remove (segment1)-[:connectsTo]->(segment3)
		final Iterable<Relationship> connectsToEdges = match.getSegment1().getRelationships(Direction.OUTGOING,
				Neo4jConstants.relationshipTypeConnectsTo);
		for (final Relationship connectsToEdge : connectsToEdges) {
			if (connectsToEdge.getEndNode().equals(match.getSegment3())) {
				connectsToEdge.delete();
			}
		}
	}
}
 
Example 5
Source File: Neo4jLiveTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void testPersonCar() {
    graphDb.beginTx();
    Node car = graphDb.createNode(Label.label("Car"));
    car.setProperty("make", "tesla");
    car.setProperty("model", "model3");

    Node owner = graphDb.createNode(Label.label("Person"));
    owner.setProperty("firstName", "baeldung");
    owner.setProperty("lastName", "baeldung");

    owner.createRelationshipTo(car, RelationshipType.withName("owner"));

    Result result = graphDb.execute("MATCH (c:Car) <-[owner]- (p:Person) " +
            "WHERE c.make = 'tesla'" +
            "RETURN p.firstName, p.lastName");

    Map<String, Object> firstResult = result.next();
    Assert.assertEquals("baeldung", firstResult.get("p.firstName"));
}
 
Example 6
Source File: ReadOptimizedGraphity.java    From metalcon with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void createStatusUpdate(final long timestamp, final Node user,
		final StatusUpdate content) {
	// get last recent status update
	final Node lastUpdate = NeoUtils.getNextSingleNode(user,
			SocialGraphRelationshipType.UPDATE);

	// create new status update node
	final Node crrUpdate = NeoUtils.createStatusUpdateNode(content.getId());

	// prepare status update for JSON parsing
	content.setTimestamp(timestamp);
	content.setCreator(new User(user));

	// fill status update node
	crrUpdate.setProperty(Properties.StatusUpdate.TIMESTAMP, timestamp);
	crrUpdate.setProperty(Properties.StatusUpdate.CONTENT_TYPE,
			content.getType());
	crrUpdate.setProperty(Properties.StatusUpdate.CONTENT, content
			.toJSONObject().toJSONString());

	// update references to previous status update (if existing)
	if (lastUpdate != null) {
		user.getSingleRelationship(SocialGraphRelationshipType.UPDATE,
				Direction.OUTGOING).delete();
		crrUpdate.createRelationshipTo(lastUpdate,
				SocialGraphRelationshipType.UPDATE);
	}

	// add reference from user to current update node
	user.createRelationshipTo(crrUpdate, SocialGraphRelationshipType.UPDATE);
	user.setProperty(Properties.User.LAST_UPDATE, timestamp);

	// update ego network for this user
	this.updateEgoNetwork(user);
}
 
Example 7
Source File: ReadOptimizedGraphity.java    From metalcon with GNU General Public License v3.0 5 votes vote down vote up
/**
 * remove a followed user from the replica layer
 * 
 * @param followedReplica
 *            replica of the user that will be removed
 */
private void removeFromReplicaLayer(final Node followedReplica) {
	final Node prev = NeoUtils.getPrevSingleNode(followedReplica,
			SocialGraphRelationshipType.GRAPHITY);
	final Node next = NeoUtils.getNextSingleNode(followedReplica,
			SocialGraphRelationshipType.GRAPHITY);

	// bridge the user replica in the replica layer
	prev.getSingleRelationship(SocialGraphRelationshipType.GRAPHITY,
			Direction.OUTGOING).delete();
	if (next != null) {
		next.getSingleRelationship(SocialGraphRelationshipType.GRAPHITY,
				Direction.INCOMING).delete();
		prev.createRelationshipTo(next,
				SocialGraphRelationshipType.GRAPHITY);
	}

	// remove the followship
	followedReplica.getSingleRelationship(
			SocialGraphRelationshipType.FOLLOW, Direction.INCOMING)
			.delete();

	// remove the replica node itself
	followedReplica.getSingleRelationship(
			SocialGraphRelationshipType.REPLICA, Direction.OUTGOING)
			.delete();
	followedReplica.delete();
}
 
Example 8
Source File: DynamicResourceModuleIT.java    From SciGraph with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void setup() {
  try (Transaction tx = graphDb.beginTx()) {
    Node node = graphDb.createNode();
    Node node2 = graphDb.createNode();
    node.createRelationshipTo(node2, RelationshipType.withName("foo"));
    node.setProperty("foo", "bar");
    tx.success();
  }
  when(context.getUriInfo()).thenReturn(uriInfo);
  MultivaluedHashMap<String, String> map = new MultivaluedHashMap<>();
  map.put("foo", newArrayList("bar"));
  when(uriInfo.getQueryParameters()).thenReturn(map);
  when(uriInfo.getPathParameters()).thenReturn(new MultivaluedHashMap<String, String>());
}
 
Example 9
Source File: LouvainTest.java    From Neo4jSNA with Apache License 2.0 5 votes vote down vote up
@Override
    protected void initGraph() {
        Int2ObjectMap<Node> nodes = new Int2ObjectOpenHashMap<>();

        for (int i = 0; i < 9; i++) {
            Node n = db.createNode();
            n.setProperty("id", i);
            nodes.put(i, n);
        }

        for (int i = 0; i < 9; i++) {
            Node src = nodes.get(i);
            Node dst = (i + 1) % 3 != 0 ? nodes.get(i + 1) : nodes.get(i - 2);

            src.createRelationshipTo(dst, CommonsRelationshipTypes.KNOWS);
//            dst.createRelationshipTo(src, CommonsRelationshipTypes.KNOWS);
        }

        nodes.get(0).createRelationshipTo(nodes.get(3), CommonsRelationshipTypes.KNOWS);
        nodes.get(3).createRelationshipTo(nodes.get(6), CommonsRelationshipTypes.KNOWS);
        nodes.get(6).createRelationshipTo(nodes.get(0), CommonsRelationshipTypes.KNOWS);

//        for (int i = 0; i < 9; i += 3) {
//            Node src = nodes.get(i);
//            Node dst1 = nodes.get((i + 3) % 9);
//            Node dst2 = nodes.get((i + 6) % 9);
//            src.createRelationshipTo(dst1, CommonsRelationshipTypes.KNOWS);
// //            dst1.createRelationshipTo(src, CommonsRelationshipTypes.KNOWS);
//            src.createRelationshipTo(dst2, CommonsRelationshipTypes.KNOWS);
// //            dst2.createRelationshipTo(src, CommonsRelationshipTypes.KNOWS);
//        }

    }
 
Example 10
Source File: Neo4jGraphSerializer.java    From trainbenchmark with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void createEdge(final String label, final Object from, final Object to) {
	if (from == null || to == null) {
		return;
	}

	final Node source = (Node) from;
	final Node target = (Node) to;

	final RelationshipType relationshipType = relationship(label);
	source.createRelationshipTo(target, relationshipType);
}
 
Example 11
Source File: Neo4jApiTransformationRepairRouteSensor.java    From trainbenchmark with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void activate(final Collection<Neo4jRouteSensorMatch> matches) {
	for (final Neo4jRouteSensorMatch match : matches) {
		final Node route = match.getRoute();
		final Node sensor = match.getSensor();
		route.createRelationshipTo(sensor, Neo4jConstants.relationshipTypeRequires);
	}
}
 
Example 12
Source File: Neo4jApiTransformationRepairSwitchMonitored.java    From trainbenchmark with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void activate(final Collection<Neo4jSwitchMonitoredMatch> matches) {
	for (final Neo4jSwitchMonitoredMatch match : matches) {
		final Node sw = match.getSw();
		final Node sensor = driver.getGraphDb().createNode(Neo4jConstants.labelSensor);
		sensor.setProperty(ModelConstants.ID, driver.generateNewVertexId());
		sw.createRelationshipTo(sensor, Neo4jConstants.relationshipTypeMonitoredBy);
	}
}
 
Example 13
Source File: WordKnowledgeExtractor.java    From SnowGraph with Apache License 2.0 5 votes vote down vote up
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));
    }
}
 
Example 14
Source File: ReadOptimizedGraphity.java    From metalcon with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean deleteStatusUpdate(final Node user, final Node statusUpdate) {
	// get the status update owner
	final Node statusUpdateAuthor = NeoUtils.getPrevSingleNode(
			statusUpdate, SocialGraphRelationshipType.UPDATE);

	// the status update is not owned by the user passed
	if (!user.equals(statusUpdateAuthor)) {
		return false;
	}

	// update ego network
	this.updateReplicaLayerStatusUpdateDeletion(user, statusUpdate);

	// remove reference from previous status update
	final Node previousUpdate = NeoUtils.getPrevSingleNode(statusUpdate,
			SocialGraphRelationshipType.UPDATE);
	previousUpdate.getSingleRelationship(
			SocialGraphRelationshipType.UPDATE, Direction.OUTGOING)
			.delete();

	// update references to the next status update (if existing)
	final Node nextUpdate = NeoUtils.getNextSingleNode(statusUpdate,
			SocialGraphRelationshipType.UPDATE);
	if (nextUpdate != null) {
		statusUpdate.getSingleRelationship(
				SocialGraphRelationshipType.UPDATE, Direction.OUTGOING)
				.delete();
		previousUpdate.createRelationshipTo(nextUpdate,
				SocialGraphRelationshipType.UPDATE);
	}

	// delete the status update node
	statusUpdate.delete();
	return true;
}
 
Example 15
Source File: Neo4j.java    From SPADE with GNU General Public License v3.0 4 votes vote down vote up
@Override
    public boolean putEdge(AbstractEdge incomingEdge)
    {
        incomingEdge.removeAnnotation(ID_STRING);
        String bigHashCode = incomingEdge.bigHashCode();
        if (edgeBloomFilter.contains(bigHashCode))
        {
            Relationship edge;
            edge = edgeIndex.get(HASHCODE_LABEL, bigHashCode).getSingle();
            if (edge != null)
            {
                // if (LOG_PERFORMANCE_STATS == true) {
                //     // if there is heavy repetition of edges then comment out this logging or it will slow down ingestion
                //     logger.log(Level.INFO, "Edge (bigHashCode: " + bigHashCode + ") is already in db, skiping");
                // }
                return true;
            }
        }
        
        try(Transaction tx = graphDb.beginTx()){
        AbstractVertex childVertex = incomingEdge.getChildVertex();
        AbstractVertex parentVertex = incomingEdge.getParentVertex();

        try
        {
            String childVertexHash = childVertex.bigHashCode();
            String parentVertexHash = parentVertex.bigHashCode();
            Node childNode = localNodeCache.get(childVertexHash);
            Node parentNode = localNodeCache.get(parentVertexHash);

            if (childNode == null)
            {
                dbHitCountForEdge++;
                childNode = vertexIndex.get(HASHCODE_LABEL, childVertexHash).getSingle();
                if (childNode == null)
                {
                    // insert vertex if not in db
                    putVertex(childVertex);
                    childNode = localNodeCache.get(childVertexHash);
                }
                putInLocalCache(childNode, childVertexHash);
            }

            if (parentNode == null)
            {
                dbHitCountForEdge++;
                parentNode = vertexIndex.get(HASHCODE_LABEL, parentVertexHash).getSingle();
                if (parentNode == null)
                {
                    // insert vertex if not in db
                    putVertex(parentVertex);
                    parentNode = localNodeCache.get(parentVertexHash);
                }
                putInLocalCache(parentNode, parentVertexHash);
            }

            edgeCount++;
            reportProgress();

            Relationship newEdge = childNode.createRelationshipTo(parentNode, RelationshipTypes.EDGE);
            newEdge.setProperty(PRIMARY_KEY, bigHashCode);
            edgeIndex.add(newEdge, PRIMARY_KEY, bigHashCode);
            newEdge.setProperty(CHILD_VERTEX_KEY, childVertexHash);
            edgeIndex.add(newEdge, CHILD_VERTEX_KEY, childVertexHash);
            newEdge.setProperty(PARENT_VERTEX_KEY, parentVertexHash);
            edgeIndex.add(newEdge, PARENT_VERTEX_KEY, parentVertexHash);
            for (Map.Entry<String, String> currentEntry : incomingEdge.getCopyOfAnnotations().entrySet())
            {
                String key = currentEntry.getKey();
                String value = currentEntry.getValue();
                newEdge.setProperty(key, value);
                edgeIndex.add(newEdge, key, value);
            }
//            newEdge.setProperty(HASHCODE_LABEL, bigHashCode);
//            edgeIndex.add(newEdge, HASHCODE_LABEL, bigHashCode);
            newEdge.setProperty(ID_STRING, newEdge.getId());
            edgeIndex.add(newEdge, ID_STRING, Long.toString(newEdge.getId()));
            edgeBloomFilter.add(bigHashCode);

        } finally {
        	tx.success();
        }
        }
        return true;
    }
 
Example 16
Source File: WordKnowledgeExtractor.java    From SnowGraph with Apache License 2.0 4 votes vote down vote up
private Node dfs_ele(DocumentElementInfo ele) {
    Node node = db.createNode();
    if(ele == null) {
        System.out.println("Meet a null element in docx file:"
                + docxDirPath + "\n This result in a empty node created");
        return node;
    }

    if(ele instanceof PlainTextInfo) {
        GraphNodeUtil.createPlainTextNode((PlainTextInfo) ele, node);
    }
    else if(ele instanceof SectionInfo) {
        SectionInfo sectionEle = (SectionInfo) ele;
        GraphNodeUtil.createSectionNode(sectionEle, node);
        List<DocumentElementInfo> subElements = ele.getSubElements();
        String currentSectionContent =
                "<section>\n<h" + sectionEle.getLayer() + ">" + sectionEle.getTitle() + "</h" + sectionEle.getLayer() + ">";
        //String currentEnglishSectionContent = sectionEle.getEnglishTitle();
        for(DocumentElementInfo subEle : subElements) {
            Node subNode = dfs_ele(subEle);
            if(subEle instanceof SectionInfo) {
                currentSectionContent = currentSectionContent +
                        "\n" + subNode.getProperty(SECTION_CONTENT);
            }
            else if(subEle instanceof TableInfo) {
                currentSectionContent = currentSectionContent +
                        "\n" + subNode.getProperty(TABLE_CONTENT);
            }
            else if(subEle instanceof PlainTextInfo) {
                currentSectionContent = currentSectionContent +
                        "\n" + subNode.getProperty(PLAIN_TEXT_CONTENT);
            }
            node.createRelationshipTo(subNode, RelationshipType.withName(HAVE_SUB_ELEMENT));
        }
        node.setProperty(SECTION_CONTENT, currentSectionContent + "</section>\n");
        //node.setProperty(SECTION_ENGLISH_CONTENT, currentEnglishSectionContent);
    }
    else if(ele instanceof TableInfo) {
        GraphNodeUtil.createTableNode((TableInfo) ele, node);
        node.setProperty(TABLE_CONTENT,  ele.toHtml(false));
        //node.setProperty(TABLE_ENGLISH_CONTENT, ele.toHtml(true));
    }
    return node;
}
 
Example 17
Source File: GraphTestBase.java    From SciGraph with Apache License 2.0 4 votes vote down vote up
static protected Relationship addRelationship(String parentIri, String childIri,
    RelationshipType type) {
  Node parent = createNode(parentIri);
  Node child = createNode(childIri);
  return child.createRelationshipTo(parent, type);
}
 
Example 18
Source File: UniqueRelationshipFactory.java    From neo4jena with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a relationship of given type between subject and object nodes.
 * This method is not idempotent and would create duplicate relationships
 * if called repeatedly. 
 */
public Relationship create(Node subject, RelationshipType type, Node object) {
	Relationship relation = subject.createRelationshipTo(object, type);
	//relation.setProperty(NeoGraph.PROPERTY_URI, type.name());
	return relation;
}
 
Example 19
Source File: StoreGraphDependencyMojo.java    From maven-dependency-mapper with GNU Lesser General Public License v3.0 4 votes vote down vote up
private void registerDependency(String type, Node projectNode, Artifact artifact) {
    projectNode.createRelationshipTo(makeNode(artifact), MavenRelationships.getByName(type));
    getLog().info("Registered dependency of scope: " + type);
}
 
Example 20
Source File: ReadOptimizedGraphity.java    From metalcon with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void createFriendship(final Node following, final Node followed) {
	// try to find the replica node of the user followed
	Node followedReplica = null;
	for (Relationship followship : following.getRelationships(
			SocialGraphRelationshipType.FOLLOW, Direction.OUTGOING)) {
		followedReplica = followship.getEndNode();
		if (NeoUtils.getNextSingleNode(followedReplica,
				SocialGraphRelationshipType.REPLICA).equals(followed)) {
			break;
		}
		followedReplica = null;
	}

	// user is following already
	if (followedReplica != null) {
		return;
	}

	// create replica
	final Node newReplica = this.graph.createNode();
	following.createRelationshipTo(newReplica,
			SocialGraphRelationshipType.FOLLOW);
	newReplica.createRelationshipTo(followed,
			SocialGraphRelationshipType.REPLICA);

	// check if followed user is the first in following's ego network
	if (NeoUtils.getNextSingleNode(following,
			SocialGraphRelationshipType.GRAPHITY) == null) {
		following.createRelationshipTo(newReplica,
				SocialGraphRelationshipType.GRAPHITY);
	} else {
		// search for insertion index within following replica layer
		final long followedTimestamp = getLastUpdateByReplica(newReplica);
		long crrTimestamp;
		Node prevReplica = following;
		Node nextReplica = null;
		while (true) {
			// get next user
			nextReplica = NeoUtils.getNextSingleNode(prevReplica,
					SocialGraphRelationshipType.GRAPHITY);
			if (nextReplica != null) {
				crrTimestamp = getLastUpdateByReplica(nextReplica);

				// step on if current user has newer status updates
				if (crrTimestamp > followedTimestamp) {
					prevReplica = nextReplica;
					continue;
				}
			}

			// insertion position has been found
			break;
		}

		// insert followed user's replica into following's ego network
		if (nextReplica != null) {
			prevReplica.getSingleRelationship(
					SocialGraphRelationshipType.GRAPHITY,
					Direction.OUTGOING).delete();
			newReplica.createRelationshipTo(nextReplica,
					SocialGraphRelationshipType.GRAPHITY);
		}
		prevReplica.createRelationshipTo(newReplica,
				SocialGraphRelationshipType.GRAPHITY);
	}
}