title: Converting a star-topology to a linked list in Neo4j
body: <p>When I initially created my data set I thought a star topology would be nice, but now that I've gotten some sample data, I'd rather be using a <a href="https://stackoverflow.com/questions/15645938/neo4j-linked-list-multiple-nodes">linked list</a> topology. Now I want to do an in-place conversion using Cypher only, and in one call. Is this possible?</p>
  
  <p>To use a simplified example: a <code>Blog</code> node can have several children <code>Post</code> nodes, so I attached them directly like this:</p>
  
  <pre><code>CREATE (a:Blog), (a)-[:HAS]-&gt;(b:Post), (a)-[:HAS]-&gt;(c:Post)
  RETURN a,b,c
  </code></pre>
  
  <p>Now as my design moves along, I think I'd rather have this as a linked list, something like this (assuming the <code>:FIRST</code> post is already created):</p>
  
  <pre><code>MATCH (a:Blog)-[r:FIRST]-&gt;(b:Post)
  CREATE (a)-[:FIRST]-&gt;(c:Post)-[:PREV]-&gt;(b)
  DELETE r
  RETURN a,b,c
  </code></pre>
  
  <p>So I can code the linked list fine. What I need to do is to convert the old star topologies to the new linked list format. I tried a bunch of things but nothing worked, so here is my best guess, but is completely non-functional code: </p>
  
  <pre><code>MATCH (b:Blog)-[:HAS]-(p:Post)
  WITH b, collect(p) as posts
  CREATE b-[:FIRST]-&gt;posts[0]
  FOREACH( i IN range(1,len(posts)-1) |
      CREATE posts[i]-[:PREV]-&gt;posts[i-1]
  )
  RETURN b,p
  </code></pre>
  
  <p>Indexing collections doesn't seem to work in a <code>CREATE</code> statement (neither inside or outside the <code>FOREACH</code>). </p>
  
  <p>Any way to achieve this translation?</p>
  
  <p><strong>EDIT</strong>
  I thought an additional way might be to tag the posts with ordinal values and do some iteration over sequential ordinals, but I get a syntax error trying to add the ordinals:</p>
  
  <pre><code>MATCH (b:Blog)-[:HAS]-(p:Post)
  WITH b, collect(p) as posts
  FOREACH( i in range(0,length(posts)) |
      SET posts[i].ordinal = i
  }
  </code></pre>
  
  <p>The syntax error is:</p>
  
  <pre><code>Invalid input '[': expected an identifier character, node labels, a property map, a relationship pattern, '(', '.' or '=' (line 4, column 14)
  "    SET posts[i].ordinal = i"
                ^
  </code></pre>
  
  <p><strong>EDIT/2</strong></p>
  
  <p>Another idea I had was to put the linked-list code inside the <code>FOREACH</code>, but this fails because <code>MATCH</code> cannot be used inside <code>FOREACH</code>. First I created and attached a dummy <code>(b:Blog)-[:FIRST]-&gt;(p:Post)</code> relationship, then wrote this query (which doesn't work):</p>
  
  <pre><code>MATCH (f)&lt;-[:FIRST]-(b:Blog)-[:HAS]-&gt;(p:Post)
  WITH b, collect(p) as posts
  FOREACH( x IN posts |
      MATCH (b)-[r:FIRST]-&gt;(f) 
      DELETE r
      CREATE (b)-[r2:FIRST]-&gt;(x), (x)-[:PREV]-&gt;(f)
  )
  RETURN b-[*0..1]-()
  </code></pre>