본문 바로가기

DKE/Neo4j

[Neo4j] WITH / 2023.02.13

https://neo4j.com/docs/cypher-manual/current/clauses/with/

 

WITH - Cypher Manual

The `WITH` clause allows query parts to be chained together, piping the results from one to be used as starting points or criteria in the next.

neo4j.com

 

*Example Graph

create (anders {name:'Anders'}),
(caesar {name: 'Caesar'}),
(bossman {name: 'Bossman'}),
(george {name:'George'}),
(david {name: 'David'}),
(anders)-[:BLOCKS]->(caesar),
(anders)-[:KNOWS]->(bossman),
(caesar)-[:KNOWS]->(george),
(bossman)-[:KNOWS]->(george),
(bossman)-[:BLOCKS]->(david),
(david)-[:KNOWS]->(anders)

WITH를 사용하면 출력이 다음 쿼리 부분으로 전달되기 전에 출력을 조작할 수 있음

 

1. Introducing variables for expressions

쿼리를 평가한 결과에 새로운 변수를 도입할 수 있음

#George에 연결된 이름이 C로 시작하는 사람의 이름 반환
MATCH (george {name: 'George'})<--(otherPerson)
WITH otherPerson, toUpper(otherPerson.name) AS upperCaseName
WHERE upperCaseName STARTS WITH 'C'
RETURN otherPerson.name

2. Using the wildcard to carry over variables

와일드카드 *를 사용하여 새 변수를 추가할 뿐만 아니라 범위 내의 모든 변수를 전달할 수 있음

#모든 사람의 이름과 사람 간의 관계 type을 반환
MATCH (person)-[r]->(otherPerson)
WITH *, type(r) AS connectionType
RETURN person.name, otherPerson.name, connectionType

3. Filter on aggregate function results

집계된 결과가 WITH 절을 통과해야 필터링 가능

#David와 연결된 사람 (Anders, Bossman) 중 둘 이상의 발신 관계를 가진 Anders 반환
#Bossman은 David 관련 관계 제외하고 발신 관계 하나를 가짐
MATCH (david {name: 'David'})--(otherPerson)-->()
WITH otherPerson, count(*) AS foaf
WHERE foaf > 1
RETURN otherPerson.name

4. Sort results before using collect on them

#3개로 제한된 사용자 이름의 역순 목록이 list로 반환됩니다.
MATCH (n)
WITH n
ORDER BY n.name DESC
LIMIT 3
RETURN collect(n.name)

5. Limit branching of a path search

#Anders과 관계된 모든 노드를 찾고 이름을 내림차순으로 정렬 한 후 맨 위 결과 하나만 얻음 (David)
#David와 관련된 모든 노드 이름 반환
MATCH (n {name: 'Anders'})--(m)
WITH m
ORDER BY m.name DESC
LIMIT 1
MATCH (m)--(o)
RETURN o.name

6. Limit and Filtering

LIMIT -> WHERE 과 WHERE -> LIMIT 순서의 결과 차이

6-1) LIMIT -> WHERE

# LIMIT -> 1, 2, 3, 4, 5
# WHERE -> 3, 4, 5
UNWIND [1, 2, 3, 4, 5, 6] AS x
WITH x
LIMIT 5
WHERE x > 2
RETURN x

6-2) WHERE -> LIMIT

# WHERE -> 3, 4, 5, 6
# LIMIT -> 3, 4, 5, 6
UNWIND [1, 2, 3, 4, 5, 6] AS x
WITH x
WHERE x > 2
WITH x
LIMIT 5
RETURN x