简体   繁体   English

Postgres:使用索引将JSON数组元素扩展为值?

[英]Postgres: expand JSON array elements into values with their index?

I have a table with a column containing a JSON array. 我有一个包含JSON数组的列的表。 As an example: 举个例子:

with example as (
    select '["a", "b"]'::jsonb as col
    union select ('["c", "d", "e"]'::jsonb) as col
)
select col from example

Returns: 返回:

col
["a", "b"]
["c", "d", "e"]

I can use jsonb_array_elements to expand out each array into rows: 我可以使用jsonb_array_elements将每个数组扩展为行:

select jsonb_array_elements(col) from example

Returns: 返回:

jsonb_array_elements
"a"
"b"
"c"
"d"
"e"

I want the index of each array element along with the element itself (a bit like Python's enumerate ), like so: 我想要每个数组元素的索引以及元素本身(有点像Python的enumerate ),如下所示:

jsonb_array_elements    array_index
"a"                     1
"b"                     2
"c"                     1
"d"                     2
"e"                     3

How can I do this? 我怎样才能做到这一点?

My application has read-only access, so I cannot create functions. 我的应用程序具有只读访问权限,因此无法创建功能。

Use with ordinality : with ordinality使用:

with example (col) as (
  values 
    ('["a", "b"]'::jsonb),  
    ('["c", "d", "e"]'::jsonb)
)
select t.*
from example, jsonb_array_elements(col) with ordinality as t(e,idx)

returns: 收益:

e   | idx
----+----
"a" |   1
"b" |   2
"c" |   1
"d" |   2
"e" |   3

with ordinality can only be used if you use the set returning function in the from clause, which is highly recommended anyway. 只有在from子句中使用set returns函数时才能使用with ordinality ,无论如何强烈建议使用。

Ahh that's an interesting little postgres puzzle. 啊,这是一个有趣的小postgres拼图。 How about the below? 下面怎么样?

   WITH example1 AS (
        SELECT '["a", "b"]'::jsonb AS col

    ),
    example2 AS (
        SELECT ('["c", "d", "e"]'::jsonb) AS col
    )

    SELECT  1 AS group, jsonb_array_elements(col) AS jcol, row_number() OVER (ORDER BY jsonb_array_elements(col)) FROM example1
    UNION
    SELECT 2 AS group, jsonb_array_elements(col) AS jcol, row_number() OVER (ORDER BY jsonb_array_elements(col)) FROM example2
    ORDER BY "group", row_number ASC;

That will give you 那会给你

1   "a" 1
1   "b" 2
2   "c" 1
2   "d" 2
2   "e" 3

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

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