Search code examples
springspring-bootneo4jneo4j-ogmspring-repositories

How to merge two existing nodes in neo4j using Spring, OGM and @RelationshipEntity


I am using Spring neo4j ogm and I have Entities already saved in database. Now I want to create new relationship between them with spring ogm. Problem is that i have only entities uuid in this moment, and I want to escape getEntityByUuid() which could get me entity object and then repo.save() would do the trick.

If i need to create custom query, can it be in repository in this format:

public interface EntityRepository extends Neo4jRepository<Entity, Long> {
    @Query("MATCH (e:Entity {uuid:$0}), (e2:Entity{uuid:$1}) CREATE (e)-[:MENTION{relationshipProperties...}]->(e2)")
    boolean createRelationshipBetweenExistingEntities(String  entity1uuid, String  entity2uuid, RelationshipNeo4j rel);

These are my classes:

public abstract class AbstractEntity {
@Id
@GeneratedValue
private Long id;
}
@RelationshipEntity(type = "MENTION")
public class RelationshipNeo4j extends AbstractEntity {
@Property
protected String type;
@Property
protected LocalDate date;
@StartNode
protected Entity start;
@EndNode
protected Entity end;
}

@NodeEntity
public class Entity extends AbstractEntity {
protected String name;
@Index(unique = true)
protected String  uuid;
protected String wikiURL;
protected String  description;
@Relationship(type="MENTION")
protected List<RelationshipNeo4j> relationships;
}

Solution

  • This is the closest I came:

    @Query("MATCH (e:Entity {uuid:{entity1uuid}}), (e2:Entity{uuid:{entity2uuid}}) CREATE (e)-[r:MENTION{uuid:{relationshipUuid},type:{type},date:{date}}]->(e2) RETURN e,e2,r")
    RelationshipNeo4j createRelationshipBetweenExistingEntities(String  entity1uuid, String  entity2uuid, String  relationshipUuid, String  type, String date);
    

    We can't inset into query non primitive types: https://markhneedham.com/blog/2017/12/01/neo4j-cypher-property-values-can-primitive-types-arrays-thereof/