Jonas Malm
Jonas Malm

Reputation: 429

py2neo cypher create several relations to central node in for loop

just starting out with neo4j, py2neo and Cypher.

I have encountered the following problem and google and my knowledge of what to ask have not yet given me an answer or a helpful hint in the right direction. Anyway:

Problem: I don't know how to, in python/py2neo, create relations between a unique starting node and a number of following nodes that I create dynamically in a for loop.

Background: I have a json object which defines a person object, who will have an id, and several properties, such as favourite colour, favourite food etc.

So at the start of my py2neo script I define my person. After this I loop through my json for every property this person has.

This works fine, and with no relations I end up with a neo4j chart with several nodes with the right parameters.

If I'm understanding the docs right I have to make a match to find my newly created person, for each new property I want to link. This seems absurd to me as I just created this person and still have the reference to the person object in memory. But for me it is unclear on how to actually write the code for creating the relation. Also, as a relative newbie in both python and Cypher, best practices are still an unknown to me.

What I understand is I can use py2neo

graph = Graph(http://...)
tx = graph.begin()
p = Node("Person", id)
tx.create(p)

and then I can reference p later on. But for my properties, of which there can be many, I create a string in python like so (pseudocode here, I have a nice oneliner for this that fits my actual case with lambda, join, map, format and so on)

for param in params:
  par = "MERGE (par:" + param + ... )
  tx.append(par)
tx.process()
tx.commit()

How do I create a relation "likes" back to the person for each and every par in the for loop?

Or do I need to rethink my whole solution?

Help?! :-)

//Jonas

Upvotes: 0

Views: 507

Answers (1)

Jack Daniels
Jack Daniels

Reputation: 123

Considering you've created a node Alice and you want to create the other as dynamic, I'll suggest while dynamically parsing through the nodes, store it everytime (in the loop) in a variable, make a node out of it and then implement in Relationship Syntax. The syntax is

Relationship(Node_1, Relation, Node_2)

Now key thing to know here is type(Node_1) and type(Node_2) both will be Node.

I've stored all the nodes (only their names) from json in a list named nodes. Since you mentioned you only have reference to Alice a = ("Person", name:"Alice") for node in nodes: (excluding Alice) = Node(, name:"") = Relationship(a, ,

Make sure to iterate variable name, else it'll keep overwriting.

Upvotes: 1

Related Questions