Cypher查询以按属性查找与其他节点不相关的节点

Cypher查询以按属性查找与其他节点不相关的节点

本文介绍了Cypher查询以按属性查找与其他节点不相关的节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下数据库结构:

Consider the following DB structure:

为方便起见,您可以使用以下方法创建它:

For your convenience, you can create it using:

create (p1:Person {name: "p1"}),(p2:Person {name: "p2"}),(p3:Person {name: "p3"}),(e1:Expertise {title: "Exp1"}),(e2:Expertise {title: "Exp2"}),(e3:Expertise {title: "Exp3"}),(p1)-[r1:Expert]->(e1),(p1)-[r2:Expert]->(e2),(p2)-[r3:Expert]->(e2),(p3)-[r4:Expert]->(e3),(p2)-[r5:Expert]->(e3)

我希望能够找到与特定Expertise节点相关的所有Person节点,例如"Exp2"

I want to be able to find all Person nodes that are not related to a specific Expertise node, e.g. "Exp2"

我尝试过

MATCH (p:Person)--(e:Expertise)
WHERE NOT (e.title = "Exp2")
RETURN p

但是它返回所有Person节点(而我希望它仅返回p3).

But it returns all the Person nodes (while I expected it to return only p3).

从逻辑上讲,此结果是有意义的,因为这些节点中的每一个都与至少一个不是Exp2Expertise相关.
但是我想要的是找到所有与Exp2不相关的Person节点,即使它们也与其他节点也相关.

Logically, this result makes sense because each of these nodes is related to at least one Expertise that is not Exp2.
But what I want is to find all the Person nodes that are not related to Exp2, even if they are related to other nodes as well.

这怎么办?

修改

看来我不清楚要求.这是(非常)简化的方法,可以用更复杂的数据库来表示我的问题.
考虑Expertise具有更多属性的可能性,这些属性我想在同一查询中使用(不一定带有否定).例如:

It appears that I wasn't clear on the requirements. This is a (very) simplified way of presenting my problem with a much more complicated DB.
Consider the possibility that Expertise has more properties which I would like to use in the same query (not necessarily with negation). For example:

MATCH (p)--(e)
WHERE e.someProp > 5 AND e.anotherProp = "cookie" AND NOT e.title = "Exp2"

推荐答案

来自@ChristopheWillemsen的少量更改查询:

Little change query from @ChristopheWillemsen:

MATCH (e:Expertise) WHERE e.someProperty > 5 AND NOT e.title = someValue
WITH collect(e) as es
MATCH (p:Person) WHERE all(e in es WHERE NOT Exists( (p)--(e) ) )
RETURN p

更新:

// Collect the `Expertise` for which the following conditions:
MATCH (e:Expertise) WHERE e.num > 3 AND e.title = 'Exp2'
WITH collect(e) as es

// Select the users who do not connect with any of of expertise from `es` set:
OPTIONAL MATCH (p:Person) WHERE all(e in es WHERE NOT Exists( (p)--(e) ) )
RETURN es, collect(p)

另一个经过优化的查询:

Another query with some optimization:

// Get the set of `Expertise-node` for which the following conditions:
MATCH (e:Expertise) WHERE e.num > 3 AND e.title = 'Exp2'

// Collect all `Person-node` connected to node from the `Expertise-node` set:
OPTIONAL MATCH (e)--(p:Person)
WITH collect(e) as es, collect(distinct id(p)) as eps

//Get all `Person-node` not in `eps` set:
OPTIONAL MATCH (p:Person) WHERE NOT id(p) IN eps
RETURN es, collect(p)

这篇关于Cypher查询以按属性查找与其他节点不相关的节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-28 00:47