How do I check to see if a node exists before creating it in neomodel
? Is there a way other than filter that will optimize my code?
Asked
Active
Viewed 2,118 times
5 Answers
2
I have created my own query to do that. Check if it helps.
def exists(node=None, property=None, value=None):
filter_node = (":" + node) if node != None else ''
filter_value = ("{" + property + ": '" + value + "'}") if property != None and value != None else ''
return db.cypher_query("MATCH(n" + filter_node + filter_value + ")" + " return count(n) > 0 as exists;" )[0][0][0]
exists(node='User')

Felipe Santiago
- 414
- 6
- 16
2
You can use first_or_none to check if a node exists.
Example:
person = Person.nodes.first_or_none(name='James')
if person == None:
personNew = Person(name='James').save()

Raman Kishore
- 542
- 2
- 12
0
bit extending on @raman Kishore's answer, I did this, cause I wanted to check if object's exists and also, sometimes I would insert an ID for myself because it came from another DB and I wanted to keep compatibility, so did the following:
class DefaultMixin:
date_added = DateTimeProperty()
nodes: NodeSet # makes pycharm smarter
def exists(self, **filters):
if not filters:
if not self.id:
raise KeyError('no filters or id provided')
filters['id'] = self.id
return bool(self.nodes.first_or_none(**filters))

yovel cohen
- 267
- 3
- 12
0
I created a decorator over each of my StructuredNode classes, which checks for the node upon initialization.
def check_if_node_exists(node):
def node_checker(**kwargs):
result = node.nodes.first_or_none(**kwargs)
if result == None:
print("Creating New Node")
return node(**kwargs).save()
print("Returning Existing Node")
return result
return node_checker
@check_if_node_exists
class Employee(StructuredNode):
name = StringProperty()
To call it, just create an instance of the class:
employee1 = Employee(
name = "test_name"
)

Phillip Ng
- 45
- 6