Neoism relate if relationship doesn't exist

94 Views Asked by At

I've only just started using neoism and enjoying it so far. I've hit a bit of a problem and wondered if it my naivety of neoism or neoism itself that's at fault.

I've got a line in my go code:

agent.Relate(relation, node.Id() , neoism.Props{})

The issue is that if I run it more than once it will duplicate the relationship. Is there a way to create only if the relationship doesn't already exist - something similar to the GetOrCreateNodeFunction.

Or will I have to write some raw cql to check if the relationship already exists before running the statement above?

Thanks in advance

2

There are 2 best solutions below

1
On BEST ANSWER

There is not a native function or REST endpoint for creating unique directed relationships. You might assign a unique property value to each relationship and add a unique index on the relationship property, or you might use a cypher query and the CREATE UNIQUE clause.

http://neo4j.com/docs/stable/query-create-unique.html#_create_unique_relationships

0
On

You can use the following function which I am using for my code. It has an external dependency at

github.com/imdario/mergo

And the following generic function will work for any kind of node and relationships.

 func GetOrCreateRelationship(from *neoism.Node, to *neoism.Node, relType string, props neoism.Props) (relationship *neoism.Relationship) {
relationships, err := from.Relationships(relType)

if err == nil {
    for _, relationship := range relationships {
        endNode, err := relationship.End()

        if err != nil {
            continue
        }

        if endNode.Id() == to.Id() {
            newProps, err := relationship.Properties()

            if err != nil {
                return relationship
            }

            if err := mergo.Merge(&newProps, props); err != nil {
                relationship.SetProperties(newProps)
            }

            return relationship
        }
    }
}

relationship, err = from.Relate(relType, to.Id(), props)

if err != nil {
    log.Printf("Cannot create relationship: %s", err)
}

return
}