Ricardo Saporta
Ricardo Saporta

Reputation: 55340

create relationships between nodes in parallel

Using cypher and neo4j 2.0.

Given two sets of node ids (of equal length) and a set of weights, I'd like to create a relationship between the corresponding nodes and set the weight as a property. For example if I have the following three lists:

node list 1: (101, 201, 301)  
node list 2: (102, 202, 302)
weights:     (0.1, 0.6, 0.25)

I would like to create the following representation

 101 - knows {w : .1}  - 102
 201 - knows {w : .6}  - 202
 301 - knows {w : .25} - 302

but NOT, for example, 101 - knows - 302

I can do this by iterating over my parameters and then creating the individual queries. Is there a way to batch run this, passing my lsits as parameters and asking cypher to match the nodes & properties in order?


I thought for a moment that using parameters in the following fashion would work, but it instead creates all permutations of relationships (as expected) and assigns as the entire list of weights as a property to each relationship.

{
    "query": 
       "START a1=node({starts}), a2=node({ends}) 
        CREATE UNIQUE a1-[r:knows {w : {weights}}]-a2 
        RETURN type(r), r.w, a1.name, a2.name",

    "params": {
        "starts"  : [101, 201, 301],
        "ends"    : [102, 202, 302],
        "weights" : [0.1, 0.6, 0.25]
    }
}

Upvotes: 1

Views: 595

Answers (1)

Michael Hunger
Michael Hunger

Reputation: 41676

How large are your lists in real life? I'd probably send in one triple at a time.

Otherwise you should be able to use a collection and foreach to do what you want:

START a1=node({starts}), a2=node({ends}) 
FOREACH(w in filter(w in weights : head(w)=id(a1) AND head(tail(w))=id(a2)) :
  CREATE UNIQUE a1-[r:knows {w : last(w)}]-a2 
)

"params": {
        "starts"  : [101, 201, 301],
        "ends"    : [102, 202, 302],
        "weights" : [[101,102,0.1], [201,202,0.6], [301,302,0.25]]
}

Upvotes: 1

Related Questions