如何在postgresql中的jsonb列中搜索

时间:2016-07-11 13:37:51

标签: postgresql jsonb

我基本上有一个postgresql表,它有一个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"和#34;人族"在我的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

2 个答案:

答案 0 :(得分:1)

您必须使用“获取值作为文本”运算符->>才能实现此目的:

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

我还将其添加到收到电子邮件中,因为我认为您希望将其作为文本。

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

答案 1 :(得分:1)

使用->> operator

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