1

我正在做一个在 PostgreSQL 中使用 JSONB 进行索引的示例,并希望将随机 uuid 添加到如下所示的一段 JSON 中。但是,我无法获得最接近的语法是"{"lookup_id": " || uuid || "}".

But I require
{"lookup_id": "92b3b21a-a87c-1798-5d91-3dbf3043c209"}

我的代码是:

INSERT INTO test (id, json)
SELECT x.id, '{
    "lookup_id": " || uuid || "
   }'::jsonb 
FROM generate_series(1,100) AS x(id),
     uuid_in(md5(now()::text)::cstring) AS uuid;
4

1 回答 1

1

你可以使用row_to_json功能:

select x.id, row_to_json(r.*)::jsonb
from generate_series(1,100) AS x(id)
    cross join (select uuid_in(md5(now()::text)::cstring) as lookup_id) as r;

更新

首先,您可以使用uuid这样您就可以创建唯一的 uid:

CREATE EXTENSION "uuid-ossp";

with cte as (
    select
        *, uuid_generate_v4() as uuid
    from generate_series(1,5) AS x(id)
)
select distinct uuid from cte

------------------------------------------------
"e980c784-8aae-493f-90fb-1091280fe4f7"
"45a80660-3be8-4538-a039-13d97d6306af"
"5380f285-5d6b-467a-a83a-7fdc5c0ebc4c"
"7a435b36-95d3-49fc-808f-359838a866ed"
"3164a544-a2c9-4cd0-b0c4-199a99986cea"

接下来,将其合并到您现有的json. 目前最愚蠢和最简单的方法可能是这样的:

with cte as (
    select
        '{"a":1}'::json as j, uuid_generate_v4() as uuid
    from generate_series(1,5) AS x(id)
)
select 
    left(j::text, length(j::text) - 1) || ', "uuid":' || to_json(uuid) || '}'
from cte

但是你也可以写一些函数来合并jsons,或者你可以使用hstore扩展来合并jsons:

with cte as (
    select
        id, '{"a":1, "b":2}'::json as data, uuid_generate_v4() as uuid
    from generate_series(1,5) AS x(id)
), cte2 as (
    select 
        id,
        (
            select hstore(array_agg(r.key), array_agg(r.value))
            from (
                select *
                from json_each_text(c.data) as j
                union all
                select 'uuid', c.uuid::text
            ) as r
        ) as data
    from cte as c
)
select
    id, hstore_to_json(data)
from cte2

而且我确信 PostgreSQL 方面的大专家可以建议更优雅的方式将 json 合并在一起

于 2015-03-05T11:29:50.467 回答