如何使用新的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.

相关文章

项目需要,有个数据需要导入,拿到手一开始以为是mysql,结果...
本文小编为大家详细介绍“怎么查看PostgreSQL数据库中所有表...
错误现象问题原因这是在远程连接时pg_hba.conf文件没有配置正...
因本地资源有限,在公共测试环境搭建了PGsql环境,从数据库本...
wamp 环境 这个提示就是说你的版本低于10了。 先打印ph...
psycopg2.OperationalError: SSL SYSCALL error: EOF detect...