0

For example, can I have such a command that generate the increment of number?

MATCH (n) 
RETURN n, number_increment

node A   1
node B   2
node C   3
node D   4

I want to assign id to a group of nodes (not the id(n) one) and I need a chain of increasing number. Is this doable in Cypher or I need to use another language?

Ooker
  • 1,969
  • 4
  • 28
  • 58

2 Answers2

1

Looks like you want something like a row number. There isn't a direct way to do it in cypher, but there are a number of different solutions. One way is using the apoc.coll.zip function and manipulating the result into collections,

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

(Be careful though, the above query selects all nodes in the store, so may take a while if you have a huge number of nodes)

Ooker
  • 1,969
  • 4
  • 28
  • 58
aldrin
  • 4,482
  • 1
  • 33
  • 50
  • we can change `WITH collect(n) as nodes` to `WITH collect(n.name) as nodes` to reduce the result length – Ooker Oct 27 '21 at 07:09
  • Playing with this I get some weird results. Can you help? [Some weird results of apoc.coll.zip()](https://stackoverflow.com/q/69736707/3416774) – Ooker Oct 27 '21 at 10:11
  • Follow up question: [How to set node properties as increasing numbers?](https://stackoverflow.com/q/70799657/3416774) – Ooker Jan 21 '22 at 10:15
1

This will work.

MATCH(n)
WITH RANGE(1, COUNT(n)) AS indexes, COLLECT(n) AS nodes
FOREACH(i IN indexes | SET (nodes[i-1]).myID = i)
WITH nodes UNWIND nodes AS node
RETURN node
  • doesn't work to me. It return `V2` and no property is set. I cut the line `WITH nodes UNWIND nodes AS node` and just `RETURN nodes` and it returns `V1`. Weird – Ooker Oct 27 '21 at 10:30