Create unique relationship property in FOREACH in neo4j

I'm trying to accomplish something pretty simple in python, but not so good in Neo4j. I would appreciate any comments and suggestions for improving the procedure!

In a Python script, I am trying to create a link as well as its property for each pair of two nodes. From parsing the data (not the csv file), I ended up with a 3-column dataframe like this:

name1    name2    points
===========================
Jack     Sara     0.3
Jack     Sam      0.4
Jack     Jill     0.2
Mike     Jack     0.4
Mike     Sara     0.5    
...

      

From now on, I would like to create all the nodes for people: Jack, Sarah, Sam, Mike, etc., and also their relationship to the property name dots.

I first tried to map all nodes and then use "FOREACH" to update the relationship property one at a time.

tx = graph.cypher.begin()
qs2 = "MATCH (p1:person {name:"Jack"}), (p2:person) 
       WHERE p2.name IN ["Sara","Jill","Mike"] 
       FOREACH (r IN range(10) | 
         CREATE (p1)-[:OWES TO {score:{score_list}[r]}]->(p2))"

      

The above statement does not return what I expected. Instead of mapping one node to another, it calls all the nodes in p2 and creates a link between paris, resulting in multiple copies of the same information.

Is there a notation to refer to one node at a time? If you think there is a better approach than the one above, please share with me. Thank!

+3


source to share


1 answer


The easiest way is to export the import data to a csv file and use the command LOAD CSV

in cypher.

LOAD CSV WITH HEADERS FROM <url> AS csvLine
MATCH (p1:Person {name:csvLine.name1}), (p2:Person {name:csvLine.name2})
CREATE (p1)-[:OWES_TO {score:csvLine.points}]->(p2)

      

If you cannot use this approach, you can use the parameterized Cypher statement with a transactional http endpoint . Parameter is a single element map containing an array of your data structure. At the http level, the request body will look like this:

{
   "statements": [
       {
           "parameters": {
               "data": [
                   {
                       "name1": "Jack", "name2": "Sara", "points": 0.3 
                   }, 
                   {
                       "name1": "Jack", "name2": "Sam", "points": 0.4
                   }, 
                   {
                       "name1": "Jack", "name2": "Jill", "points": 0.2
                   }  // ...
               ]
           }, 
           "statement": "UNWIND {data} AS row     
                         MATCH (p1:Person {name:row.name1}), (p2:Person {name:row.name2})
                         CREATE (p1)-[:OWES_TO {row.points}]->(p2)"
       }
   ]
}

      



update comment below

Q: How can I create parameters from pyhton? A: use python json module

import json
json.dumps({'data':[{'name1':'Jack', 'name2':'Sara', 'points':0.3},{'name1':'Jack', 'name2':'Sam', 'points':0.4}]})

      

+3


source







All Articles