【问题标题】:Add incremental property to nodes in a chain of nodes向节点链中的节点添加增量属性
【发布时间】:2017-12-14 09:50:02
【问题描述】:

我有一个节点链,我想为每个节点添加一个属性"DtaID",并且该值应该在链中递增。有没有办法用 Cypher 做到这一点?

【问题讨论】:

    标签: neo4j cypher


    【解决方案1】:

    我假设你有一个这样格式的节点链:

    create (:Node)-[:LINK]->(:Node)-[:LINK]->(:Node)-[:LINK]->(:Node)-[:LINK]->(:Node)-[:LINK]->(:Node)-[:LINK]->(:Node)
    

    然后我使用了这个 Cypher:

    // Get the path between the start and end nodes, including both
    MATCH p = (start:Node)-[:LINK*]->(end:Node)
    WHERE NOT (end)-[:LINK]->() AND NOT ()-[:LINK]->(start)
    // extract the nodes of p and calc an array of indexes to 
    // access each node in the array of nodes called `nodes`.
    WITH nodes(p) as nodes, range(0, size(nodes(p))) AS indexes
    // unwind indexes as index...
    UNWIND indexes AS index
    // set the value of `DtaID` property of each nodes to the index value.
    // That is: the node 0 will have `DtaID` equal to 0.
    // I'm assuming that you need an increment by one. If you need a
    // different increment you can do calculations here. For example:
    // SET (nodes[index]).DtaID = index * 10 to increment by 10.
    SET (nodes[index]).DtaID = index
    

    结果:

    ╒═══════════╕
    │"n"        │
    ╞═══════════╡
    │{"DtaID":0}│
    ├───────────┤
    │{"DtaID":1}│
    ├───────────┤
    │{"DtaID":2}│
    ├───────────┤
    │{"DtaID":3}│
    ├───────────┤
    │{"DtaID":4}│
    ├───────────┤
    │{"DtaID":5}│
    ├───────────┤
    │{"DtaID":6}│
    └───────────┘
    

    如果需要使用第一个节点的DtaID的值作为基值,可以将第一个节点传递给WITH子句,在计算中使用。

    MATCH p = (start:Node)-[:LINK*]->(end:Node)
    WHERE NOT (end)-[:LINK]->() AND NOT ()-[:LINK]->(start)
    WITH start, nodes(p) as nodes, range(0, size(nodes(p))) AS indexes
    UNWIND indexes AS index
    SET (nodes[index]).DtaID = start.DtaID + index
    

    【讨论】:

    • 非常适合我。非常感谢你,最好的问候,安德烈亚斯
    • @AndreasKuczera 嗨!不客气!如果此答案已解决您的问题,请单击复选标记考虑accepting it。这向更广泛的社区表明您已经找到了解决方案,并为回答者和您自己提供了一些声誉。没有义务这样做。
    • 感谢您的建议,不知道这个。最好的问候,安德烈亚斯
    • @AndreasKuczera 不客气,安德烈亚斯!我建议您take a tour in the system 以更好地了解 StackOverflow。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-03
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 2023-03-27
    相关资源
    最近更新 更多