Reputation: 40386
Say I have matched a collection of relationships:
MATCH a-[r:BELONGS_TO]->b
How can I iterate through each relationship and assign it an index? In pseudocode:
for i in range(0, # of r's)
r.order = i
Upvotes: 7
Views: 4898
Reputation: 67044
Depending on your requirements, you may be able to use the "internal" ID that the neo4j DB automatically assigns to every relationship (and node). Although every internal ID is unique, after a relationship (or node) is deleted, its internal ID can be reused by a new relationship (or node). Over time, the set of active internal IDs for relationships (and nodes) may no longer have a 0 origin and may not have contiguous integer values.
If the internal ID is adequate for your needs, then there is no need to add your own id
or index
property.
You can use the ID()
function to get the internal ID whenever you need it. For example, this is how you'd get the internal ID of every BELONGS_TO
relationship:
MATCH ()-[r:BELONGS_TO]->()
RETURN ID(r);
Upvotes: 0
Reputation: 8556
This should work:
MATCH (a)-[r:BELONGS_TO]->(b)
WITH collect(r) as rels
WITH rels, range(0, size(rels)) AS is
UNWIND is AS i
WITH rels[i] as rel, i
SET rel.order = i
Upvotes: 19
Reputation: 20185
You can hack it a bit :
MATCH (a)-[r:BELONGS_TO]->(b)
WITH collect(r) as relationships
UNWIND range(0, size(relationships)-1) as x
RETURN relationships[x]
Upvotes: 7