0

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

Airomega
  • 574
  • 6
  • 22

2 Answers2

1

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

erezny
  • 46
  • 1
  • 3
  • Thanks for your response. I ended up doing just that - creating a cypher statement and running it via neoism.query. – Airomega Mar 25 '16 at 09:14
1

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
}
shivendra pratap singh
  • 1,318
  • 1
  • 13
  • 18