Search code examples
neo4jcypherpy2neo

How to Set a property on a node based on function argument


Trying to write a generic function in py2neo that can update any node property in Neo4j based on property and value passed in arguments. I tried something like this

def updateUserProfile(self, property, value):

    query = """
    MATCH (n { username: {user} }) SET n.{property} = {value} RETURN n
    """

    return graph.cypher.execute(query, user=self.username, property=property, value=value)

But I get an error py2neo.cypher.error.statement.InvalidSyntax: Invalid input '{': expected whitespace or a property key name (line 2, column 38 (offset: 46)) "MATCH (n { username: {user} }) SET n.{property} = {value} RETURN n"

It is pointing at {property}. Is it correct to specify property to set like this ?


Solution

  • No you can't set properties like this.

    The best way to do it, is to use a dict for your properties :

    def updateUserProfile(self, property, value):
    
        query = """
        MATCH (n { username: {props}.user }) SET n += {props} RETURN n
        """
        props = {}
        props["user"] = self.username
        props[property] = value
        return graph.cypher.execute(query, {"props": props})