Postgres比较多个jsonb字段
Postgres compare multiple jsonb fields
我在 table 中有一个 jsonb "contacts" 字段,它是:
- 一个对象,其中每个键都是联系人类型,例如邮寄、账单、紧急情况等。这些都是松散定义的。
- #1 中每个键的值是一个数组,每个类型包含 1 个或多个联系人
- #2 中的每个值都是一个包含松散定义字段的对象。
示例:
{
"main": [{
"name": "Bobby Smith",
"email": "bs@example.com",
"telephone": "555-999-0000"
}, {
"name": "Joan Smith",
"email": "js@example.com",
"telephone": "555-999-0002"
}],
"billing": [{
"name": null,
"region": "Arizona",
"address": ["PO BOX 123", "456 Nowhere Road"],
"country": "USA",
"locality": "BigMac",
"postalCode": "90210"
}],
"emergency": [{
"name": "John Cooper",
"email": "jc@example.com",
"telephone": "555-987-0000"
}]
}
我想要一种简单的方法来比较最外层对象中的键不可知的名称字段,以及每个数组中的元素数量。
实际上是这样的:
SELECT * FROM clients WHERE contacts#>>'{*, *, name}' = 'John Cooper';
return 包含上述内容的行是否匹配“{emergency, 0, name}”
您需要为当前的数据库设计展开数据,例如:
select t.*
from t, jsonb_each(contacts) e, jsonb_array_elements(e.value) c
where c ->> 'name' = 'John Cooper'
但这不能为您的查询使用任何索引。
更好的设计是仅在连接 table 的每一行上存储联系人数据,例如:
t t_contact
------------------ -------------------------
t_id primary key t_id references t(t_id)
contact_type text
contact jsonb
然后,您可以索引 t_contact(contact)
并查询,例如:
select t.*
from t
join t_contact using (t_id)
where contact ->> 'name' = 'John Cooper'
group by t.t_id
我在 table 中有一个 jsonb "contacts" 字段,它是:
- 一个对象,其中每个键都是联系人类型,例如邮寄、账单、紧急情况等。这些都是松散定义的。
- #1 中每个键的值是一个数组,每个类型包含 1 个或多个联系人
- #2 中的每个值都是一个包含松散定义字段的对象。
示例:
{
"main": [{
"name": "Bobby Smith",
"email": "bs@example.com",
"telephone": "555-999-0000"
}, {
"name": "Joan Smith",
"email": "js@example.com",
"telephone": "555-999-0002"
}],
"billing": [{
"name": null,
"region": "Arizona",
"address": ["PO BOX 123", "456 Nowhere Road"],
"country": "USA",
"locality": "BigMac",
"postalCode": "90210"
}],
"emergency": [{
"name": "John Cooper",
"email": "jc@example.com",
"telephone": "555-987-0000"
}]
}
我想要一种简单的方法来比较最外层对象中的键不可知的名称字段,以及每个数组中的元素数量。
实际上是这样的: SELECT * FROM clients WHERE contacts#>>'{*, *, name}' = 'John Cooper';
return 包含上述内容的行是否匹配“{emergency, 0, name}”
您需要为当前的数据库设计展开数据,例如:
select t.*
from t, jsonb_each(contacts) e, jsonb_array_elements(e.value) c
where c ->> 'name' = 'John Cooper'
但这不能为您的查询使用任何索引。
更好的设计是仅在连接 table 的每一行上存储联系人数据,例如:
t t_contact
------------------ -------------------------
t_id primary key t_id references t(t_id)
contact_type text
contact jsonb
然后,您可以索引 t_contact(contact)
并查询,例如:
select t.*
from t
join t_contact using (t_id)
where contact ->> 'name' = 'John Cooper'
group by t.t_id