复制和转换 postgresql 列中的文本

Copy and convert text in postgresql column

假设我有一些 JSON 存储在 postgresql 中,如下所示:

{"the": [0, 4], "time": [1, 5], "is": [2, 6], "here": [3], "now": [7]}

这是一个倒排索引,显示每个单词的位置,拼写出来

the time is here the time is now

我想将第二个示例中的文本放在单独的列中。我可以像这样用 python 转换倒排文本:

def convert_index(inverted_index):
    unraveled = {}
    for key, values in inverted_index.items():
        for value in values:
            unraveled[value] = key

    sorted_unraveled = dict(sorted(unraveled.items()))
    result = " ".join(sorted_unraveled.values())
    result = result.replace("\n", "")
    return result

但我很想在 postgresql 中执行此操作,因此我不会从一列中读取文本,运行 其他地方的脚本,然后在单独的列中添加文本。有人知道解决这个问题的方法吗?我可以使用某种脚本吗?

您需要使用 jsonb_each() 获取键并使用 jsonb_array_elements() 解压数组,然后按正确的顺序聚合键:

with my_table(json_col) as (
values
('{"the": [0, 4], "time": [1, 5], "is": [2, 6], "here": [3], "now": [7]}'::jsonb)
)

select string_agg(key, ' ' order by ord::int)
from my_table
cross join jsonb_each(json_col)
cross join jsonb_array_elements(value) as e(ord)

Db<>fiddle.

中测试