cancel
Showing results for 
Search instead for 
Did you mean: 

Head's Up! These forums are read-only. All users and content have migrated. Please join us at community.neo4j.com.

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.

ex.

    def create_relationships(tx):
            result = tx.run("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?

1 ACCEPTED SOLUTION

Hi @dhanashree.murge

How about this code.

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

View solution in original post

6 REPLIES 6

Bennu
Graph Fellow

Hi @dhanashree.murge !

Can you use APOC?

Try this:

Bennu

Thank you @Bennu , I will try this.

Hi @dhanashree.murge

How about this code.

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

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

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

@dhanashree.murge

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):
        self.driver.close()

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

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


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

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