图数据库Neo4j的基本使用及与SpringBoot集成 (3)

和sql语句一样,可以给返回结果增加列

MATCH (p:Person) RETURN p, p.name AS name, toUpper(p.name), coalesce(p.nickname,"n/a") AS nickname, { name: p.name, label:head(labels(p))} AS person

JSON结果:

[ { "p": { "identity": 65, "labels": [ "Person" ], "properties": { "name": "Keanu Reeves", "born": 1964 } }, "name": "Keanu Reeves", "toUpper(p.name)": "KEANU REEVES", "nickname": "n/a", "person": { "name": "Keanu Reeves", "label": "Person" } }, { "p": { "identity": 66, "labels": [ "Person" ], "properties": { "name": "Robert Zemeckis", "born": 1951 } }, "name": "Robert Zemeckis", "toUpper(p.name)": "ROBERT ZEMECKIS", "nickname": "n/a", "person": { "name": "Robert Zemeckis", "label": "Person" } }, { "p": { "identity": 67, "labels": [ "Person" ], "properties": { "name": "Tom Hanks", "born": 1956 } }, "name": "Tom Hanks", "toUpper(p.name)": "TOM HANKS", "nickname": "n/a", "person": { "name": "Tom Hanks", "label": "Person" } } ] 排序分页

演员按照出演电影的数量排序取前10个

MATCH (a:Person)-[:ACTED_IN]->(m:Movie) RETURN a, count(*) AS appearances ORDER BY appearances DESC SKIP 0 LIMIT 10;

结果:

╒════════════════════════════════╤═════════════╕ │"a" │"appearances"│ ╞════════════════════════════════╪═════════════╡ │{"name":"Tom Hanks","born":1956}│2 │ ├────────────────────────────────┼─────────────┤ │{"name":"Jerry","born":1986} │1 │ └────────────────────────────────┴─────────────┘ 聚合统计查询

查看演员的总数量

MATCH (:Person) RETURN count(*) AS people

结果:

╒════════╕ │"people"│ ╞════════╡ │4 │ └────────┘

统计出演电影的演员

MATCH (m:Movie)<-[:ACTED_IN]-(a:Person) RETURN m.title AS movie, collect(a.name) AS cast, count(*) AS actors

结果:

╒══════════════╤═════════════╤════════╕ │"movie" │"cast" │"actors"│ ╞══════════════╪═════════════╪════════╡ │"The Matrix" │["Jerry"] │1 │ ├──────────────┼─────────────┼────────┤ │"Cloud Atlas" │["Tom Hanks"]│1 │ ├──────────────┼─────────────┼────────┤ │"Forrest Gump"│["Tom Hanks"]│1 │ └──────────────┴─────────────┴────────┘ UNION / WITH

union 用来组合查询的结果,查询电影的演职人员表

MATCH (actor:Person)-[r:ACTED_IN]->(movie:Movie) RETURN actor.name AS name, type(r) AS type, movie.title AS title UNION MATCH (director:Person)-[r:DIRECTED]->(movie:Movie) RETURN director.name AS name, type(r) AS type, movie.title AS title

结果:

╒═════════════════╤══════════╤══════════════╕ │"name" │"type" │"title" │ ╞═════════════════╪══════════╪══════════════╡ │"Jerry" │"ACTED_IN"│"The Matrix" │ ├─────────────────┼──────────┼──────────────┤ │"Tom Hanks" │"ACTED_IN"│"Cloud Atlas" │ ├─────────────────┼──────────┼──────────────┤ │"Tom Hanks" │"ACTED_IN"│"Forrest Gump"│ ├─────────────────┼──────────┼──────────────┤ │"Robert Zemeckis"│"DIRECTED"│"Forrest Gump"│ └─────────────────┴──────────┴──────────────┘

或者和下面的查询是等价的

MATCH (actor:Person)-[r:ACTED_IN|DIRECTED]->(movie:Movie) RETURN actor.name AS name, type(r) AS type, movie.title AS title

WITH 关键字可以看成是查询的语句的一个子条件,主要是用来过滤数据用的,比如

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zzjzsp.html