Reputation: 3459
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?
Upvotes: 4
Views: 2868
Reputation: 147
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"
)
Upvotes: 0
Reputation: 267
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))
Upvotes: 0
Reputation: 582
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()
Upvotes: 4
Reputation: 454
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')
Upvotes: 2