简体   繁体   English

Postgres - 在 json 元素数组中搜索

[英]Postgres - search in json array of elements

My table:我的表:

id |身份证 | name |姓名 | open_days开放天数

Column open_days is a json column with following structure:列 open_days 是一个具有以下结构的 json 列:

{
daysOfWeek: ['mon','tue','sat']
months: ['may','november']
}

I would like to find rows where daysOfWeek contain searching element.我想找到 daysOfWeek 包含搜索元素的行。 Something like就像是

SELECT * FROM places WHERE :day=ANY(open_days->'daysOfWeek') 

But above query is not correct.但是上面的查询是不正确的。 Pleas help how to search is json array.请帮助如何搜索json数组。

Thank you.谢谢你。

Assuming open_days is a jsonb column (which it should be), then you can use the contains operator ?假设open_days是一个jsonb列(它应该是),那么您可以使用 contains 运算符? :

select *
from places
where open_days -> 'daysOfWeek' ? :day

If it's a json column, you need to cast it open_days::jsonb -> ...如果是json列,则需要将其open_days::jsonb -> ...


If you want to search for values that contain multiple weekdays, you can use the ?& operator:如果要搜索包含多个工作日的值,可以使用?&运算符:

select *
from places
where open_days -> 'daysOfWeek' ?& array['mon','tue']

the above would return all rows that contain mon and tue以上将返回包含montue所有行

One way is to use json_array_elements() .一种方法是使用json_array_elements()

SELECT *
       FROM places
       WHERE :day = ANY (SELECT json_array_elements(open_days->'daysOfWeek')#>>'{}');

Yet another way to do this is with the containment operator.另一种方法是使用容器操作员。

select * from places where open_days @> '{"daysOfWeek":["mon"]}'

An advantage over using -> ... ?使用-> ... ?的优势-> ... ? is that containment can use the default JSONB index, while the other would require a specialized index.一个是容器可以使用默认的 JSONB 索引,而另一个则需要专门的索引。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM