cockroachdb jsonb选择查询

时间:2018-03-30 23:00:48

标签: jsonb cockroachdb

我在CockroachDB v2.0-beta中有一个简单的表:

CREATE TABLE account ( 
   id UUID NOT NULL DEFAULT uuid_v4()::UUID, 
   acct JSON NULL,
   CONSTRAINT "primary" PRIMARY KEY (id ASC),
   INVERTED INDEX account_acct_idx (acct),
   FAMILY "primary" (id, acct) 
) 

我可以运行一个select查询来查找acct->属性下的特定属性,如下所示:

select acct->>'id' from account where acct @> '{"properties": {"foo": "bar"}}';

有没有办法选择Json blob的子集,比如嵌套属性?这样的事情会有所帮助:

select acct->>'id', acct->>'properties:description' from account 
    where acct @> '{"properties": {"foo": "bar"}}';

提前感谢任何提示!

干杯, 〜克

1 个答案:

答案 0 :(得分:2)

就像乔丹在上面的评论中提到的那样,您已经可以使用在问题中引用的运算符来获取嵌套的JSON对象。使用您的示例,我可以按以下方式访问嵌套对象:

> CREATE TABLE account (
   id UUID NOT NULL DEFAULT uuid_v4()::UUID,
   acct JSON NULL,
   CONSTRAINT "primary" PRIMARY KEY (id ASC),
   INVERTED INDEX account_acct_idx (acct),
   FAMILY "primary" (id, acct)
);
CREATE TABLE

> INSERT INTO account (acct) VALUES ('{"properties": {"foo": "bar"}}');
INSERT 1

> SELECT * FROM account;
                   id                  |              acct
---------------------------------------+---------------------------------
  6fe08368-7720-4ddd-885e-75437b4e0267 | {"properties": {"foo": "bar"}}
(1 row)

> SELECT acct->>'properties' FROM account WHERE acct @> '{"properties": {"foo": "bar"}}';
     ?column?
------------------
  {"foo": "bar"}
(1 row)

请注意,->>返回嵌套的JSON对象的字符串表示形式。如我们的JSON docs中所述,运算符->可用于返回对象本身。如果您要访问更深层的嵌套对象,这也使您可以链接运算符。例如:

> select acct->'properties'->'foo' from account;
  ?column?
------------
  "bar"
(1 row)