본문 바로가기

DKE/Neo4j

[Neo4j] ORDER BY / 2023.02.14

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

 

ORDER BY - Cypher Manual

`ORDER BY` is a sub-clause following `RETURN` or `WITH`, and it specifies that the output should be sorted and how.

neo4j.com

 

*Example Graph

create (a {name:'A', age:34, length:170}),
(b {name:'B', age:36}),
(c {name:'C', age:32, length:185}),
(a)-[:KNOWS]->(b),
(b)-[:KNOWS]->(c)
 

ORDER BY는 출력을 정렬할 수 있음

 

1. Order nodes by property

노드의 속성으로 정렬할 수 있음

#노드가 이름순으로 정렬되어 반환
MATCH (n)
RETURN n.name, n.age
ORDER BY n.name

 

2. Order nodes by multiple properties

여러 속성별로 order할 수 있음

첫 번째 속성을 기준으로 결과 정렬 -> 동일한 값일 때 -> 다음 속성을 기준으로 결과 정렬

먼저 나이순으로 정렬한 다음 이름 순으로 정렬
MATCH (n)
RETURN n.name, n.age
ORDER BY n.age, n.name

3. Order nodes by ID

노드 내부 ID별로 정렬

MATCH (n)
RETURN n.name, n.age
ORDER BY elementId(n)

4. Order nodes by expression (keys()의 의미를 잘 모르겠음,,, 일단 생략)

5. Order nodes in descending order

정렬할 변수 뒤에 DESC를 추가하면 역순으로 정렬

#이름 역순으로 정렬
MATCH (n)
RETURN n.name, n.age
ORDER BY n.name DESC

6. Ordering null

오름차순 정렬일 때, null은 항상 마지막에 표시되고

내림차순으로 정렬할 때에는 먼저 표시됨

MATCH (n)
RETURN n.length, n.name, n.age
ORDER BY n.length

7. Ordering in a WITH clause

WITH와 ORDER BY를 함께 쓸 수 있음

#나이 순으로 정렬된 이름 list 반환
MATCH (n)
WITH n 
ORDER BY n.age
RETURN collect(n.name) AS names

 

'DKE > Neo4j' 카테고리의 다른 글

[Neo4j] LIMIT / 2023.02.16  (0) 2023.02.16
[Neo4j] SKIP / 2023.02.15  (0) 2023.02.15
[Neo4j] UNWIND / 2023.02.13  (0) 2023.02.13
[Neo4j] WITH / 2023.02.13  (0) 2023.02.13
[Neo4j] RETURN / 2023.02.08  (0) 2023.02.08