相关疑难解决方法(0)

如何将 JSON 数组转换为 Postgres 数组?

我有一个data类型的列,json其中包含这样的 JSON 文档:

{
    "name": "foo",
    "tags": ["foo", "bar"]
}
Run Code Online (Sandbox Code Playgroud)

我想将嵌套tags数组转换为连接字符串 ( 'foo, bar')。array_to_string()从理论上讲,使用该函数很容易做到这一点。但是,此功能不接受json输入。所以我想知道如何将这个 JSON 数组变成 Postgres 数组(类型text[])?

postgresql array postgresql-9.3 json

97
推荐指数
4
解决办法
28万
查看次数

在 Postgres 中搜索 JSON 数据哪个更有效:GIN 或多个索引列?

例如,假设我有一个中等行数(约 100,000 行)的表,其中一jsonb列包含以下示例数据:

{"name":"Bob", "favoriteColor":"red", "someOtherObject": {"somethingElse": true}}
Run Code Online (Sandbox Code Playgroud)

是否更有效:

  1. 在 jsonb 列上使用 GIN 索引,然后使用 Postgres 的内置 JSON 查询函数来提取数据

  2. 创建多列来表示可以搜索的内容,即一列用于name,一列用于favoriteColor等;在这些列上构建 b 树索引,然后运行select document from table where name = 'Bob'

  3. 一些其他的解决方案?

    请记住,解决方案需要有效地支持like查询,以便能够搜索以给定输入字符串开头的值。

postgresql index json postgresql-9.6

7
推荐指数
1
解决办法
5976
查看次数

PostgreSQL 运算符使用索引但底层函数不使用

我正在尝试JSONB与 JDBC一起使用,这意味着我必须避免使用任何使用 '?' 的运算符。字符(因为 PostgreSQL JDBC 驱动程序没有对该字符进行转义)。拿一个简单的表格:

CREATE TABLE jsonthings(d JSONB NOT NULL);
INSERT INTO jsonthings VALUES
    ('{"name":"First","tags":["foo"]}')
  , ('{"name":"Second","tags":["foo","bar"]}')
  , ('{"name":"Third","tags":["bar","baz"]}')
  , ('{"name":"Fourth","tags":["baz"]}');
CREATE INDEX idx_jsonthings_name ON jsonthings USING GIN ((d->'name'));
Run Code Online (Sandbox Code Playgroud)

使用命令行我可以运行一个简单的选择并按预期使用索引:

EXPLAIN ANALYZE SELECT d FROM jsonthings WHERE d->'name' ? 'First';

                                                            QUERY PLAN                                                            
----------------------------------------------------------------------------------------------------------------------------------
 Bitmap Heap Scan on jsonthings  (cost=113.50..30236.13 rows=10000 width=61) (actual time=0.024..0.025 rows=1 loops=1)
   Recheck Cond: ((d -> 'name'::text) ? 'First'::text)
   Heap Blocks: exact=1
   ->  Bitmap Index Scan on idx_jsonthings_name  (cost=0.00..111.00 rows=10000 width=0) (actual …
Run Code Online (Sandbox Code Playgroud)

postgresql index-tuning json operator postgresql-9.4

6
推荐指数
1
解决办法
1756
查看次数

在 JSONB 记录数组中查找包含键的行

我正在尝试查询对象数组中存在的键。这种结构:

column jdata
{"name": "Somedata",
 "array": [ {"name":"bla1", "attr": "somevalue"}, 
            {"name":"bla2", "otherdata": "somevalue2"},
            {"name":"bla3", "otherdata": "somevalue"}
           ],
"otherstuff": "stuff"
}
Run Code Online (Sandbox Code Playgroud)

现在我在jdata->'name'or上做 btree (jdata->'datetime')::cast,效果很好。

我也做 json_path_opsjdata->'array' @> '[{"name":"bla3"}]'真正的魅力所在。

我的问题是attr键可以在数组中的任何对象中,如果键存在,我关心记录,但是值几乎可以是任何东西。有没有办法查询这个?有没有办法索引它?我想做jdata->'array' @> '[{"attr": ?}]'或者也许? 'attr'可以在数组中以某种方式使用?

目前我正在考虑一个扫描键的触发器,然后将它移动到一个带有 true 或 false 或其他什么的标题,然后一个普通的 btree 将工作。有没有更好的办法?我需要在平均站点上编辑大约 50 万条记录才能添加这些值。

请给我指明一个方向。

postgresql index array json json-path

5
推荐指数
1
解决办法
2万
查看次数