mg1*_*075 5 postgresql json postgresql-9.5
Postgres 9.5
给定一个表,其中包含一个类型为 的字段json,大约有 700 行,并且每行在单个数组中大约有 4,000 个元素......
我的数据库字段:
[0.44577, 0.4855, 0.45429, 0.54437,...]
[0.45012, 0.48698, 0.45715, 0.55337,...]
[0.47347, 0.49156, 0.46079, 0.56818,...]
[0.4936, 0.49835, 0.46086, 0.58195,...]
[0.51068, 0.50511, 0.46228, 0.59482,...]
Run Code Online (Sandbox Code Playgroud)
PostgreSQL文档展示了如何查询数组中的单个元素。
SELECT my_db_field->2 AS test FROM my_db_table
Run Code Online (Sandbox Code Playgroud)
结果:
test (of type json)
--------------------
0.4855
0.48698
0.49156
etc.
Run Code Online (Sandbox Code Playgroud)
不过,我想做的是选择数组中的多个元素,并将其作为与行格式相同的数组返回。我所说的多个是指数组中大约有 300 个元素;例如,从元素 0 到元素 300。Postgres 对于这样的查询有很好的语法吗?
小智 9
在 PostgreSQL 12 中,您可以使用以下jsonb_path_query_array函数获取 JSONB 数组切片:
SELECT jsonb_path_query_array('["a","b","c","d","e","f"]', '$[2 to 4]');
jsonb_path_query_array
------------------------
["c", "d", "e"]
(1 row)
Run Code Online (Sandbox Code Playgroud)
select array_to_json
(
(select array_agg(my_db_field->n order by n)
from generate_series(0,least(300,json_array_length(my_db_field))-1) gs(n)
)
)
from my_db_table
Run Code Online (Sandbox Code Playgroud)
这个解决方案(这个答案中的原始解决方案)很可能不能保证元素的顺序
select (array(select json_array_elements(my_db_field)))[1:300]
from my_db_table
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6576 次 |
| 最近记录: |