简体   繁体   English

从 Postgres jsonb 中提取字段

[英]Extract fields from Postgres jsonb

I'm trying to find an efficient way to extract specific fields from a Postgres jsonb column.我试图找到一种从 Postgres jsonb 列中提取特定字段的有效方法。

CREATE TABLE foo (
  id integer,
  data jsonb
)

"data" contains a row with: “数据”包含一行:

{
  "firstname": "bob",
  "lastname": "smith,
  "tags": ["tag0","tag1"]
}

I want to extract a large number of fields from the data column.我想从数据列中提取大量字段。 This select statement works, but it's cumbersome with large numbers of fields, yields really long SQL statements, and also I don't know if it is traversing the jsonb repeatedly for each column:这个 select 语句有效,但是对于大量字段来说很麻烦,产生非常长的 SQL 语句,而且我不知道它是否重复遍历每列的 jsonb:

SELECT data->>'firstname', data->'tags' FROM foo

I tried this:我试过这个:

SELECT jsonb_path_query(data, '$.[firstname,tags]') FROM foo

but it gave an error message: syntax error, unexpected '[' This syntax is, in fact, correct jsonpath per https://jsonpath.com/ , but it appears that Postgres doesn't implement it.但它给出了一条错误消息: syntax error, unexpected '['实际上,这种语法是正确的 jsonpath 每个https://jsonpath.com/ ,但似乎 Postgres 没有实现它。

Is there a way to extract jsonb fields efficiently, both in terms of execution speed and compactness of the SQL query command?在 SQL 查询命令的执行速度和紧凑性方面,有没有办法有效地提取 jsonb 字段?

Yes, your query will read the complete data column for all rows of foo .是的,您的查询将读取foo的所有行的完整data列。

Even if you normalize the data model and turn your JSON attributes into regular columns, it will read the table row by row, but then your query becomes cheaper if you only access the first couple of columns in the table.即使您规范化数据 model 并将您的 JSON 属性转换为常规列,它也会逐行读取表,但是如果您只访问表中的前几列,您的查询会变得更便宜。

What you are looking for is a column store , but PostgreSQL doesn't have that built in.您正在寻找的是column store ,但 PostgreSQL 没有内置。

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

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