将查询结果合并到一个唯一的列表中 - Neo4j

时间:2017-01-24 09:31:54

标签: neo4j cypher unique union

给定一个关键字,我想找到所有包含关键字的文章,他们的参考文献和所有论文的作者。我尝试过使用3种方法。

方法1将结果合并到一个列表中,但这导致列表中的重复条目(论文)。

MATCH (k:keyword)-[AREAOF]->(f:fieldOfStudy {fieldName: "fos1"}) 
WITH k
MATCH (p:paper)-[:CONTAINS]->(k)
WITH p
MATCH (p)-[:REFERENCES]->(r:paper)
WITH p,r
MATCH (c:paper)-[:REFERENCES]->(p)
WITH [c,p,r] as papers
MATCH (a:author)-[:PUBLISHED]->(p:paper)
WHERE p in papers
return a,p

方法2 - 使用+运算符 我尝试做类似于this的操作,但是我遇到了类型不匹配错误。

MATCH (k:keyword)-[AREAOF]->(f:fieldOfStudy {fieldName: "fos1"}) 
WITH k 
MATCH (p:paper)-[:CONTAINS]->(k) 
WITH p 
MATCH (p)-[:REFERENCES]->(r:paper) 
WITH p,r 
MATCH (c:paper)-[:REFERENCES]->(p) 
RETURN p+r

错误:

Type mismatch: expected List<Node> but was Node (line 8, column 14 (offset: 229))
"    return p+r"
              ^

方法3 - 使用UNION

第一种方法失败,因为每个结果都显示代表论文之间的联系。即 - [:参考] - &gt; p - [:REFERENCES] - &gt; r。为了获得一维结果,我尝试使用UNION。这有效并获得了一份独特的论文清单,但我无法使用输出来查询作者。

MATCH (k:keyword)-[AREAOF]->(f:fieldOfStudy {fieldName: "fos1"}) 
WITH k
MATCH (p:paper)-[:CONTAINS]->(k)
RETURN p as papers
UNION 
MATCH (k:keyword)-[AREAOF]->(f:fieldOfStudy {fieldName: "fos1"}) 
WITH k
MATCH (p:paper)-[:CONTAINS]->(k)
WITH p
MATCH (p)-[:REFERENCES]->(r:paper)
RETURN r as papers
UNION
MATCH (k:keyword)-[AREAOF]->(f:fieldOfStudy {fieldName: "fos1"}) 
WITH k
MATCH (p:paper)-[:CONTAINS]->(k)
WITH p
MATCH (c:paper)-[:REFERENCES]->(p)
RETURN c as papers

在这种情况下,我怎样才能得到最终答案(论文)并找到他们的作者?即

(a:author)-[:PUBLISHED]->(p:paper)
WHERE p in papers

3 个答案:

答案 0 :(得分:1)

经过一些进一步的研究后,我使用方法1然后使用UNWIND将答案转换为单个列表。由于这包含重复,我使用distinct()来过滤掉重复的条目。结果如下

MATCH (k:keyword)-[AREAOF]->(f:fieldOfStudy {fieldName: "fos1"}) 
WITH k
MATCH (p:paper)-[:CONTAINS]->(k)
WITH p
MATCH (p)-[:REFERENCES]->(r:paper)
WITH p,r
MATCH (c:paper)-[:REFERENCES]->(p)
WITH [c,p,r] as papers
UNWIND papers as pap
WITH distinct(pap) as papers
MATCH (a:author)-[:PUBLISHED]->(p:paper)
WHERE p in [papers]
return a,p

答案 1 :(得分:1)

通过使用0-1变量关系匹配论文并省略方向,您可以非常轻松地获得所需的所有论文。

以下是可行的方法:

MATCH (k:keyword)-[:AREAOF]->(:fieldOfStudy {fieldName: "fos1"}) 
MATCH (p:paper)-[:CONTAINS]->(k)
WITH p
MATCH (p)-[:REFERENCES*0..1]-(paper:Paper)
WITH DISTINCT paper
MATCH (a:author)-[:PUBLISHED]->(paper)
RETURN a, paper

密钥位于无向:REFERENCES匹配:

MATCH (p)-[:REFERENCES*0..1]-(paper:Paper)

这将遍历0到1:REFERENCES关系,意思是&#34; paper&#34;将包括p,以及通过a:REFERENCES关系在任一方向链接到p的任何节点,因此您将获得引用p的论文以及引用的论文。

答案 2 :(得分:0)

您可以collect将论文列入名单:

MATCH ...
WITH somePaper, collect(p) AS papers
WHERE somePaper IN papers
RETURN somePaper