org.neo4j.driver.types.Relationship Java Examples

The following examples show how to use org.neo4j.driver.types.Relationship. 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: Neo4JEdge.java    From neo4j-gremlin-bolt with Apache License 2.0 5 votes vote down vote up
Neo4JEdge(Neo4JGraph graph, Neo4JSession session, Neo4JElementIdProvider<?> edgeIdProvider, Neo4JVertex out, Relationship relationship, Neo4JVertex in) {
    Objects.requireNonNull(graph, "graph cannot be null");
    Objects.requireNonNull(session, "session cannot be null");
    Objects.requireNonNull(edgeIdProvider, "edgeIdProvider cannot be null");
    Objects.requireNonNull(out, "out cannot be null");
    Objects.requireNonNull(relationship, "relationship cannot be null");
    Objects.requireNonNull(in, "in cannot be null");
    // store fields
    this.graph = graph;
    this.session = session;
    this.edgeIdProvider = edgeIdProvider;
    // from relationship
    this.id = edgeIdProvider.get(relationship);
    this.label = relationship.type();
    // id field name (if any)
    String idFieldName = edgeIdProvider.fieldName();
    // copy properties from relationship, remove idFieldName from map
    StreamSupport.stream(relationship.keys().spliterator(), false).filter(key -> !key.equals(idFieldName)).forEach(key -> {
        // value
        Value value = relationship.get(key);
        // add property value
        properties.put(key, new Neo4JEdgeProperty<>(this, key, value.asObject()));
    });
    // vertices
    this.out = out;
    this.in = in;
    // initialize original properties
    originalProperties = new HashMap<>(properties);
    // this is a persisted edge
    newEdge = false;
}
 
Example #2
Source File: Neo4jBoltRelationship.java    From jetbrains-plugin-graph-database-support with Apache License 2.0 5 votes vote down vote up
public Neo4jBoltRelationship(Relationship rel) {
    this.id = String.valueOf(rel.id());
    this.types = Collections.singletonList(rel.type());
    this.propertyContainer = new Neo4jBoltPropertyContainer(rel.asMap());

    this.startNodeId = String.valueOf(rel.startNodeId());
    this.endNodeId = String.valueOf(rel.endNodeId());
}
 
Example #3
Source File: RemoteEntityConverter.java    From extended-objects with Apache License 2.0 5 votes vote down vote up
@Override
public Object convert(Object value) {
    if (value instanceof Node) {
        return sessionCache.getNode((Node) value);
    } else if (value instanceof Relationship) {
        return sessionCache.getRelationship((Relationship) value);
    }
    throw new XOException("Unsupported value type " + value);
}
 
Example #4
Source File: RemoteDatastoreRelationManager.java    From extended-objects with Apache License 2.0 5 votes vote down vote up
@Override
public RemoteRelationship findRelationById(RelationTypeMetadata<RelationshipMetadata<RemoteRelationshipType>> metadata, Long id) {
    String statement = String.format("MATCH (start)-[r:%s]->(end) WHERE id(r)=$id RETURN start,r,end",
            metadata.getDatastoreMetadata().getDiscriminator().getName());
    Record record = statementExecutor.getSingleResult(statement, parameters("id", id));
    Node start = record.get("start").asNode();
    Relationship relationship = record.get("r").asRelationship();
    Node end = record.get("end").asNode();
    return datastoreSessionCache.getRelationship(start, relationship, end);
}
 
Example #5
Source File: RemoteDatastoreRelationManager.java    From extended-objects with Apache License 2.0 5 votes vote down vote up
private StateTracker<RemoteRelationship, Set<RemoteRelationship>> getRelationships(RemoteNode source, RemoteRelationshipType type,
        RemoteDirection remoteDirection) {
    StateTracker<RemoteRelationship, Set<RemoteRelationship>> trackedRelationships = source.getState().getRelationships(remoteDirection, type);
    if (trackedRelationships == null) {
        String sourceIdentifier;
        switch (remoteDirection) {
        case OUTGOING:
            sourceIdentifier = "start";
            break;
        case INCOMING:
            sourceIdentifier = "end";
            break;
        default:
            throw new XOException("Direction not supported: " + remoteDirection);
        }
        String statement = String.format("MATCH (start)-[r:%s]->(end) WHERE id(%s)=$id RETURN start,r,end", type.getName(), sourceIdentifier);
        Result statementResult = statementExecutor.execute(statement, parameters("id", source.getId()));
        Set<RemoteRelationship> loaded = new LinkedHashSet<>();
        try {
            while (statementResult.hasNext()) {
                Record record = statementResult.next();
                Node start = record.get("start").asNode();
                Relationship relationship = record.get("r").asRelationship();
                Node end = record.get("end").asNode();
                RemoteRelationship remoteRelationship = datastoreSessionCache.getRelationship(start, relationship, end);
                loaded.add(remoteRelationship);
            }
        } finally {
            statementResult.consume();
        }
        trackedRelationships = new StateTracker<>(loaded);
        source.getState().setRelationships(remoteDirection, type, trackedRelationships);
    }
    return trackedRelationships;
}
 
