什么是Cypher?
- 官方定义:_Cypher _is a declarative graph query language that allows for expressive and efficient querying and updating of the graph store. Cypher is a relatively simple but still very powerful language. Very complicated database queries can easily be expressed through Cypher.
- 类似sql,neo4j自带查询脚本,功能强大,语法简单;
Cypher提供的能力:
Cypher matches patterns of nodes and relationship in the graph, to extract information or modify the data.
Cypher has the concept of identifiers which denote named, bound elements and parameters.
Cypher can create, update, and remove nodes, relationships, labels, and properties.
Cypher manages indexes and constraints.
基本语法
Cypher官方语法:https://neo4j.com/docs/cypher-refcard/current/
Cypher中文文档:http://neo4j.com.cn/public/cypher/neo4j_cql_create_node.html
demo
create (gao:Person{name:"gao.xx"})-[:MENTOR{since:"2014"}]->(sh:Person{name:"shuang.xx"})
create (gao)-[:MENTOR]->(wen:Person{name:"wen.xx"})
create (wen)-[:FRIEND]->(niu:Person{name:"超级牛"})
create (gao)-[:FRIEND]->(niu)
create (gao)-[:MENTOR]->(wei:Person{name:"wei.xx"})
create (wei)-[:MENTOR]->(:Person{name:"zhangsan"})
create (wei)-[:MENTOR]->(:Person{name:"lishi"})
create (wei)-[:FRIEND]->(:Person{name:"大牛1"})
create (wei)-[:FRIEND]->(niu2:Person{name:"大牛2"})
create (sh)-[:FRIEND]->(niu2)
1.找到gao.xx直接领导的所有人?
match (p:Person{name:"gao.xx"})-[:MENTOR]->(r) return r;
2.找到gao.xx接领导的所有人?
match (p:Person{name:"gao.xx"})-[:MENTOR*]->(r) return r;
3.找到gao.xx间接领导的所有人?
match (p:Person{name:"gao.xx"})-[:MENTOR*2..]->(r) return r;
4.gao.xx想招聘开发,于是想找到他领导的所有人的朋友?
match (p:Person{name:"gao.xx"})-[:MENTOR*]->()-[:FRIEND]->(r) return r;
5.找到wei.xx和shuang.xx的共同好友?
match (:Person{name:"wei.xx"})--(p)--(:Person{name:"shuang.xx"}) return p
6.和wen.xx有直接关系的人,不考虑方向?
match (:Person{name:"wen.xx"})-[*..1]-(p) return p;
或
match (:Person{name:"wen.xx"})-[:FRIEND|:MENTOR]-(p) return p;
7.最短路径:shuang.xx到大牛2的最短路径
match p = shortestPath((n1:Person{name:"shuang.xx"})-[*..6]-(n2:Person{name:"大牛2"})) return p;