简体   繁体   English

在 Postgres 中的特定索引处有效地将元素插入到 json 数组中

[英]Efficiently insert elements into json array at specific index in Postgres

We have an "order_json" column to store and represent the order of all the items referencing that row.我们有一个“order_json”列来存储和表示引用该行的所有项目的顺序。

Items can be added by clients in specific indexes in json arrays.客户可以在json arrays中的特定索引中添加项目。

However, I feel my solution for this is rather awkward and inefficient.但是,我觉得我的解决方案相当笨拙且效率低下。

SELECT JSON_AGG(element)
FROM 

(WITH first_part AS (
    SELECT id, jsonb_array_elements(order_json) AS element
    FROM my_boards
    WHERE id = 5
    LIMIT 2 -- means that client wants to add the element at index 2
)
, second_part AS (
    SELECT id, jsonb_array_elements(order_json) AS element
    FROM my_boards
    WHERE id = 5
    OFFSET 2
)
SELECT element
FROM first_part
UNION ALL

-- the new json element the client wants to add at index 2
SELECT element
FROM (values(5,'{"item_id": 999}'::JSONB)) n(id, element)

UNION ALL -- regular 'union' can mess up the order
SELECT element
FROM second_part) nj;

Is there a more efficient way to insert json objects at specific indexes?有没有更有效的方法在特定索引处插入 json 个对象?

jsonb_insert() can insert an element into an array at any position: jsonb_insert()可以在任意 position 处插入一个元素到数组中:

The following:下列:

with data (order_json) as (
  values ('[{"item_id": 1}, {"item_id": 2}, {"item_id": 3}, {"item_id": 4}]'::jsonb)
)
select jsonb_insert(order_json, '{1}', '{"item_id": 999}')
from data  

will return将返回

[{"item_id": 1}, {"item_id": 999}, {"item_id": 2}, {"item_id": 3}, {"item_id": 4}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM