如何使用JPA Criteria API和Postgres GIN索引进行不区分大小写的搜索

时间:2020-06-15 17:39:07

标签: postgresql hibernate jpa criteria criteria-api

在Postgres 9.6中提供表格

<iframe class="home-page__iframe" frameborder="0" data-branding="homePage" data-branding-type="iframe" src="mysite.local:8081/app/account#/login"></iframe>

创建一些random data using

create table foo
(
    id                 uuid         not null default uuid_generate_v1(),
    bar        varchar(255),

    primary key (id)
);

我想使用GIN索引进行不区分大小写的搜索。问题在于,JPA标准API(与Hibernate传统API不同)不支持insert into foo ( bar ) select md5(random()::text) from generate_series(1, 10000) s(i) ,类似

的查询
ilike

被使用。

但是,在创建像这样的索引时:

select * from foo
where lower(bar) like '%baz%'

似乎无法使用索引。

CREATE  INDEX foo_idx_bar ON foo USING gin (bar gin_trgm_ops);

相比
explain select * from foo
where lower(bar) like '%baz%'

Seq Scan on foo  (cost=0.00..254.01 rows=400 width=48)
  Filter: (lower((bar)::text) ~~ '%baz%'::text)

现在的问题是:

无法轻松更改现有条件API查询,不支持explain select * from foo where bar ilike '%baz%' Bitmap Heap Scan on foo (cost=16.01..20.02 rows=1 width=48) Recheck Cond: ((bar)::text ~~* '%baz%'::text) -> Bitmap Index Scan on foo_idx_bar (cost=0.00..16.01 rows=1 width=0) Index Cond: ((bar)::text ~~* '%baz%'::text) ,API中可以使用lower and like,但结果查询不使用索引。

可以在类似这样的表达式上添加索引:

ilike

使用了索引,但是它似乎仍然是一种解决方法,因为它不支持没有CREATE INDEX foo_idx_bar2 ON foo USING gin (lower(bar) gin_trgm_ops); 的搜索。

那么在Hibernate,JPA或Postgres中是否有任何解决方案可以获取用于区分大小写和不区分大小写的查询的索引?

0 个答案:

没有答案