Create relationship at run time by concatenating two values

I want to create relationship between nodes and relationship label should be assigned from a variable value. I am using GraphDatabase module from neo4j plugin for python for connecting to neo4j.


    def create_relationships(tx):
            result ="MATCH (a:NodeType1), (b:NodeType2)"
                            "MERGE (a)-[r:$related]->(b)"
                            "RETURN r", related = getLabelForRelationship())
            return result

Basically for any relation creation (a)-[:related]-(b), related string is not fixed so instead of string related I want to use a variable. Is this possible? Can someone please help me with this?

Hi @dhanashree.murge !

Can you use APOC?

Try this:


Hi @dhanashree.murge

How about this code.

    def create_relationships(tx, related):
        result ="MATCH (a:NodeType1), (b:NodeType2) "
                        "MERGE (a)-[r:" + related + "]->(b) "
                        "RETURN r")
        return result
1 Like

Thank you for response. But this solution also gives similar syntax error.

SyntaxError : Invalid input ' " ', expected whitespace or a rel type name.

Thank you @Bennu , I will try this.


This is the complete sample code.
I modified the HelloWorldExample.
You need to set the relationship name.

from neo4j import GraphDatabase

class HelloWorldExample:

    def __init__(self, uri, user, password):
        self.driver = GraphDatabase.driver(uri, auth=(user, password))

    def close(self):

    def print_relationships(self, related):
        with self.driver.session() as session:
            greeting = session.write_transaction(self.create_relationships, related)

    def create_relationships(tx, related):
        result ="MATCH (a:NodeType1), (b:NodeType2) "
                        "MERGE (a)-[r:" + related + "]->(b) "
                        "RETURN r")
        return result

if __name__ == "__main__":
    greeter = HelloWorldExample("bolt://localhost:7687", "neo4j", "hogehoge")

Thanks a lot @koji, I was passing related variable as an argument to function so it did not work earlier. Now I treated it as separate variable as you have shown and it worked!