具体来说,给出一系列JSON记录:
[ {name: "Toby",occupation: "Software Engineer"},{name: "Zaphod",occupation: "Galactic President"} ]
在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函数移动到自己的项目:
我引用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
> The manual on new JSON functionality.
> The Postgres Wiki on new features in pg 9.3。
> @ a comments below在blog 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 types和functions上的手册。
> 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