yugabyte-db - YugabyteDB 未在 json 列上使用表达式索引
问题描述
[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)
解决方案
索引和查询上的谓词必须匹配如下:
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)
推荐阅读
- c# - 文件内容搜索c#
- android - gradlew.bat 上的 React Native 构建错误
- sql - 根据传入的时间值(从列表中)获取下一次的值
- postgresql - Proc SQL 到 Postgres UFT8 数据库:不可打印字符显示为普通问号,无法删除
- php - 如果目标时间小于 PHP 中的当前时间,如何打印消息
- git - Git:查找未合并到特定远程分支的远程分支
- unix - 测试命令不在 Crontab 中运行
- javascript - 按出现等级排列数组元素
- javascript - 带有 url 列的网格 webix 单击
- docker-compose - Ansible 和 docker-compose pull / up -d