Neo4jSampleQuery

DH Edu
이동: 둘러보기, 검색


Neo4j 실습을 위한 샘플 예제 및 쿼리 문서입니다.
본 문서는 DH Edu 교강사 김지선이 작성하였습니다.(21-2학기 최초 작성)


실습 예제

【샘플 데이터1(한강이남) 시트 페이지로 이동】 - 21-1 김지선 편찬
【샘플 데이터2(서울전체) 시트 페이지로 이동】 - 23-2 김지선 & 23-2 디인입2 수강생 공동 편찬 : 웹에서 교가를 찾지 못한 16곳의 학교[1]는 제외함.
【샘플 데이터3(서울전체-교화/교목추가) 시트 페이지로 이동】 - 23-2 김지선 & 23-2 디인입2 수강생 공동 편찬

펼치기

샘플1

펼치기

샘플2

펼치기

샘플3


샘플 쿼리

생성

● 단일 노드 생성〔생성된 노드 확인 하기 위해서는 return a〕
-ex) create (a:label명{gid:'gid명', class:'class명', name:'대표명칭', refurl:'외부정보링크'})

create (a:label명{property명:'property값'}) 


● 특정 라벨(label)의 노드 속성(properties) 및 값(value)을 생성

match (a:label명) set a. property명=“property값”


● 엣지 데이터 생성〔생성된 엣지 데이터 확인 하기 위해서는 return a, r, b〕

match (a{property명:'property값'}) match(b{property명:'property값'})
create (a) - [r:relation명] -> (b)  


● 관계 속성을 지닌 엣지 데이터 생성〔생성된 엣지 데이터 확인 하기 위해서는 return a, r, b〕

match (a{property명:'property값'}) match(b{property명:'property값'})
create (a) - [r:relation명{property명:'property값'}] -> (b)


출력: 기초

● 모든 데이터를 출력

match (n) return n 
= match (n) return * 


● 모든 데이터를 출력하되 50개 이하로 출력

match (n) return n limit 50


● 관계(relation)를 갖고 있는 모든 데이터를 출력

match (a)-[r]-(b) return a, r, b


● 관계(relation)가 없는 외톨이 노드 출력

match (a) where not (a)-[]-() return a


● 특정 라벨(label)에 속하는 데이터를 출력

match (a:label명) return a


● 여러 라벨(label)을 가지고 있는 데이터 출력

  • "|"(파이프문자)는 "or"과 같은 의미
  • label명은 2개 이상 사용 가능
match (a:label명①|label명②)-[r]-(b) return a, r, b


● 여러 관계(relation)를 가지고 있는 데이터 출력

  • relation명은 2개 이상 사용 가능
match (a:label명)-[r:relation명①|relation명②]-(b) return a, r, b


출력: 속성

● 특정 노드의 속성(properties) 값(value)을 기준으로 데이터를 출력

match (a) where a.property명='property값' return a
= match (a{property명:'property값'})  return a


● 특정 라벨(label)에 속하는 노드의 속성(properties) 값(value)을 기준으로 데이터를 출력

match (a:label명) where a.property명='property값' return a
= match (a:label명{property명:'property값'})  return a


○ Where 참고1: >, <, =, <>[2], starts with, ends with, contains
ⓐ노드의 속성(properties) 값(value)이 'ABC'인 노드를 출력

Where a.property명='ABC'

ⓑ노드의 속성(properties) 값(value)이 'ABC'가 아닌 노드를 출력

Where a.property명 <> 'ABC' 

ⓒ노드의 속성(properties) 값(value)이 A로 시작하는 노드를 출력

Where a.property명 starts with 'A'

ⓓ노드의 속성(properties) 값(value)이 C로 끝나는 노드를 출력

Where a.property명 ends with 'C'

ⓔ노드의 속성(properties) 값(value) 중 B가 들어가는 노드를 출력

Where a.property명 contains 'B'

ⓕ노드의 속성(properties) 값(value)으로 'ABC', 'DEF', 'GHI' 중 하나를 가지는 노드를 출력

Where a.property명 in ['ABC', 'DEF', 'GHI']


○ Where 참고2: not 과 함께 쓸 경우 해당 조건 결과값을 제외

match (a:label명l) where not a.property명='property값' return a

- 노드의 속성(properties) 값(value)이 A로 시작하는 노드를 출력하지 않음

Where not a.property명 starts with 'A'


○ Where 참고3: and 과 함께 쓸 경우 복수의 조건 결과값을 출력

where a.propertyA명='propertyA값' and a.propertyB명='propertyB값'
= match (a:label명{propertyA:'propertyA값', propertyB:'propertyB값'})
Where a.property명 contains 'A' and a.property명 contains 'B'


● 특정 라벨(label)을 기준으로 데이터의 속성을 출력

match (a:label명) return a.property명


출력: 관계

● 특정 관계(relation)를 갖고 있는 모든 데이터를 출력

match (a) -[r:relation명]- (b) return a, r, b
= match (a:label명)-[r]-(b) where type(r)="relation명" return a, r, b


● 특정 관계 속성(properties) 값(value)을 기준으로 데이터를 출력

