Cypher - 数字有序关系

时间:2018-06-07 13:42:56

标签: neo4j cypher

我在一个密码查询上磕磕绊绊。我想创建一个关系,其中存在基于每个指令的整数属性的隐式顺序。例如,我想将address_1与address_2和address_2匹配到address_3,等等WHERE条件适用时。以下是尝试的声明:

MATCH (i:Instruction), (i2:Instruction)
 WHERE i.address < i2.address AND i.vars_written = i2.vars_read
MERGE (i)-[r:USED_BY]->(i2)
RETURN i, i2, r

问题是较低的数字地址将映射到适合WHERE条件的所有其他地址,而不仅仅是相关的地址 - 创建不应该存在的其他关系,例如address_1到address_3。

一条指令可能有多个USED_BY关系,但是一旦另一条指令具有相同的vars_written属性,它就应该开始一个新的USED_BY关系。

要提供具体示例,请考虑以下4个节点:

Index 1 parameters: {
  address: 1
  vars_written: var_b
  vars_read: var_a
}

Index 2 parameters: {
  address: 2
  vars_written: var_c
  vars_read: var_b
}

Index 3 parameters: {
  address: 3
  vars_written: var_c      <- Same vars_written as Index 2
  vars_read: var_b
}

Index 4 parameters: {
  address: 4
  vars_written: var_e   
  vars_read: var_c         <- var_c was overwritten in Index 3, should NOT map to Index 2
}

产地:

1 -[USED_BY]-> 2
1 -[USED_BY]-> 3
2 -[USED_BY]-> 4   (This should not be made because 3 should only map to 4!)
3 -[USED_BY]-> 4

1 个答案:

答案 0 :(得分:1)

感谢Neo4J团队回答他们的Slack频道:

MATCH (i:Instruction), (i2:Instruction)
 WHERE i.address < i2.address AND i.vars_written = i2.vars_read
WITH i, i2 ORDER BY i2.address ASC // <-- order the i2 by it's address
WITH i, head(collect(i2)) as i2 // <-- collect all of the matches and take the first
MERGE (i)-[r:USED_BY]->(i2)
RETURN i, i2, r