简体   繁体   English

在Postgres中使用嵌套数组高效查询JSON

[英]Efficiently querying JSON with nested arrays in Postgres

I'm trying to query a JSON data structure in Postgres (9.6 on Amazon RDS). 我正在尝试查询Postgres中的JSON数据结构(Amazon RDS上的9.6)。 The data contains an array of objects, which in turn has an element that contains an array of objects. 数据包含一个对象数组,而这些对象又包含一个包含对象数组的元素。 I'd like to find all records that match a key + value in one of those nested arrays. 我想找到与其中一个嵌套数组中的键+值匹配的所有记录。

Given rows like this: 给定这样的行:

{"drinkers" : [
  {"name" : "geoff", 
   "beers" : [
     {"name": "PBR"},
     {"name" : "Bud Select"}
    ]}, 
  {"name" : "tom", 
   "beers" : [
     {"name": "Bud Light"},
     {"name" : "Busch"}
    ]}
]}

I want to find all rows where there's a drinkers.beers object that's name is "PBR". 我想找到所有的行,其中有一个名为“PBR”的drinkers.beers对象。 The closest I've come is this: 我最接近的是:

select jsonb_data 
from bars 
where jsonb_array_elements(jsonb_array_elements(data -> 'drinkers') -> 'beers') ->> 'name' = 'PBR'``

But this does not work since the where returns a list instead of a single true/false to match on. 但这不起作用,因为where返回一个列表而不是一个匹配的true / false。 I've come up other solutions using sub queries, lateral joins, etc but all these solutions have performance issues, even with proper gin indexes. 我已经提出了使用子查询,横向连接等的其他解决方案,但所有这些解决方案都存在性能问题,即使使用正确的杜松子酒索引也是如此。 Any suggestions on how to query a data structure like this in Postgres? 关于如何在Postgres中查询这样的数据结构的任何建议?

Did you try using the IN operator? 你尝试过使用IN运算符吗?

WHERE 'PBR' IN (
  SELECT jsonb_array_elements(jsonb_array_elements(data -> 'drinkers') -> 'beers') ->> 'name'
);

Another approach would be to use JSONB contain (ie @> ): 另一种方法是使用JSONB contain (即@> ):

WHERE data -> 'drinkers' @> '[{"beers": [{"name": "PBR"}]}]';

对不起,这应该只是一个注释,但如果返回名称的语句给你一个列表或数组,你可以使用'PBR' = ANY jsonb_array_elements(...

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

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