小编jgm*_*jgm的帖子

针对多个值的 PostgreSql JSONB SELECT

我有一个非常简单的 JSON 表,其中填充了一些示例数据:

CREATE TABLE jsonthings(d JSONB NOT NULL);

INSERT INTO jsonthings VALUES ('{"name":"First","tags":["foo"]}');
INSERT INTO jsonthings VALUES ('{"name":"Second","tags":["foo","bar"]}');
INSERT INTO jsonthings VALUES ('{"name":"Third","tags":["bar","baz"]}');
INSERT INTO jsonthings VALUES ('{"name":"Fourth","tags":["baz"]}');

CREATE INDEX ON jsonthings USING GIN(d);
Run Code Online (Sandbox Code Playgroud)

并且在运行SELECT. SELECT获取值为单个项目的行的简单方法工作正常:

SELECT d FROM jsonthings WHERE d @> '{"name":"First"}';
Run Code Online (Sandbox Code Playgroud)

但是当尝试运行匹配多个值的查询时,name我无法找到如何使用索引。我试过了:

SELECT d FROM jsonthings WHERE d->>'name' = ANY(ARRAY['First', 'Second']);
SELECT d FROM jsonthings WHERE d->'name' ?| ARRAY['First', 'Second'];
SELECT d FROM jsonthings WHERE d#>'{name}' ?| ARRAY['First','Second'];
Run Code Online (Sandbox Code Playgroud)

并且所有这些都显示了对表的顺序扫描(enable_seqscan=false如果可能,我正在使用强制使用索引)。有什么方法可以重写查询以便它使用索引?我知道我可以这样做: …

postgresql json postgresql-9.4

7
推荐指数
2
解决办法
9414
查看次数

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
查看次数