赞
踩
在图数据库中,图空间是存储图数据的容器。以下是创建和克隆图空间的示例:
# 创建图空间
CREATE SPACE test_Nebula(partition_num=15, replica_factor=1, vid_type=fixed_string(30));
# 克隆图空间
CREATE SPACE IF NOT EXISTS monitor_rules_orderby AS monitor_rules;
在进行数据操作前,需要选择一个图空间:
USE test_Nebula;
在图数据库中,Tag代表顶点的属性集合,Edge Type代表边的类型和属性:
CREATE TAG player(name string, age int);
CREATE TAG team(name string);
CREATE EDGE follow(degree int);
CREATE EDGE serve(start_year int, end_year int);
可以对已存在的边添加新的属性:
ALTER EDGE follow ADD (seq int);
插入顶点和边的数据:
INSERT VERTEX player(name, age) VALUES "player100":("Tim Duncan", 42);
INSERT VERTEX player(name, age) VALUES "player101":("Tony Parker", 36);
INSERT VERTEX player(name, age) VALUES "player102":("LaMarcus Aldridge", 33);
INSERT VERTEX team(name) VALUES "team203":("Trail Blazers"), "team204":("Spurs");
INSERT EDGE follow(degree) VALUES "player101" -> "player100":(95);
INSERT EDGE follow(degree) VALUES "player101" -> "player102":(90);
INSERT EDGE follow(degree) VALUES "player102" -> "player100":(75);
INSERT EDGE serve(start_year, end_year) VALUES "player101" -> "team204":(1999,2018), "player102" -> "team203":(2006,2015);
使用go
语句可以进行图遍历:
# 从VID为player101的球员开始,沿着follow找到链接的球员
GO FROM "player101" OVER follow YIELD id($$);
# 从VID为player101的球员开始,沿着边follow查找年龄大于或者等于35岁的球员,并返回他们的姓名和年龄
GO FROM "player101" OVER follow WHERE properties($$).age >= 35 YIELD properties($$).name AS Teammate, properties($$).age AS Age;
使用fetch
语句可以获取顶点的属性:
FETCH PROP ON player "player100" YIELD properties(vertex);
MATCH
语句用于执行复杂的图查询:
# 查询所有边
MATCH ()-[e]->() RETURN e;
以下是一些基于图数据库的查询示例:
MATCH (t:team)<-[:serve]-(p:player)
RETURN t.name AS team_name, collect(p.name) AS players;
MATCH (p:player)-[:serve]->(t:team)
RETURN p.name AS player_name, collect(t.name) AS teams;
MATCH (p:player {name: '特定球员姓名'})-[:serve*]->(t:team)
RETURN t.name AS team_name;
MATCH (p1:player)-[:follow*2]->(p2:player)
WHERE p1.name = '特定球员姓名'
RETURN p2.name AS followed_player;
MATCH (p:player)
RETURN p.age AS age, count(*) AS player_count
ORDER BY age;
MATCH (p:player)-[:serve]->(t:team)
WHERE (p.end_year - p.start_year) > 10
RETURN p.name AS player_name, t.name AS team_name;
除了查询,我们还可以更新和删除图数据库中的数据:
UPDATE VERTEX "player100" SET player.name = "Tim";
UPDATE EDGE ON follow "player101" -> "player100" SET degree = 96;
DELETE VERTEX "player111", "team203";
DELETE EDGE follow "player101" -> "team204";
通过上述操作,我们可以看到图数据库在处理关系数据方面的强大能力。无论是社交网络分析、推荐系统还是其他需要复杂关系查询的场景,图数据库都能提供高效的解决方案。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。