带有JAVA的JSONB PostgreSQL数据类型 - 插入和连接

时间:2015-07-17 17:37:58

标签: java json postgresql-9.4 postgresql-performance jsonb

第一次尝试JSONB数据类型(讨论从(Join tables using a value inside a JSONB column继续)来自@Erwin的建议,开始新线程)

两个表(模糊数据和表名):

1. Discussion table { discussion_id int, contact_id, group_id, discussion_updates jsonb } [has around 600 thousand rows]
2. Authorization table {user_id varchar , auth_contacts jsonb, auth_groups jsonb} [has around 100 thousand rows]

auth_contacts jsonb data has key value pairs data (as example) 
- {"CC1": "rr", "CC2": "ro" }
auth_groups jsonb data has key value pairs data (as example)
- {"GRP1": "rr", "GRP2": "ro" }

1-首先,通过Java JDBC在数据库中插入: 我在做的是:

JSONObject authContacts = new JSONObject();

for(each record in data){
authContacts.put(contactKey, contactRight);
authGroups.put(groupKey, groupRight);
}

String insertSql = "INSERT INTO SSTA_AuthAll(employee_id, auth_contacts, auth_groups) VALUES(?,?::jsonb,?::jsonb)";
//---Connect to Db and prepare query
preparedStatement.setObject(2, authContacts.toJSONString());
preparedStatement.setObject(3, authGroups.toJSONString());
//INSERT into DB

现在,toJSONString()需要时间(有时多达1秒 - TIME FORJSON STRING LOOP:17238ms),这又是低效的。 那么这也是正确的方法吗?谷歌上的大多数例子都直接有一个他们插入的字符串。

如果我直接将一个MAP插入到jsonb coolumn中,它会期望一个HSTORE扩展,如果我要使用jsonb,这是我不应该使用的?

2-现在下一部分: 我需要将讨论表中的contact_id与auth_contacts json数据类型的contact_id [如上例中所示的密钥]连接起来,并将auth_groups的group_id与讨论表的group_id连接起来

截至目前,尝试仅在contact_id上加入:

SELECT *
FROM discussion d 
JOIN 
(SELECT user_id, jsonb_object_keys(a.contacts) AS contacts FROM auth_contacts a WHERE user_id='XXX') AS c
ON (d.contact_id = c.contacts::text)
ORDER BY d.updated_date DESC

对于拥有大约6万个授权联系人的用户而言,此联接大约需要60毫秒,连续运行次数较少 - 混淆解释计划如下:

   "Sort  (cost=4194.02..4198.39 rows=1745 width=301) (actual time=50.791..51.042 rows=5590 loops=1)"
"  Sort Key: d.updated_date"
"  Sort Method: quicksort  Memory: 3061kB"
"  Buffers: shared hit=11601"
"  ->  Nested Loop  (cost=0.84..4100.06 rows=1745 width=301) (actual time=0.481..44.437 rows=5590 loops=1)"
"        Buffers: shared hit=11598"
"        ->  Index Scan using auth_contacts_pkey on auth_contacts a  (cost=0.42..8.93 rows=100 width=888) (actual time=0.437..1.074 rows=1987 loops=1)"
"              Index Cond: ((user_id)::text = '105037'::text)"
"              Buffers: shared hit=25"
"        ->  Index Scan using discussion_contact_id on discussion d  (cost=0.42..40.73 rows=17 width=310) (actual time=0.016..0.020 rows=3 loops=1987)"
"              Index Cond: ((contact_id)::text = (jsonb_object_keys(a.contacts)))"
"              Buffers: shared hit=11573"
"Planning time: 17.866 ms"
"Execution time: 52.192 ms"

我的最终目标是使用group_id在同一查询中另外加入。 jsonb_object_keys实际上做的是创建每个密钥的userid vs authcontacts映射。因此,对于拥有6万个联系人的用户,它将创建一个6万行的视图(可能在内存中)。现在,如果我在auth_groups上包含联接(对于具有6万个联系人的样本用户,将有大约1000万个组,这会使查询变慢。

这是在jsonb对象上进行连接的正确方法,还有更好的方法吗?

0 个答案:

没有答案
相关问题