postgresql 如何在Apache AGE中声明主键

qvsjd97n  于 2023-04-11  发布在  PostgreSQL
关注(0)|答案(1)|浏览(115)

这里,我创建了一个SoftwareEngineer节点。我想确保一个SocialSecurityNumber只能存在一个SoftwareEngineer如何使用Apache AGE实现此功能?

test=# SELECT * FROM cypher('staff_details', $$
CREATE(e: SoftwareEngineer {
name: 'Muneeb',
SocialSecurityNumber: '12345',
date: pg_catalog.now()
}) RETURN e
$$) as (e agtype);

当我运行上面的查询两次时,我创建了两个包含完全相同数据的节点。

test=# Select * from cypher('staff_details', $$ MATCH (v:SoftwareEngineer) RETURN v $$) as (v agtype);

提供:

{"id": 1407374883553281, "label": "SoftwareEngineer", "properties": {"date": "2023-04-01T07:23:10.069163+05:00", "name"
: "Muneeb", "SocialSecurityNumber": "12345"}}::vertex
 {"id": 1407374883553282, "label": "SoftwareEngineer", "properties": {"date": "2023-04-01T07:28:39.245981+05:00", "name"
: "Muneeb", "SocialSecurityNumber": "12345"}}::vertex
(2 rows)

虽然id属性不同,但数据是相同的。我希望Apache AGE限制创建两个具有相同SocialSecurityNumber的节点,就像Primary Key一样。

tyu7yeag

tyu7yeag1#

在Github上有一个关于类似issue的讨论。请查看。从我所尝试的,适用于您的情况的是:
1.创建函数“get_ssn”,该函数将从“properties”列返回属性SocialSecurityNumber

CREATE OR REPLACE FUNCTION get_ssn(properties agtype) 
RETURNS agtype
AS
$BODY$
select agtype_access_operator($1, '"SocialSecurityNumber"');
$BODY$
LANGUAGE sql
IMMUTABLE;

1.在属性“SocialSecurityNumber”上创建唯一索引
CREATE UNIQUE INDEX person_ssn_idx ON staff_details."SoftwareEngineer"(get_ssn(properties)) ;
在运行上述CREATE INDEX查询之前,可能需要首先创建折点标注(如果尚未创建)
SELECT * FROM create_vlabel('staff_details', 'SoftwareEngineer');
现在,当您尝试添加具有相同SocialSecurityNumber的另一个节点时,您会收到错误:
ERROR: duplicate key value violates unique constraint "person_ssn_idx" DETAIL: Key (get_ssn(properties))=("12345") already exists.

相关问题