【问题标题】:YugabyteDB not using expression index on json columnYugabyteDB 未在 json 列上使用表达式索引
【发布时间】:2021-09-15 11:31:03
【问题描述】:

[YugabyteDB用户提出的问题]

我很难让查询规划器在下面的查询中使用索引:

postgres=# create table books(k int primary key, doc jsonb not null);
postgres=# CREATE INDEX books_year
     ON books (((doc->>'year')::int) ASC)
     WHERE doc->>'year' is not null;
postgres=# EXPLAIN select
   (doc->>'ISBN')::bigint as isbn,
   doc->>'title'          as title,
   (doc->>'year')::int    as year
 from books
 where (doc->>'year')::int > 1850
 order by 3;
                           QUERY PLAN                            
-----------------------------------------------------------------
 Sort  (cost=177.33..179.83 rows=1000 width=44)
   Sort Key: (((doc ->> 'year'::text))::integer)
   ->  Seq Scan on books  (cost=0.00..127.50 rows=1000 width=44)
         Filter: (((doc ->> 'year'::text))::integer > 1850)
(4 rows)

在通过字符串值查询时,看起来它正在使用它:

postgres=# EXPLAIN select
   (doc->>'ISBN')::bigint as isbn,
   doc->>'title'          as title,
   (doc->>'year')::int    as year
 from books
 where (doc->>'year') = '1988'
 order by 3;
                                  QUERY PLAN                                  
------------------------------------------------------------------------------
 Index Scan using books_year on books  (cost=0.00..125.50 rows=1000 width=44)
   Filter: ((doc ->> 'year'::text) = '1988'::text)
(2 rows)

【问题讨论】:

    标签: yugabyte-db


    【解决方案1】:

    索引和查询上的谓词必须匹配如下:

    postgres=# CREATE INDEX books_year ON books (((doc->>'year')::int) asc) where doc->>'year' is not null;
    postgres=# EXPLAIN select
       (doc->>'ISBN')::bigint as isbn,
       doc->>'title'          as title,
       (doc->>'year')::int    as year
    from books
    where (doc->>'year')::int > 1850 and doc->>'year' is not null;
                                    QUERY PLAN                                
    --------------------------------------------------------------------------
     Index Scan using books_year on books  (cost=0.00..5.24 rows=10 width=44)
       Index Cond: (((doc ->> 'year'::text))::integer > 1850)
    (2 rows)
    

    【讨论】:

      猜你喜欢
      • 2014-08-21
      • 1970-01-01
      • 2018-10-07
      • 2011-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-09
      • 2021-12-26
      相关资源
      最近更新 更多