我匹配了一些路径,并且我希望返回该路径。但我不需要整个节点,我只需要它们的 ID。我试过:
match path =
return path {id}
但是我遇到语法错误
您可以使用列表理解来获取每个路径中所有节点的 id(extract() 也可以):
match path = ...
return [node in nodes(path) | id(node)] as nodesInPath
这将为您提供每个节点的 neo4j 内部 id 的集合。如果您尝试使用自己的
id
属性,请在列表理解的投影部分中使用 node.id
。
有这样的事吗?
match path = ()--()
unwind(nodes(path)) as nodes
return {id : id(nodes)}
我知道这作为回应已经太晚了,但我希望这对以后的人有所帮助。 我试图做同样的事情,下面是我精心设计的解决方案。
示例设置
我在 Cypher 教程中使用了 Neo4j 示例中的数据子集。 您可以使用此密码查询列表创建您自己的示例图。
CREATE (TheMatrix:Movie {title:'The Matrix', released:1999,tagline:'Welcome to the Real World'})
CREATE (Keanu:Person {name:'Keanu Reeves', born:1964})
CREATE (Carrie:Person {name:'Carrie-Anne Moss', born:1967})
CREATE (Laurence:Person {name:'Laurence Fishburne', born:1961})
CREATE (Hugo:Person {name:'Hugo Weaving', born:1960})
CREATE (LillyW:Person {name:'Lilly Wachowski', born:1967})
CREATE (LanaW:Person {name:'Lana Wachowski', born:1965})
CREATE (JoelS:Person {name:'Joel Silver', born:1952})
CREATE (Keanu)-[:ACTED_IN {roles:['Neo']}]->(TheMatrix), (Carrie)-[:ACTED_IN {roles:['Trinity']}]->(TheMatrix), (Laurence)-[:ACTED_IN {roles:['Morpheus']}]->(TheMatrix), (Hugo)-[:ACTED_IN {roles:['Agent Smith']}]->(TheMatrix),(LillyW)-[:DIRECTED]->(TheMatrix), (LanaW)-[:DIRECTED]->(TheMatrix),(JoelS)-[:PRODUCED]->(TheMatrix)
我的方法
通过这种方式,您可以将路径解压到节点列表和关系列表,提取所需的属性,然后将它们打包回路径数组。
match path =(n) - [r*] - (m)
with nodes(path) as node_list, relationships(path) as rel_list
with reduce(acc=[], i in range (0, size(rel_list)) |
acc + [
{ actor_name: node_list[i].name, movie_title: node_list[i].title },
{ relationship: type(rel_list[i]), roles: rel_list[i].roles }
]) as path_list
return path_list[0..size(path_list)-1];
解释上面的代码的作用
match path =(n) - [r*] - (m)
// get list of nodes and list of relationships
with nodes(path) as node_list, relationships(path) as rel_list
// use reduce to loop through indices from 0 to size of rel_list.
// I'm using rel_list because the last index will get you the last node
// and a null relationship (since there is no relationship after the
// last node). We will take care of this null relationship below
with reduce(acc=[], i in range (0, size(rel_list)) |
// for each loop, extract the properties you need from node_list[i] and
// the properties you need from rel_list[i].
// You can either use the same keys for the properties (for e.g. the
// "roles" key below), or you can change the keys as you wish.
// Add the objects for the trimmed down node and relationship to acc[].
// Note that the syntax is `acc + [{node object}, {relationship
// object}]` because you cannot run 2 statements after the "|" in the
// reduce function. This is how you add multiple objects to the array
// in Cypher
acc + [
{ actor_name: node_list[i].name, movie_title: node_list[i].title },
{ relationship: type(rel_list[i]), roles: rel_list[i].roles }
]) as path_list
// remove the last element in the path_list to remove the
// aforementioned null relationship
return path_list[0..size(path_list)-1];
最终结果