【问题标题】:Is there a jsonb array overlap function for postgres?postgres 是否有 jsonb 数组重叠功能?
【发布时间】:2016-01-11 15:18:30
【问题描述】:

无法从 postgres 中的 jsonb 中提取和比较两个数组以进行重叠检查。有这个功能吗?

people_favorite_color 表中的示例:

{
    "person_id":1,
    "favorite_colors":["red","orange","yellow"]
}
{
    "person_id":2,
    "favorite_colors":["yellow","green","blue"]
}
{
    "person_id":3,
    "favorite_colors":["black","white"]
}

数组重叠 postgres 测试:

select 
p1.json_data->>'person_id',
p2.json_data->>'person_id',
p1.json_data->'favorite_colors' && p2.json_data->'favorite_colors'
from people_favorite_color p1 join people_favorite_color p2 on (1=1)
where p1.json_data->>'person_id' < p2.json_data->>'person_id'

预期结果:

p1.id;p2.id;likes_same_color
1;2;t
1;3;f
2;3;f

--编辑-- 尝试转换为 text[] 会导致错误:

select
('{
        "person_id":3,
        "favorite_colors":["black","white"]
}'::jsonb->>'favorite_colors')::text[];

ERROR:  malformed array literal: "["black", "white"]"
DETAIL:  "[" must introduce explicitly-specified array dimensions.

【问题讨论】:

  • 尝试将p1.json_data-&gt;'favorite_colors' 的结果转换为text[],那么您应该可以使用通常的数组重叠运算符。
  • 请使用 JSONLint 验证 json 值。
  • @a_horse_with_no_name 编辑了问题以修复格式并包含投射结果

标签: arrays postgresql jsonb


【解决方案1】:

使用array_agg()jsonb_array_elements_text()将jsonb数组转换为文本数组:

with the_data as (
    select id, array_agg(color) colors
    from (
        select json_data->'person_id' id, color
        from 
            people_favorite_color, 
            jsonb_array_elements_text(json_data->'favorite_colors') color
        ) sub
    group by 1
    ) 
select p1.id, p2.id, p1.colors && p2.colors like_same_colors
from the_data p1
join the_data p2 on p1.id < p2.id
order by 1, 2;

 id | id | like_same_colors 
----+----+------------------
 1  | 2  | t
 1  | 3  | f
 2  | 3  | f
(3 rows)    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-19
    • 1970-01-01
    • 2016-06-14
    • 1970-01-01
    • 2023-03-16
    • 2020-05-14
    相关资源
    最近更新 更多