简体   繁体   English

如何使用 Spring Data Jpa 和 postgres 中的索引使我的本机查询更快

[英]How to make my native query faster using indexing in Spring Data Jpa and postgres

I am trying to search a join table of millions of records using JPA native query and PostgreSQL but the result is too slow.我正在尝试使用 JPA 本机查询和 PostgreSQL 搜索包含数百万条记录的连接表,但结果太慢。 I want to make it faster using index search on postgres or any better option that can be suggested.我想使用 postgres 上的索引搜索或任何可以建议的更好的选项来加快速度。 I looked up several articles online like this: https://hashrocket.com/blog/posts/exploring-postgres-gin-index我在网上查了几篇这样的文章: https : //hashrocket.com/blog/posts/exploring-postgres-gin-index

but am not quite sure how to implement it as am not getting the improved speed.但我不太确定如何实现它,因为我没有得到提高的速度。

Here is what I had in my JPA repository:这是我在 JPA 存储库中的内容:

 @Query(value = "SELECT DISTINCT C.APPROVED_NAME AS companyName, C.CITY AS city, C.STATE AS state, 
FROM TABLE_NAME_1 C LEFT JOIN TABLE_NAME_2 AS A ON A.COMPANY_FK = C.ID 
WHERE CONCAT(UPPER(A.FIRSTNAME), ' ', UPPER(A.SURNAME))
 LIKE UPPER(concat(:searchTerm,'%')) ", nativeQuery = true)
    List<table_1_Interface> findByName(@Param("searchTerm") String searchTerm);

Here is what I tried to do using index search (I am new to using index search):这是我尝试使用索引搜索做的事情(我是使用索引搜索的新手):

 @Query(value = "CREATE INDEX company_search_idx ON TABLE_NAME_2(firstname, surname );
SELECT DISTINCT C.APPROVED_NAME AS companyName, C.CITY AS city, C.STATE AS state, 
FROM TABLE_NAME_1 C LEFT JOIN TABLE_NAME_2 AS A ON A.COMPANY_FK = C.ID 
WHERE CONCAT(UPPER(A.FIRSTNAME), ' ', UPPER(A.SURNAME))
 LIKE UPPER(concat(:searchTerm,'%')) ", nativeQuery = true)
    List<table_1_Interface> findByName(@Param("searchTerm") String searchTerm);

Please help me with your suggestions, ideas and solutions.请帮助我提供您的建议、想法和解决方案。

If you search on CONCAT(UPPER(A.FIRSTNAME), ' ', UPPER(A.SURNAME)) then that is what the index needs to be built on (but without the table aliases).如果您在CONCAT(UPPER(A.FIRSTNAME), ' ', UPPER(A.SURNAME))那么这就是索引需要建立的地方(但没有表别名)。 But for pg_trgm it supports ILIKE directly, so you could just use that instead of manually fiddling with case.但是对于 pg_trgm 它直接支持 ILIKE,所以你可以使用它而不是手动摆弄大小写。

Since you only add a % to the end of the search term, you could instead use a btree index with text_pattern_ops.由于您只在搜索词的末尾添加一个 %,因此您可以使用带有 text_pattern_ops 的 btree 索引。 But then you would need the UPPER with LIKE.但是,您将需要带有 LIKE 的 UPPER。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM