PostgreSQL json 搜索

PostgreSQL json search

我正在考虑以 postgres jsonb 数据类型存储一些数据。会有这样的结构

{"name": "Jhon Smith", "emails": ["smith@test.com", "agent@matrix.net"],
 "phones": ["123456789", "987654321"]}.

我知道,我可以像这样搜索这个结构

where contact->'emails' @> '"smith@test.com"'::jsonb;

但是我需要用一些 LIKE 运算符搜索我的数据,所以

where contact->'emails' <SOME_JSON_LIKE_OPERATOR> "smith"';

我找不到psql是否有类似的东西,也许没有。所以,也许我可以将 contact->'emails' 字段转换为 Text ('["smith@test.com", "agent@matrix.net"]') 然后使用简单的 LIKE.. 你会如何解决这个问题?

您可以将 json 数组扩展为一个文本记录集,然后以您喜欢的任何方式进行搜索:

where exists (
    select 1 from json_array_elements_text(contact->'emails')
    where 
        value like "%smith%"
    )