[英]Neo4j how to get (DISTINCT) all nodes and relationships with at least one node in common?
I have been experimenting with neo4j and cypher lately but I don't quite manage to get the following query correctly.我最近一直在试验 neo4j 和 cypher 但我不太能正确获得以下查询。 I would like to return all employees that share at least one project with a given employee and the projects they worked on.
我想退回与给定员工共享至少一个项目的所有员工以及他们从事的项目。 It is perhaps simpler if described with an example:
如果用一个例子来描述可能会更简单:
The desired outcome for the graph above for the input being employee 1 is:上图中输入为员工 1 的期望结果是:
Employee![]() |
Project![]() |
---|---|
0 ![]() |
A![]() |
1 ![]() |
A![]() |
1 ![]() |
B![]() |
4 ![]() |
A![]() |
I tried the following query but it returns duplicated relationships:我尝试了以下查询,但它返回重复的关系:
MATCH (a0:Employee {name:1})-[:WORKS]->(b0:Project)
MATCH (b0)<-[:WORKS]-(a:Employee)
MATCH (a)-[:WORKS]->(b:Project)
RETURN a.name AS employee, b.name AS project
ORDER BY employee, project
Employee![]() |
Project![]() |
---|---|
0 ![]() |
A![]() |
1 ![]() |
A![]() |
1 ![]() |
A![]() |
1 ![]() |
B![]() |
1 ![]() |
B![]() |
4 ![]() |
A![]() |
Thank you in advance for your help.预先感谢您的帮助。
Note: These queries can be used to create the graph above注意:这些查询可用于创建上面的图表
CREATE (:Employee {name: 0}),
(:Employee {name: 1}),
(:Employee {name: 2}),
(:Employee {name: 3}),
(:Employee {name: 4}),
(:Project {name: 'A'}),
(:Project {name: 'B'}),
(:Project {name: 'C'})
MATCH (e:Employee), (p:Project) WHERE e.name=0 AND p.name='A' CREATE (e)-[:WORKS]->(p)
MATCH (e:Employee), (p:Project) WHERE e.name=1 AND p.name='A' CREATE (e)-[:WORKS]->(p)
MATCH (e:Employee), (p:Project) WHERE e.name=1 AND p.name='B' CREATE (e)-[:WORKS]->(p)
MATCH (e:Employee), (p:Project) WHERE e.name=4 AND p.name='A' CREATE (e)-[:WORKS]->(p)
MATCH (e:Employee), (p:Project) WHERE e.name=3 AND p.name='C' CREATE (e)-[:WORKS]->(p)
After struggling with it for a couple hours, I found a solution.经过几个小时的努力,我找到了解决方案。 I am not sure it is efficient though.
我不确定它是否有效。 In a way, the answer was already in the question - DISTINCT.
在某种程度上,答案已经在问题中了——DISTINCT。 This query does the job:
这个查询完成了这项工作:
MATCH (a0:Employee {name:0})-[:WORKS]->(b0:Project)
MATCH (b0)<-[:WORKS]-(a:Employee)
WITH DISTINCT(a)
MATCH (a)-[:WORKS]->(b:Project)
RETURN a.name AS employee, b.name AS project
ORDER BY employee, project
You seem to want the answer to the question: given the projects a certain employee works at, find all employees working on those projects.您似乎想要这个问题的答案:给定某个员工从事的项目,找到从事这些项目的所有员工。
You can answer this with a simple query:您可以通过一个简单的查询来回答这个问题:
MATCH (:Employee {name:1})-[:WORKS]->(b:Project)
MATCH (a:Employee)-[:WORKS]->(b)
RETURN a.name AS employee, b.name AS project
ORDER BY employee, project
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.