postgresql jsonb 在二级上包含 key:value

postgresql jsonb contains key:value on second level

在 postgresql 中是否有可能在第二层查询 key:value

例如一行的 jsonb 字段如下所示:

{
   "something": {
      "v_id": "5544d28431f19", 
      "value": "xyz"
   }, 
   "something_else": {
      "v_id": "5544d28431feb", 
      "value": "abc"
   }
}

我想使用 v_id 值查询此行,例如:

  SELECT id, jsonb_field
  FROM table_1
  WHERE jsonb_field @> '{{"v_id": "5544d28431feb"}}'
  ;

但是,此查询无效。如何实现这样的查询?

编辑:

根据@CraigRinger 的评论:

这里的重点是不知道top level key,我想说"for any object, is there an inner object that has the following key with the following value".

您可以使用 lateral join 为 table 中的每一行调用 jsonb_each。函数 jsonb_each 将每个节点变成一行,其中包含两列,分别称为 keyvalue:

select  value
from    table_1
cross join lateral
        jsonb_each(jsonb_field) sub
where   value @> '{"v_id": "5544d28431feb"}';

完整示例(尚未 SQL Fiddle 支持 Postgres 9.4):

create table table_1 (id int primary key, jsonb_field jsonb);
insert into table_1 (id, jsonb_field) values (42, '{
   "something": {
      "v_id": "5544d28431f19", 
      "value": "xyz"          
   },                                       
   "something_else": {
      "v_id": "5544d28431feb", 
      "value": "abc"
   }
}');

select  value
from    table_1
cross join lateral
        jsonb_each(jsonb_field) t2
where   value @> '{"v_id": "5544d28431feb"}';

这会打印:

                   value                   
-------------------------------------------
 {"v_id": "5544d28431feb", "value": "abc"}