bboyjing's blog

Neo4j学习笔记六【Cypher操作图形数据】

Cypher更新图形数据

创建新的USERS节点

1
2
create (n:USERS{name : 'Grace Spencer', yearOfBirth : 1982, email : 'grace@gmail.com'})
return n;

创建关系

1
2
3
4
match (john:USERS),(grace:USERS)
where john.name = 'John Johnson' and grace.name = 'Grace Spencer'
create (john)-[r:IS_FRIEND_OF]->(grace)
return r;

同时创建新节点和关系

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
match (john:USERS)
where john.name = 'John Johnson'
create (john)-[r:IS_FRIEND_OF]->(lee:USERS{name : 'Lee', yearOfBirth : 1990, email : 'lee@gmail.com'})
return r,lee
```
#### 删除数据
```cypher
//尝试执行上述代码会出错,Neo4j要求先删除关系
start lee= node(10)
delete lee;
//明确删除一个节点和所有关联关系
start lee = node(10)
match (lee)-[r]-()
delete lee,r
//或者执行新的api
MATCH (lee:USERS { name:'Lee' })
DETACH DELETE lee

更新节点属性

1
2
3
4
match (john)
where john.name = 'John Johnson'
//若yearOfBirth属性不存在会创建该属性
set john.yearOfBirth = 1973;

删除节点属性

1
2
3
match (john)
where john.name = 'John Johnson'
remove john.yearOfBirth;

高级Cypher

聚合

1
2
3
match(user:USERS)-[:IS_FRIEND_OF]-()
return user,count(*)
order by count(*) desc;

函数

查看每一类型有多少个关系开始于或结束于用户John

1
2
3
match (john:USERS{name:'John Johnson'})
match (john)-[rel]-()
return type(rel),count(*);

with语句的管道功能,只查出多于一次的关系

1
2
3
4
5
match (john:USERS{name:'John Johnson'})
match (john)-[rel]-()
with type(rel) as type, count(*) as count
where count > 1
return type, count;