PostgreSQL 13.6 - 查询 JSON 导致 "operator does not exist: json -> record"

PostgreSQL 13.6 - Querying JSON resulting in "operator does not exist: json -> record"

我的 PostgreSQL table 中有 json 列,看起来与此类似:

{"example--4--":"test 1","another example--6--":"test 2","final example--e35b172a-af71-4207-91be-d1dc357fe8f3--Equipment":"ticked"}

{"example--4--":"test 4","another example--6--":"test 5","final example--e35b172a-af71-4207-91be-d1dc357fe8f3--Equipment":"ticked"}

每个键包含一个由 -- 分隔的映射。前缀是唯一的,即:“example”、“another example”和“final example”。

我需要查询唯一前缀,到目前为止,我尝试的一切都还很接近。

select some_table.json_column from some_table
left join lateral (select array(select * from json_object_keys(some_table.json_column) as keys) k on true
where (select SPLIT_PART(k::text, '--', 1) as part_name) = 'example'
and some_table.json_column->>k = 'test 1'

以上导致以下错误(最后一行):

operator does not exist: json -> record

我的预期输出是存在 "example--4--":"test 1" 的任何记录(在我上面的示例中,唯一的结果是)

{"example--4--":"test 1","another example--6--":"test 2","final example--e35b172a-af71-4207-91be-d1dc357fe8f3--Equipment":"ticked"}

感谢任何帮助。调试了一段时间后,我可以看到主要问题在隐式转换为 ::text 时得到了解决。 k 似乎是我需要循环和拆分以进行比较的键的“记录”,目前,我正在将记录转换为导致问题的文本。

一种方法是将 EXIST 条件与 jsonb_each_text()

一起使用
select *
from the_table
where exists (select *
              from jsonb_each_text(data) as x(key,value)
              where x.key like 'example%'
                and x.value = 'test 1')

如果您的专栏不是 jsonb(应该是),您需要使用 json_each_text() 代替

另一种选择是使用 JSON 路径表达式:

select *
from the_table
where data @? '$.keyvalue() ? (@.key like_regex  "^example" && @.value == "test 1")'