# 查询所有Person节点 SELECT*FROM cypher('my_graph', $$ MATCH (p:Person) RETURN p $$) as (v agtype);
# 条件查询节点 SELECT*FROM cypher('my_graph', $$ MATCH (p:Person) WHERE p.age >30 RETURN p $$) as (v agtype);
查询边
1 2 3 4 5 6 7 8 9 10 11 12
# 查询所有朋友关系 SELECT*FROM cypher('my_graph', $$ MATCH (a:Person)-[r:FRIENDS]->(b:Person) RETURN a.name, r.since, b.name $$) as (name1 agtype, since agtype, name2 agtype);
# 查询特定条件的关系 SELECT*FROM cypher('my_graph', $$ MATCH (a:Person)-[r:WORKS_AT]->(c:Company) WHERE c.name ='科技公司' RETURN a.name, c.name $$) as (person_name agtype, company_name agtype);
高级查询功能
路径查询
1 2 3 4 5 6
# 查找两个节点之间的路径 SELECT*FROM cypher('my_graph', $$ MATCH p = (a:Person {name: '张三'})-[*1..3]->(b:Person) RETURN p $$) as (path agtype); *表示任意边,范围在1~3之间的节点
聚合查询
1 2 3 4 5
# 统计每个公司的员工数 SELECT*FROM cypher('my_graph', $$ MATCH (p:Person)-[:WORKS_AT]->(c:Company) RETURN c.name, count(p) as employee_count $$) as (company agtype, count agtype);
基本更新操作
更新节点
1 2 3 4 5 6
# 更新节点属性 SELECT * FROM cypher('my_graph', $$ MATCH (p:Person {name: '张三'}) SET p.age = 31 RETURN p $$) as (v agtype);
删除边
1 2 3 4 5 6
# 删除关系 SELECT*FROM cypher('my_graph', $$ MATCH (a:Person)-[r:FRIENDS]->(b:Person) WHERE a.name ='张三'AND b.name ='李四' DELETE r $$) as (v agtype);
删除节点
1 2 3 4 5
# 删除节点(需要先删除相关的边) SELECT*FROM cypher('my_graph', $$ MATCH (p:Person {name: '张三'}) DETACH DELETE p $$) as (v agtype);
索引
Age支持对节点和边构建索引,用于加速查找过程。
节点索引
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
# 1. 基本的 B-tree 索引(适用于等值查询、范围查询) CREATE INDEX idx_person_name ON ag_catalog.ag_label_vertex USING btree ((properties ->'name')) WHERE label ='Person'AND graph_name ='my_graph';
# 2. GiST 索引(适用于地理数据或多维数据) CREATE INDEX idx_person_location ON ag_catalog.ag_label_vertex USING gist ((properties ->'location')) WHERE label ='Person'AND graph_name ='my_graph';
# 3. Hash 索引(仅适用于等值查询) CREATE INDEX idx_person_id ON ag_catalog.ag_label_vertex USING hash ((properties ->'id')) WHERE label ='Person'AND graph_name ='my_graph';
# 4. 多列索引 CREATE INDEX idx_person_name_age ON ag_catalog.ag_label_vertex USING btree ((properties ->'name'), (properties ->'age')) WHERE label ='Person'AND graph_name ='my_graph';
边索引
1 2 3 4 5 6 7 8 9
# 1. 基本的关系索引 CREATE INDEX idx_friendship_date ON ag_catalog.ag_label_edge USING btree ((properties ->'since')) WHERE label ='FRIENDS'AND graph_name ='my_graph';
# 2. 复合边索引 CREATE INDEX idx_relationship_composite ON ag_catalog.ag_label_edge USING btree ((properties ->'type'), (properties ->'weight')) WHERE label ='RELATIONSHIP'AND graph_name ='my_graph';
索引管理
1 2 3 4 5 6 7 8 9
# 查看所有索引 SELECT*FROM pg_indexes WHERE tablename LIKE'ag_label%';