3

Suppose I need to create unique node with email,

If I run the following code, it will creat 2 nodes with the same email

person_nod = Node("person", email="bob123@gmail.com")
graph.create(person_nod)

person_nod = Node("person", email="bob123@gmail.com")
graph.create(person_nod)

I have no idea how to avoid the duplicated node with neo4j

newBike
  • 14,385
  • 29
  • 109
  • 192

1 Answers1

9

First, if you want unique nodes, you should create a uniqueness constraint on label person and property email:

graph = Graph()
graph.schema.create_uniqueness_constraint('person', 'email')

Now you will get an error if you try to add a node that violates the uniqueness constraint. I.e. your second create statement will fail.

You can also merge the node instead of creating it. MERGE matches existing nodes or creates them if they do not exist:

person_node = graph.merge('person', property_key='email', property_value='email@email.com')

For merging see: http://py2neo.org/2.0/essentials.html#py2neo.Graph.merge

Martin Preusse
  • 9,151
  • 12
  • 48
  • 80