match (a) -[r:relation명{property명:'property값'}]- (b) return a, r, b
= match (a) -[r:relation명]- (b) where r.property명='property값' return a, r, b


● 특정 관계 속성(properties) 값(value)이 들어가는 데이터를 출력

match (a) -[r]- (b) where r.property명 contains 'property값' return a, r, b


● 특정 관계(relation)를 가지지 않는 데이터 출력

match (a:label명)-[r]-(b) where not type(r)="relation명" return a, r, b


● 특정 관계(relation)를 하나 이상 가지고 있는 데이터 출력

match (a:label명) - [r:relation명] - (b:label명) with a, count(r) as s, collect(b) as c
where s > 1 return a, s, c


출력: 간편하게!

● match문에 입력한 변수를 *으로 받기(*: 'all'을 뜻함)

match 쿼리 return *


출력: n단계

● 특정 노드를 기준으로 1단계 관계를 맺고 있는 데이터를 모두 출력

match (a{property명'property값'}) - [r] - (b) return a, r, b


● 특정 노드와 특정 관계(1단계)에 있는 내용을 출력

match (a{property명'property값'}) -[relation명]- (b) return a, r, b


● 특정 노드와 특정 노드 사이에 1단계 관계를 맺고 있는 데이터를 모두 출력

match (a{property명'property값'}) -[relation명]- (b{property명'property값'}) return a, r, b


● 특정 노드를 기준으로 1~2단계 관계를 맺고 있는 데이터를 모두 출력

match (a{property명'property값'}) - [*..2] - (b) return a, b


● 특정 노드를 기준으로 1~3단계 관계를 맺고 있는 데이터를 모두 출력

match (a{property명'property값'}) - [*..3] - (b) return a, b


● 특정 노드를 기준으로 3단계 관계를 맺고 있는 데이터를 모두 출력

match (a{property명'property값'}) - [*3] - (b) return a, b


● 특정 노드를 기준으로 2~3단계 관계를 맺고 있는 데이터를 모두 출력

match (a{property명'property값'}) - [*2..3] - (b) return a, b


● 특정 노드를 기준으로 1~3단계의 특정 관계(relation)를 맺고 있는 데이터를 모두 출력

match (a{property명'property값'}) - [relation명*..3] - (b) return a, r, b


경로 구하기

● 특정 노드 사이의 경로 구하기(※p: 'path' 의 줄임말 / N에는 원하는 숫자 넣기)

match (a{property명:'property값'}), (b{property명:'property값'}), 
p = ((a)-[*..N]-(b))
return p


● 특정 노드 사이의 가장 빠른 경로 구하기(※N에는 원하는 숫자 넣기)

match (a{property명:'property값'}), (b{property명:'property값'}), 
p = shortestPath((a)-[*..N]-(b))
return p


오름/내림차순

● 노드 개수를 오름/내림차순으로 보이기
-예시1-1) 교가에 언급된 산의 이름과 언급 횟수를 오름차순으로 출력하라.

match (a:SchoolSong) -[r:mentions] -> (b:Mountain) 
return b.name as 산이름, count(b) as 언급횟수 order by 언급횟수


-예시1-2) 교가에 언급된 산의 이름과 언급 횟수를 내림차순으로 출력하라.

match (a:SchoolSong) -[r:mentions] -> (b:Mountain)
return b.name as 산이름, count(b) as 언급횟수 order by 언급횟수 desc 


○ as 참고: as 뒤에 오는 명칭에는 (쌍)따옴표를 붙이지 않으며, 띄어쓰기 시 _(언더바)를 붙인다.

예) match (a:SchoolSong) -[r:mentions] -> (b:Mountain) return b.name as 산_이름, count(b) as 언급_횟수 order by 언급_횟수 desc


복합 출력

● 여러 단계의 연결고리를 기반으로 한 특정 정보의 추론
-예시1) 서울시_강남구(Location) 소재 고등학교 교가(SchoolSong)에서 언급된(mentions) 산(Mountain)을 출력하라.

match (a:Location{name:'서울시_강남구'}) <-[r:isPartOf]- (b) <-[s:isLocatedIn]- (c) -[t:hasSchoolSong]-> (d) -[u:mentions]-> (e)  
return c.name as 학교명, e.name as 산이름 

= match (a:Location{name:'서울시_강남구'}) -[*..2]- (b:HighSchool) -[*..2] - (c:Mountain)
return b.name as 학교명, c.name as 산이름 


-예시2) 서울시_강남구(Location) 소재 고등학교 교가(SchoolSong)에서 언급된(mentions) 산(Mountain)의 이름과 언급 횟수를 내림차순으로 출력하라.

match (a:Location{name:'서울시_강남구'}) -[*..2]- (b:HighSchool) -[*..2] - (c:Mountain)
return c.name as 산이름, count(c) as 언급횟수 order by 언급횟수 desc 


-예시3) 서울시_강남구(Location) 소재 고등학교 교가(SchoolSong)에서 언급된(mentions) 산(Mountain)의 이름과 학교명(name), 학교 설립연도(syear)를 내림차순으로 출력하라.

