【问题标题】:How to do a lookup for array elements in jsonb field?如何在 jsonb 字段中查找数组元素?
【发布时间】:2020-07-22 15:12:42
【问题描述】:

假设我有一张桌子:

SELECT * FROM settings;
| id | name    | strategies |
| -- | ---     | ---        |
| 1  | default | [{name: xyz, enabled: true}, {name: bot, enabled: true}]  |
| 2  | new1    | [{name: bot, enabled: true}, {name: xyz, enabled: false}] |

strategies这里是一个jsonb类型的字段(一个对象数组)。

我想更改策略列(数组)中一个元素(对象)中一个属性的值 - 即将“bot”重命名为“bot2”。

我想我可以这样做:

-- renames strategy bot to bot2 using fixed index
UPDATE settings
SET strategies = jsonb_set(strategies, '{1}', '{
  "name": "bot2",
  "enabled": true,
}', FALSE)
WHERE name = 'default';

但我不喜欢使用幻数作为数组索引 ({1})。

如果我不知道要编辑的数组元素的索引(或者所有记录的索引不同)怎么办?如何根据属性查找 jsonb 字段中的数组元素,即查找name='bot'?我正在使用 PostgreSQL v10.5。

【问题讨论】:

标签: postgresql sql-update jsonb postgresql-10


【解决方案1】:

因为你想先获取元素的路径然后更新它

你可以试试这个:

with cte as (
  select  ('{'||index-1||',name}')::text[] as json_path
  from settings, jsonb_array_elements(strategies) 
  with ordinality arr(strategy,index) where strategy->>'name'='bot'
  )
  
  update settings 
  set strategies = jsonb_set(strategies,cte.json_path,'"bot2"',false) 
  from cte ;
  

DEMO

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-17
    • 2019-05-29
    • 1970-01-01
    相关资源
    最近更新 更多