Prev |  | Next

## 7.3. Linked Lists

A powerful feature of using a graph database, is that you can create your own in-graph data structures — like a linked list.

This datastructure uses a single node as the list reference. The reference has an outgoing relationship to the head of the list, and an incoming relationship from the last element of the list. If the list is empty, the reference will point to it self.

Something like this:

Figure 7.1. Graph

To initialize an empty linked list, we simply create an empty node, and make it link to itself.

Query.

    CREATE root-[:LINK]->root // no ‘value’ property assigned to root
    RETURN root

Adding values is done by finding the relationship where the new value should be placed in, and replacing it with a new node, and two relationships to it.

Query.

    START root=node:node_auto_index(name = "ROOT")
    MATCH root-[:LINK*0..]->before,// before could be same as root
    after-[:LINK*0..]->root, // after could be same as root
    before-[old:LINK]->after
    WHERE before.value? < 25  // This is the value, which would normally
    AND 25 < after.value?   // be supplied through a parameter.
    CREATE before-[:LINK]->({value:25})-[:LINK]->after
    DELETE old

Deleting a value, conversely, is done by finding the node with the value, and the two relationships going in and out from it, and replacing with a new value.

Query.

    START root=node:node_auto_index(name = "ROOT")
    MATCH root-[:LINK*0..]->before,
    before-[delBefore:LINK]->del-[delAfter:LINK]->after,
    after-[:LINK*0..]->root
    WHERE del.value! = 10
    CREATE before-[:LINK]->after
    DELETE del, delBefore, delAfter

Copyright © 2013 Neo Technology

Prev | Up | Next
| Home |