如何在 postgresql 的 jsonb 列中搜索

How to search within a jsonb column in postgresql

我基本上有一个 postgresql table,它有一个 jsonb 类型的列。 json 数据看起来像这样

{
  "personal": {  
    {
       "gender":"male",
       "contact":{
          "home":{
             "email":"ceo@home.me",
             "phone_number":"5551234"
          },
          "work":{
             "email":"ceo@work.id",
             "phone_number":"5551111"
          }
       },
       "religion":"other",
       "languages":[
          "English",
          "Xen"
       ],
       "last_name":"Eeo",
       "birth_date":"1945-07-28",
       "first_name":"Cee",
       "nationality":"Martian",
       "marital_status":"married"
    }
  }
}

我想获取所有 "Martian" 和 "Terran" 国籍的人.. 在我的 postgresql 命令行中这有效

select employees->'personal'->'contact'->'work'->'email' 
from employees 
where employees->'personal' @> '{"nationality":"Martian"}' 
   or employees->'personal' @> '{"nationality":"Terran"}'

这有效..但它很难看..我想运行这样的东西:

select employees->'personal'->'contact'->'work'->'email' 
from employees 
where employees->'personal'->'nationality' in ('Martian','Terran')

但我遇到这样的格式错误:

DETAIL:  Token "Martian" is invalid.
CONTEXT:  JSON data, line 1: Martian

您必须使用 "get value as text" 运算符 ->> 才能实现:

select employees->'personal'->'contact'->'work'->>'email' 
from employees 
where employees->'personal'->>'nationality' in ('Martian','Terran')

我还把它添加到接收电子邮件中,因为我假设你想要它作为文本。

请注意,转换为文本 (employees->'personal'->'nationality')::text 将不起作用,因为它 return 不只是值,而是 json 转换为文本,在本例中为 "Martian" 包括引号。

使用->> operator:

select employees->'personal'->'contact'->'work'->'email' 
from employees 
where employees->'personal'->>'nationality' in ('Martian','Terran')