Like 对 postgresql 中的 Json 对象的操作

Like operation on Json object in postgresql

我的 table 中有 JSON 列,其中包含字典数组。该数组具有标准格式。

[{'path': 'chat/xyz.pdf', 'file_name': 'xyz.pdf'},
 {'path': 'chat/xyl.pdf', 'file_name': 'xyl.pdf'}]

table 名称是 chat,列名称是 attachments。我想对文件名执行搜索,这样即使我输入了一个字母,也应该检索该行。例如:如果我按字符串 'pd' 搜索,则应检索具有 file_name 和 'pd' 字符串的所有值。

我试过了,确实有效。

select distinct attachments from chat, jsonb_array_elements_text(attachments)
where value::json->>'file_name' like '%xyz%';

我从文档中获取了 reference

您可以使用 EXISTS 条件,然后就不需要 DISTINCT:

select c.*
from chat c
where exists (select *
              from jsonb_array_elements(c.attachments) as t(doc)
              where t.doc ->> 'file_name' like '%xyz%');