Example #6
Source File: RemoteDatastoreSessionCache.java    From extended-objects with Apache License 2.0 5 votes vote down vote up
private RemoteRelationship getRelationship(Relationship relationship, RemoteNode startNode, RemoteNode endNode, RemoteRelationshipType type) {
    RemoteRelationship remoteRelationship = getRelationship(relationship.id(), startNode, type, endNode);
    if (!remoteRelationship.getState().isLoaded()) {
        remoteRelationship.getState().load(relationship.asMap());
    }
    return remoteRelationship;
}
 
Example #7
Source File: RepositoryIT.java    From sdn-rx with Apache License 2.0 4 votes vote down vote up
@Test
void saveEntityWithRelationshipWithProperties(
	@Autowired PersonWithRelationshipWithPropertiesRepository repository) {
	// given
	Hobby h1 = new Hobby();
	h1.setName("Music");

	int rel1Since = 1995;
	boolean rel1Active = true;
	LocalDate rel1LocalDate = LocalDate.of(1995, 2, 26);
	LikesHobbyRelationship.MyEnum rel1MyEnum = LikesHobbyRelationship.MyEnum.SOMETHING;
	CartesianPoint2d rel1Point = new CartesianPoint2d(0.0, 1.0);

	LikesHobbyRelationship rel1 = new LikesHobbyRelationship(rel1Since);
	rel1.setActive(rel1Active);
	rel1.setLocalDate(rel1LocalDate);
	rel1.setMyEnum(rel1MyEnum);
	rel1.setPoint(rel1Point);

	Hobby h2 = new Hobby();
	h2.setName("Something else");
	int rel2Since = 2000;
	boolean rel2Active = false;
	LocalDate rel2LocalDate = LocalDate.of(2000, 6, 28);
	LikesHobbyRelationship.MyEnum rel2MyEnum = LikesHobbyRelationship.MyEnum.SOMETHING_DIFFERENT;
	CartesianPoint2d rel2Point = new CartesianPoint2d(2.0, 3.0);

	LikesHobbyRelationship rel2 = new LikesHobbyRelationship(rel2Since);
	rel2.setActive(rel2Active);
	rel2.setLocalDate(rel2LocalDate);
	rel2.setMyEnum(rel2MyEnum);
	rel2.setPoint(rel2Point);

	Map<Hobby, LikesHobbyRelationship> hobbies = new HashMap<>();
	hobbies.put(h1, rel1);
	hobbies.put(h2, rel2);
	PersonWithRelationshipWithProperties clonePerson = new PersonWithRelationshipWithProperties(
		"Freddie clone");
	clonePerson.setHobbies(hobbies);

	// when
	PersonWithRelationshipWithProperties shouldBeDifferentPerson = repository
		.save(clonePerson);

	// then
	assertThat(shouldBeDifferentPerson)
		.isNotNull()
		.isEqualToComparingOnlyGivenFields(clonePerson, "hobbies");

	assertThat(shouldBeDifferentPerson.getName()).isEqualToIgnoringCase("Freddie clone");

	try (Session session = createSession()) {
		Record record = session.run(
			"MATCH (n:PersonWithRelationshipWithProperties {name:'Freddie clone'}) "
				+ "RETURN n, "
				+ "[(n) -[:LIKES]->(h:Hobby) |h] as Hobbies, "
				+ "[(n) -[r:LIKES]->(:Hobby) |r] as rels"
		).single();

		assertThat(record.containsKey("n")).isTrue();
		assertThat(record.containsKey("Hobbies")).isTrue();
		assertThat(record.containsKey("rels")).isTrue();
		assertThat(record.values()).hasSize(3);
		assertThat(record.get("Hobbies").values()).hasSize(2);
		assertThat(record.get("rels").values()).hasSize(2);

		assertThat(record.get("rels").values(Value::asRelationship)).
			extracting(
				Relationship::type,
				rel -> rel.get("active"),
				rel -> rel.get("localDate"),
				rel -> rel.get("point"),
				rel -> rel.get("myEnum"),
				rel -> rel.get("since")
			)
			.containsExactlyInAnyOrder(
				tuple(
					"LIKES", Values.value(rel1Active), Values.value(rel1LocalDate),
					Values.point(rel1Point.getSrid(), rel1Point.getX(), rel1Point.getY()),
					Values.value(rel1MyEnum.name()), Values.value(rel1Since)
				),
				tuple(
					"LIKES", Values.value(rel2Active), Values.value(rel2LocalDate),
					Values.point(rel2Point.getSrid(), rel2Point.getX(), rel2Point.getY()),
					Values.value(rel2MyEnum.name()), Values.value(rel2Since)
				)
			);
	}
}
 
