在PostgreSQL列中复制和转换文本
假设我有一些JSON存储在PostgreSQL中的JSON,就像这样:
{"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中进行此操作,因此我不会从一列中读取文本,在其他地方运行脚本,然后在单独的列中添加文本。有人知道有一种方法吗?我可以使用某种脚本吗?
Let's say I have some JSON stored in postgresql like so:
{"the": [0, 4], "time": [1, 5], "is": [2, 6], "here": [3], "now": [7]}
This is an inverted index showing the position of each word, which spells out
the time is here the time is now
I want to put the text from the second example in a separate column. I can convert the inverted text with python like so:
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
But I would love to do this within postgresql so I am not reading text from one column, running a script somewhere else, then adding text in a separate column. Anybody know of a way to go about that? Can I use some kind of script?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要使用
jsonb_each()
获得键,并用JSONB_ARRAY_ELEMENTS()
将数组解开包装,然后用适当的顺序汇总键:在 db<
You need to get keys with
jsonb_each()
and unpack arrays withjsonb_array_elements()
then aggregate the keys with proper order:Test it in Db<>fiddle.