Google Cloud Spanner图查询:无需显式边表获取关联表数据
Google Cloud Spanner 属性图关联查询(无需显式边表)
问题背景
在Google Cloud Spanner数据库中存在两张表InterestCategory和Interest,以及一个属性图TestGraph,建表与建图语句如下:
CREATE TABLE InterestCategory ( interest_category_id STRING(36) NOT NULL, interest_category_name STRING(MAX) NOT NULL, ) PRIMARY KEY (interest_category_id); CREATE TABLE Interest ( interest_category_id STRING(36) NOT NULL, interest_id STRING(36) NOT NULL, interest_name STRING(MAX) NOT NULL, CONSTRAINT fk_interest_interest_category_id FOREIGN KEY (interest_category_id) REFERENCES InterestCategory (interest_category_id), ) PRIMARY KEY (interest_id); CREATE PROPERTY GRAPH TestGraph NODE TABLES ( InterestCategory, Interest, );
需求是通过一次图查询获取interest_id、interest_name、interest_category_id、interest_category_name字段,无需创建显式边表,仅允许在图定义中使用虚拟边表,实现一对一/一对多的关联查询,避免额外的工作量与复杂度。
尝试了以下无效查询:
GRAPH TestGraph MATCH (i:Interest) RETURN i.interest_id, i.interest_name, i.interest_category_id, i.interest_category_id.name
解决方案
1. 修改属性图定义,添加虚拟边
Spanner属性图不会自动识别外键创建节点间的关联,需要在图定义中基于外键关系创建虚拟边,无需实际创建边表。修改后的建图语句如下:
CREATE PROPERTY GRAPH TestGraph NODE TABLES ( InterestCategory AS Category, Interest AS Interest ) EDGE TABLES ( -- 基于外键创建虚拟边,关联Interest到InterestCategory Interest JOIN InterestCategory ON Interest.interest_category_id = InterestCategory.interest_category_id AS BELONGS_TO FROM Interest TO InterestCategory );
这里通过JOIN语句复用已有的外键关系,创建名为BELONGS_TO的虚拟边,逻辑上连接Interest节点到InterestCategory节点,不会生成实际的边表。
2. 编写正确的图查询
通过匹配虚拟边关联两个节点,即可获取所有需要的字段:
GRAPH TestGraph MATCH (i:Interest)-[:BELONGS_TO]->(c:Category) RETURN i.interest_id, i.interest_name, i.interest_category_id, c.interest_category_name
说明
虚拟边仅在属性图的逻辑定义中存在,无需维护额外的数据库表,完美适配一对一/一对多的关联场景,既满足查询需求又避免了不必要的复杂度。
内容的提问来源于stack exchange,提问作者Raj Chaudhary
相关产品推荐
相关产品推荐