Example #8
Source File: Neo4JSession.java    From neo4j-gremlin-bolt with Apache License 2.0 4 votes vote down vote up
private Edge loadEdge(Record record) {
    // relationship
    Relationship relationship = record.get(1).asRelationship();
    // edge id
    Object edgeId = edgeIdProvider.get(relationship);
    // check edge has been deleted
    if (!deletedEdges.contains(edgeId)) {
        // check we have record in memory
        Neo4JEdge edge = edges.get(edgeId);
        if (edge == null) {
            // nodes
            Node firstNode = record.get(0).asNode();
            Node secondNode = record.get(2).asNode();
            // node ids
            Object firstNodeId = vertexIdProvider.get(firstNode);
            Object secondNodeId = vertexIdProvider.get(secondNode);
            // check edge has been deleted (one of the vertices was deleted) or the vertices are not in the read partition
            if (deletedVertices.contains(firstNodeId) || deletedVertices.contains(secondNodeId) || !partition.containsVertex(StreamSupport.stream(firstNode.labels().spliterator(), false).collect(Collectors.toSet())) || !partition.containsVertex(StreamSupport.stream(secondNode.labels().spliterator(), false).collect(Collectors.toSet())))
                return null;
            // check we have first vertex in memory
            Neo4JVertex firstVertex = vertices.get(firstNodeId);
            if (firstVertex == null) {
                // create vertex
                firstVertex = new Neo4JVertex(graph, this, vertexIdProvider, edgeIdProvider, firstNode);
                // register it
                registerVertex(firstVertex);
            }
            // check we have second vertex in memory
            Neo4JVertex secondVertex = vertices.get(secondNodeId);
            if (secondVertex == null) {
                // create vertex
                secondVertex = new Neo4JVertex(graph, this, vertexIdProvider, edgeIdProvider, secondNode);
                // register it
                registerVertex(secondVertex);
            }
            // find out start and end of the relationship (edge could come in either direction)
            Neo4JVertex out = relationship.startNodeId() == firstNode.id() ? firstVertex : secondVertex;
            Neo4JVertex in = relationship.endNodeId() == firstNode.id() ? firstVertex : secondVertex;
            // create edge
            edge = new Neo4JEdge(graph, this, edgeIdProvider, out, relationship, in);
            // register with adjacent vertices
            out.addOutEdge(edge);
            in.addInEdge(edge);
            // register edge
            return registerEdge(edge);
        }
        // return edge
        return edge;
    }
    // skip edge
    return null;
}
 
Example #9
Source File: RemoteDatastoreRelationManager.java    From extended-objects with Apache License 2.0 4 votes vote down vote up
@Override
protected Relationship load(RemoteRelationship entity) {
    return fetch(entity.getId());
}
 
Example #10
Source File: RemoteDatastoreRelationManager.java    From extended-objects with Apache License 2.0 4 votes vote down vote up
private Relationship fetch(Long id) {
    Record record = statementExecutor.getSingleResult("MATCH ()-[r]->() WHERE id(r)=$id RETURN r", parameters("id", id));
    return record.get("r").asRelationship();
}
 
Example #11
Source File: RemoteDatastoreSessionCache.java    From extended-objects with Apache License 2.0 4 votes vote down vote up
public RemoteRelationship getRelationship(Node start, Relationship relationship, Node end) {
    RemoteNode startNode = getNode(start);
    RemoteNode endNode = getNode(end);
    RemoteRelationshipType type = new RemoteRelationshipType(relationship.type());
    return getRelationship(relationship, startNode, endNode, type);
}
 
Example #12
Source File: RemoteDatastoreSessionCache.java    From extended-objects with Apache License 2.0 4 votes vote down vote up
public RemoteRelationship getRelationship(Relationship relationship) {
    RemoteNode startNode = getNode(relationship.startNodeId());
    RemoteNode endNode = getNode(relationship.endNodeId());
    RemoteRelationshipType type = new RemoteRelationshipType(relationship.type());
    return getRelationship(relationship, startNode, endNode, type);
}