我正在为 PostgreSQL 9.2 中的新 JSON 函数寻找一些文档和/或示例。
具体来说,给定一系列 JSON 记录:
[
{name: "Toby", occupation: "Software Engineer"},
{name: "Zaphod", occupation: "Galactic President"}
]
如何编写 SQL 来按名称查找记录?
在普通 SQL 中:
SELECT * from json_data WHERE "name" = "Toby"
官方的开发手册相当稀少:
我整理了一个 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 文档存储的函数
最佳答案
我引用 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.
并不妨碍他在 PLV8 中提供一个可以解决您的问题的示例实现。 (链接已失效,请参阅现代版 PLV8。)
提供大量新函数和运算符以添加“json-processing”。
Postgres 9.3 中原始问题的答案:
SELECT *
FROM json_array_elements(
'[{"name": "Toby", "occupation": "Software Engineer"},
{"name": "Zaphod", "occupation": "Galactic President"} ]'
) AS elem
WHERE elem->>'name' = 'Toby';
高级示例:
对于较大的表,您可能需要添加表达式索引以提高性能:
添加 jsonb
(b 表示“二进制”,值存储为原生 Postgres 类型)以及 both 类型的更多功能。除了上面提到的表达式索引,jsonb
还支持GIN, btree and hash indexes , GIN 是其中最有效的。
json
and jsonb
data types 上的手册和 functions .本手册建议:
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.
完整的jsonb
函数和操作符。添加更多函数来操作 jsonb
并显示。
https://stackoverflow.com/questions/10560394/
相关文章:
.net - 如何将 JObject 反序列化为 .NET 对象
javascript - 如何将 console.log(object) 的输出保存到文件中?
json - 在 ASP.Net MVC 中设置 Access-Control-Allow-Orig
ajax - Google Chrome 将 JSON AJAX 响应显示为树而不是纯文本
javascript - 由于 JSON 中的转义单引号,jQuery.parseJSON 抛出 “
python - 从请求库解析 JSON 响应的最佳方法是什么?