【问题标题】:Get all jsonb values in one column for usage in to_tsvector在一列中获取所有 jsonb 值,以便在 to_tsvector 中使用
【发布时间】:2020-01-02 15:31:19
【问题描述】:

我有一个表 jsonb 表 t_1,其中包含 jsonb 类型的列 column_1,我需要转换为带有字符串的表,即 jsonb 值的连接

这是一个脚本

    CREATE TABLE t_1 (
       ID serial NOT NULL PRIMARY KEY,
       column_1 jsonb NOT NULL
    );


    INSERT INTO t_1 (column_1)
    VALUES
    (
       '{ "01": "Lily Bush", "03": "prod2uct"}'
    ),
    (
       '{ "41": "Josh William", "12": "product7"}'
    ),
    (
       '{ "07": "Mary Clark", "items" : "product2"}'
    );

我试过了:

SELECT distinct jsonb_array_elements_text(column_1 -> jsonb_object_keys(column_1)) AS Actor FROM t_1

但是这个返回'无法从标量中提取元素'

我试过了:

SELECT tiket, string_agg(column_2, ', ') as list FROM( SELECT column_1 ->> jsonb_object_keys(column_1) as column_2, id as tiket FROM t_1 ) as foo1 GROUP BY tiket

但这里是内部选择

如何在没有内部选择的情况下在一列中获取所有 jsonb 值,就像在第一个查询中一样?

我需要它在to_tsvector中使用

我需要用在

setweight(
to_tsvector('simple', column_with_json::text),
'A'
)

但是column_with_json::text 不是我需要的,我需要获取值,没有键

有什么例子吗?

【问题讨论】:

  • 不要在 SELECT 列表中使用集合返回函数(如 jsonb_object_keys)。在FROM 部分使用它们
  • 我需要在 setweight( to_tsvector('simple', column_with_json::text), 'A' ) 中使用它但是column_with_json::text 不是我需要的,我需要获取值,没有键任何例子?

标签: json postgresql aggregate-functions jsonb


【解决方案1】:

在横向连接中使用jsonb_each_text()

SELECT id, string_agg(value, ', ') AS list
FROM t_1
CROSS JOIN jsonb_each_text(column_1)
GROUP BY id

 id |          list          
----+------------------------
  1 | Lily Bush, prod2uct
  2 | product7, Josh William
  3 | Mary Clark, product2
(3 rows)

如果您想在条件中使用生成的聚合值,请使用HAVING 子句,例如:

SELECT id, string_agg(value, ', ') AS list
FROM t_1
CROSS JOIN jsonb_each_text(column_1)
GROUP BY id
HAVING string_agg(value, ', ') LIKE '%Lily%'

或包装查询中的派生表和WHERE 子句:

SELECT *
FROM (
    SELECT id, string_agg(value, ', ') AS list
    FROM t_1
    CROSS JOIN jsonb_each_text(column_1)
    GROUP BY id
    ) s
WHERE list LIKE '%Lily%'

这两种方法基本上是等效的,在典型情况下它们生成相同的查询计划。在这两种聚合中只计算一次。

【讨论】:

  • 嗯,问题是我需要在where子句中调用一些函数,
  • 我不明白。问题中没有提到功能。无论如何,如果需要,只需添加 WHERE 子句。
  • 我需要在 setweight( to_tsvector('simple', column_with_json::text), 'A' ) 中使用它但是column_with_json::text 不是我需要的,我需要获取值,没有键任何例子?
  • 谢谢!!!假期归来,查看答案,点击设置为正确答案=))
猜你喜欢
  • 2020-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-11
  • 1970-01-01
  • 2022-07-02
  • 2019-01-23
  • 1970-01-01
相关资源
最近更新 更多