PostgreSQL:获取jsonb数组中对象的值以进行全文搜索

时间:2017-05-24 18:06:17

标签: sql postgresql full-text-search jsonb postgresql-9.6

如何根据作为数组一部分的对象内的键获取某个值?我将json数据存储为我的Postgres 9.6 DB中的jsonb

addresses (JSONB)
---------
[{"address":"abc@def.com", "type": "home"}, {"address":"xyz@def.com", "type": "work"}]

我喜欢做的事情是:

SELECT addresses ->> 'address' FROM foo

然后在全文搜索中使用结果,我搜索特定的电子邮件地址,如:

SELECT * FROM foo WHERE 
to_tsvector('simple', CAST(addresses ->>'address' as text)) @@ to_tsquery('abc:*');

我运行第一个查询时得到的只有:(NULL)

1 个答案:

答案 0 :(得分:3)

你应该使用jsonb_array_elements():

取消json数组
with foo(addresses) as (
values
    ('[{"address":"abc@def.com", "type": "home"}, {"address":"xyz@def.com", "type": "work"}]'::jsonb)
)

select value->>'address' as address
from foo,
jsonb_array_elements(addresses)
where to_tsvector('simple', value->>'address') @@ to_tsquery('abc:*');

   address   
-------------
 abc@def.com
(1 row)