Search code examples
neo4jsetcypherincrement

How to set node properties as incrementing numbers?


I want to assign id to a group of nodes (not the id() one). From this answer I can return the increment of number along with the nodes:

MATCH (n) where n.gid="Tt" 
WITH collect(n) as nodes
WITH apoc.coll.zip(nodes, range(0, size(nodes))) as pairs
UNWIND pairs as pair 
RETURN pair[0].gid as gid, pair[1] as rowNumber

╒═════╤═══════════╕
│"gid"│"rowNumber"│
╞═════╪═══════════╡
│"Tt" │0          │
├─────┼───────────┤
│"Tt" │1          │
├─────┼───────────┤
│"Tt" │2          │
├─────┼───────────┤
│"Tt" │3          │
├─────┼───────────┤

However if I change the last line to

SET pair[0].id=pair[1]

then I got this error:

Invalid input '[': expected ":" (line 5, column 9 (offset: 145))
"set pair[0].id=pair[1]"
         ^

Is there a way to set the ids of the nodes to be incrementing numbers? Surely Cypher understands pair[0] alone as nodes; and if it's in the RETURN clause then pair[0].id still works. Why does this syntax not work in SET?

Follow up question: How to set node properties as incrementing numbers, but resetting the increment when the value of a different property changes?


Solution

  • This should work, wrapping the pair[0] in () to tell Neo4j that it's a node:

    MATCH (n) where n.gid="Tt" 
    WITH collect(n) as nodes
    WITH apoc.coll.zip(nodes, range(0, size(nodes))) as pairs
    UNWIND pairs as pair 
    SET (pair[0]).id = pair[1]