微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用新的PostgreSQL JSON数据类型中的字段进行查询?

我正在寻找一些文档和/或示例在Postgresql 9.2中的新的JSON函数

具体来说,给出一系列JSON记录:

[
  {name: "Toby",occupation: "Software Engineer"},{name: "Zaphod",occupation: "galactic President"}
]

我如何写sql来按名称查找记录?

在vanilla sql中:

SELECT * from json_data WHERE "name" = "Toby"

官方dev手册是相当稀疏:

> http://www.postgresql.org/docs/devel/static/datatype-json.html
> http://www.postgresql.org/docs/devel/static/functions-json.html

更新I

我把一个gist detailing what is currently possible with PostgreSQL 9.2
使用一些自定义函数,可以做以下事情:

SELECT id,json_string(data,'name') FROM things
WHERE json_string(data,'name') LIKE 'G%';

更新二

我现在把我的JSON函数移动到自己的项目:

PostSQL – 一组用于将Postgresql和PL / v8转换为完全真棒的JSON文档存储的函数

Postgres 9.2

我引用Andrew Dunstan on the pgsql-hackers list

At some stage there will possibly be some json-processing (as opposed
to json-producing) functions,but not in 9.2.

不阻止他提供一个example implementation in PLV8应该解决你的问题。

Postgres 9.3

提供了一个新的功能和运算符添加“json处理”。

> The manual on new JSON functionality.
> The Postgres Wiki on new features in pg 9.3
> @ a comments belowblog demonstrating the new operators发布了一个链接

在Postgres 9.3中的原始问题的答案:

SELECT *
FROM   json_array_elements(
  '[{"name": "Toby","occupation": "Software Engineer"},{"name": "Zaphod","occupation": "galactic President"} ]'
  ) AS elem
WHERE elem->>'name' = 'Toby';

高级示例:

> Query combinations with nested array of records in JSON datatype

对于较大的表,您可能需要添加一个表达式索引以提高性能

> Index for finding an element in a JSON array

Postgres 9.4

添加jsonb(b为“二进制”,值作为本地Postgres类型存储),但是更多的功能为这两种类型。除了上面提到的表达式索引,jsonb还支持GIN,btree and hash indexes,GIN是最强大的。

> json and jsonb data typesfunctions上的手册。
> The Postgres Wiki on JSONB in pg 9.4

手册最多建议:

In general,most applications should prefer to store JSON data as
jsonb
,unless there are quite specialized needs,such as legacy
assumptions about ordering of object keys.

大胆强调我。

Performance benefits from general improvements to GIN indexes.

Postgres 9.5

完成jsonb函数和运算符。添加更多的函数来操纵jsonb到位和显示

> Major good news in the release notes of Postgres 9.5.

原文地址:https://www.jb51.cc/postgresql/193982.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