match (a:Location{name:'서울시_강남구'}) -[*..2]- (b:HighSchool) -[*..2] - (c:Mountain)
return  b.name as 학교명, b.syear as 설립연도, c.name as 산이름 order by 설립연도 desc


-예시4) 교가(SchoolSong)에 관악산(Mountain)을 언급한(mentions) 고등학교(HighSchool)가 위치한 행정구(Location-category)를 출력하라.

match (a:Location{category:'행정구'}) -[*..2]- (b:HighSchool) - [*..2] - (c:Mountain{name:'관악산'})
return  a


-예시5) 교가(SchoolSong)에 한강이북(Mountain-category)에 위치한 산(Mountain)을 언급한(mentions) 고등학교(HighSchool)를 출력하라.

match (a:HighSchool)  - [r] - (b:SchoolSong) - [s] - (c:Mountain{category:'한강이북'}) return a


-예시6) 교화(SchoolFlower)가 '장미'인 고등학교(HighSchool) 중에서 서울시_송파구(Location) 소재 고등학교 교가(SchoolSong)에서 언급된(mentions) 산(Mountain)의 이름과 학교명 그리고 언급 횟수를 내림차순으로 출력하라.

match (a:Location{name:'서울시_송파구'}) <-[r:isPartOf]- (b) <-[s:isLocatedIn]- (c) -[t:hasSchoolSong]-> (d) -[u:mentions]-> (e)
match (f:SchoolFlower{name:'장미'})-[v:isSchoolFlowerOf]-(c:HighSchool)
return c.name as 학교명, e.name as 산이름, count(e) as 언급횟수 order by 언급횟수 desc 


-예시7) 교화(SchoolFlower)가 '개나리'인 '서울시_강서구_내발산동'(Location) 소재 고등학교(HighSchool) 중 교가(SchoolSong) '1절'(verse)에서 산(Mountain)을 언급하는(mentions) 학교(HighSchool)를 출력하라.

match  (a{name:'서울시_강서구_내발산동'}) -[r]- (b:HighSchool) -[s:hasSchoolSong]->  (c) -[t:mentions{verse:'1절'}]-> (d)
match (e:SchoolFlower{name:'개나리'})-[u:isSchoolFlowerOf]-(b)
return b


-예시8) 교가(SchoolSong)에 '불암산'(Mountain-name)이 언급된(mentions) 학교(HighSchool) 가운데 교화(SchoolFlower)와 교목(SchoolTree)이 모두 같은 학교를 출력하라.

match (a:SchoolTree)-[]-(b:HighSchool)-[]-(c:SchoolFlower)
match (b)-[]-(d:SchoolSong)-[]-(e:Mountain{name:'불암산'})

match (a)-[]-(f:HighSchool)-[]-(c)
match (f)-[]-(g:SchoolSong)-[]-(e)

where b <> f
return b, f


수정

  • 잘 수정되었는지 확인하고 싶다면 "return"을 사용한다.

● 특정 Node의 속성값(properties)을 수정

Match (a:label명{property명:property값}) set a.수정하고자하는property명 = '수정property값' Return a
  • 예: '영등포여자고등학교'의 coeducation 속성값을 '여'로 수정하기 위한 쿼리
    • match (a{name:'영등포여자고등학교'}) set a.coeducation = '여' Return a


● 특정 라벨(label)의 속성명(property명)을 수정

Match (n:label명) Where Exists(n.이전명칭) set n.수정명칭 = n.이전명칭 Remove n.이전명칭
  • 예: 'Mountain'의 속성명 cname을 chiname으로 수정하기 위한 쿼리
    • Match (n:Person) Where Exists(n.cname) set n.chiname = n.cname Remove n.cname


● 관계어1의 모든 속성을 유지하면서 관계어2로 변경

MATCH (a)-[r:관계어1]->(b)
WITH a, b, r, properties(r) as props
DELETE r
CREATE (a)-[new:관계어2]->(b)
SET new = props


삭제

  • 잘 삭제되었는지 확인하고 싶다면 "return"을 사용한다.

● 특정 라벨(label)의 노드 속성(properties)을 삭제

Match (a:label명) remove a. property명 Return a


● 모든 Node 삭제

Match (n) Delete n Return n


● 모든 Node와 Edge 삭제

Match (n) Detach Delete n Return n


● 특정 라벨(label)의 모든 Node 삭제

Match (a:label명) Delete a Return a


● 특정 Edge 삭제

Match (a) – [r:relation명] – (b) Delete r 



더 공부하기📚

● Neo4j 질의어 참고 자료
Cypher 메뉴얼: Neo4j 공식 웹사이트
Data Science 영역의 알고리즘 매뉴얼: Neo4j 공식 웹사이트

각주

  1. 이동 혜원여자고등학교, 신현고등학교, 동명생활경영고등학교, 은평메디텍고등학교, 선일빅데이터고등학교, 대성고등학교, 서울동구고등학교, 석관고등학교, 용산철도고등학교, 금호고등학교, 성수공업고등학교, 계성고등학교, 세그루패션디자인고등학교, 수락고등학교, 서울항공비즈니스고등학교, 동양고등학교
  2. 이동 neo4j에서는 ≠(부등호)와 같음