CYPHER store order of node relationships of the same label when I create

前端 未结 2 1444
庸人自扰
庸人自扰 2021-01-15 16:50

I have multiple relationships that stem from a node. Each of these relationships are of the same label. The relationships point to a child node (not neccesarily unique). Aft

相关标签:
2条回答
  • 2021-01-15 17:25

    You can use SET to increment or decrement properties of existing relations first.

    The following example shifts trueIndex of existing relations and pushes a new relation (to an existing child node) at index 0:

    MATCH (n:Root)-[r:HAS]->(c:Child) 
    WHERE id(n) = 0 
    SET r.trueIndex = r.trueIndex + 1
    WITH n, min(r.trueIndex) as indexStart, max(r.trueIndex) as indexEnd
    CREATE (n)-[r:HAS  {trueIndex:(indexStart-1)}]->(c:Child)
    WHERE id(c) = 12
    RETURN n,r,c
    

    You can modify the query according to your needs.

    Design wise, I agree with @jjaderberg 's answer, it would be simpler to keep a linked list to represent an array.

    0 讨论(0)
  • 2021-01-15 17:31

    Try keeping the child nodes in linked lists. The structure will look something like

    (p:Parent)-[r1:CHILDREN]->(c1:Child)-[r2:NEXT]->(c2:Child)-[r3:NEXT]->(c3:Child)
    

    This maintains the order of your child nodes and allows you to improve your interaction with the structure in two ways:

    1. Inserting a new node into this structure only involves changes to the relationships 'before' and 'after' the place that node is going, as opposed to the entire structure. For example, to insert newc between c1 and c2, you delete r2, create newc and create :NEXT relationships from c1 to newc to c2. Analogous for other operations: all your alterations are now local within the structure.

    2. You use relationships and their types to structure your data, instead of relationship properties. This is more flexible and almost always more performant (sometimes much more performant).

    To read a single child from this structure you now use your trueindex to declare the depth in the linked list at which to find the node, i.e.

    MATCH (parent:Parent {parentId: 1234})-[:CHILDREN]->()-[:NEXT*3]->(child)
    RETURN child
    

    and to retrieve a parent with all its children

    MATCH (parent:Parent {parentId: 1234})-[:CHILDREN|NEXT*]->(child)
    RETURN parent, COLLECT(child) as children
    
    0 讨论(0)
提交回复
热议问题