Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

对PostgreSQL jsonb部分key进行索引 #29

Closed
ferstar opened this issue Dec 11, 2020 · 0 comments
Closed

对PostgreSQL jsonb部分key进行索引 #29

ferstar opened this issue Dec 11, 2020 · 0 comments

Comments

@ferstar
Copy link
Owner

ferstar commented Dec 11, 2020

由于是在已有的项目上添加一点新的功能,比如需要支持模糊搜索,但不凑巧的是有几个key是存在一个jsonb col里的,like无法命中缓存,所以查询速度略慢。

一番搜索发现pg_trgm模块提供函数和操作符测定字母,数字,文本基于三元模型匹配的相似性, 还有支持快速搜索相似字符串的索引操作符类,于是实测了下,确实可以命中缓存。

image

记录下启用gin index的SQL:

create extension if not exists pg_trgm;
create extension if not exists btree_gin;
create index idx_file_meta on file using gin ((meta ->> 'name'), (meta ->> 'alias') gin_trgm_ops);

ORM查询

key = 'name'
value = 'sample'
cond = File.meta[key].astext.like(f'%{value.replace("%", "")}%')
...
# 转成实际的SQL语句就是
meta ->> 'name' like '%sample%'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant