Postgres 9.6 - 更新存储在JSONB中的文本

时间:2017-01-20 10:59:18

标签: postgresql

我有一个数据库,其中包含许多引用大量非现场图像的JSON blob。

表格:

CREATE TABLE vendors (
    id uuid NOT NULL,
    name character varying(255) NOT NULL,
    images jsonb[],
    location jsonb,
    user_id uuid,
    created timestamp with time zone,
    updated timestamp with time zone
);

JSON:

{ 
    "url": "http://domain.com/eid/id/file.jpg", 
    "title": "foo", 
    "eid": "eid", 
    "id": "id"
}

这些图片现已从http://移至https://,我想更新为数据。我最终将完全删除域名,因此这些是相对路径,从而避免了这种大屠杀!

我在考虑做一些非常粗糙的事情,例如:

UPDATE vendors SET images = REPLACE(images, 'http://', 'https://');

但是我看到以下错误:

LINE 1: UPDATE vendors SET images = REPLACE(images, 'http://','https...
                                    ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.

我猜这个问题是Type Casts部分,但我无法弄明白。

1 个答案:

答案 0 :(得分:1)

WITH https AS (
   SELECT v.id, array_agg(x.i) newimages
      FROM vendors v JOIN
           LATERAL jsonb_array_elements(
                      replace(to_jsonb(v.images)::text,
                              'http://',
                              'https://'
                      )::jsonb
                   ) x(i)
              ON TRUE
      GROUP BY v.id
)
UPDATE vendors v
   SET images = https.newimages
   FROM https
   WHERE v.id = https.id;