引言:为什么使用图数据库
在很多新型项目中,应用图数据库已经是势在必行的趋势了,因为图数据库可以很好的表示各种节点与关系的概念,并且可以很友好的可视化出来,大大方便了我们的数据管理和展示工作。
下面均以演员,导演和电影的图关系做介绍:
一 概念
节点:
(a) //actors
(m) //movies
( ) //some anonymous nod
关系:
-[r]-> //a relationship referred to as "r"
(a)-[r]->(m) //actors having a relationship referred to as "r" to movies
-[:ACTED_IN]-> //the relationship type is ACTED_IN
(a)-[:ACTED_IN]->(m) //actors that ACTED_IN some movie
(d)-[:DIRECTED]->(m) //directors that DIRECTED some movie
属性:
(m {title:"The Matrix"}) //Movie with a title property
(a {name:"Keanu Reeves",born:1964}) //Actor with name and born property
(a)-[:ACTED_IN {roles:["Neo"]}]->(m)
//Relationship ACTED_IN with roles property (an array of character names)
标签:
(a:Person) //a Person
(a:Person {name:"Keanu Reeves"}) //a Person with properties
(a:Person)-[:ACTED_IN]->(m:Movie) //a Person that ACTED_IN some movie
二 CQL查询语句-MATCH
运行环境为在线浏览器-数据库是官方演员-电影图数据库
1查询所有节点
MATCH (n)
RETURN n;
查询两个节点,一条边:
MATCH (n)-->(m)
RETURN n, m;
也可缺失一个节点
MATCH (n)-->( )
RETURN n;
返回节点的属性值:返回演员和导演的名字
MATCH (person)-->()
RETURN person.name;
2查询关系-边
查询所有的边关系:
MATCH (person)-[rel]->(movie)
RETURN person, type(rel)
查询哪个演员演了哪个电影:
MATCH (actor)-[role:ACTED_IN]->(movie)
RETURN actor.name, role.roles, movie.title;
3 查询标签:
用标签查询 哪个演员表演过哪个电影:
MATCH (actor:Person)-[:ACTED_IN]->(movie)
RETURN actor.name, movie.title;
增加WHERE 条件筛选,名字叫Tom Hanks的演员:
MATCH (tom:Person)
WHERE tom.name = "Tom Hanks"
RETURN tom;
还可以这样:
MATCH (tom:Person {name:"Tom Hanks"})
RETURN tom;
4 path:传递关系
查询哪个演员参演的电影,及这部电影的导演关系图:
MATCH (actor)-[:ACTED_IN]->(movie)<-[:DIRECTED]-(director)
RETURN actor.name, movie.title, director.name;
上面语句的另一种写法:
MATCH (actor)-[:ACTED_IN]->(movie),
(movie)<-[:DIRECTED]-(director)
RETURN actor.name, movie.title, director.name;
再来一种等价写法:
MATCH (actor)-[:ACTED_IN]->(movie),
(director)-[:DIRECTED]->(movie)
RETURN actor.name, movie.title, director.name;
定义path
用p返回多有的path及其属性:
MATCH p=(a)-[:ACTED_IN]->(m)<-[:DIRECTED]-(d)
RETURN p;
用节点node返回path:
MATCH p=(a)-[:ACTED_IN]->(m)<-[:DIRECTED]-(d)
RETURN nodes(p);
用关系rels返回path:
MATCH p=(a)-[:ACTED_IN]->(m)<-[:DIRECTED]-(d)
RETURN rels(p);
两个模式的path定义:
MATCH p1=(a)-[:ACTED_IN]->(m), p2=(d)-[:DIRECTED]->(m)
RETURN p1, p2;
通过以上的介绍,是不是你也发现了图数据库的潜力无穷的,只要用到需要的项目,Neo4j很好用。希望可以关注后续的介绍。