Head's Up! These forums are read-only. All users and content have migrated. Please join us at community.neo4j.com.
11-11-2021 04:05 AM
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?
Solved! Go to Solution.
11-11-2021 02:09 PM
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
11-11-2021 04:07 AM
11-11-2021 02:09 PM
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
11-11-2021 10:55 PM
Thank you for response. But this solution also gives similar syntax error.
error:
SyntaxError : Invalid input ' " ', expected whitespace or a rel type name.
11-11-2021 11:35 PM
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()
11-12-2021 02:00 AM
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!
All the sessions of the conference are now available online