Like 쿼리 Search 개선

·2022년 7월 4일
0

LIKE {target}%LIKE %{target}% 의 차이점

  • LIKE를 이용한 쿼리는 Full table search를 이용하는 경우 굉장히 느리다
    • O(n)
  • INDEX를 생성해야한다.
    • 그냥 INDEX를 생성하는 경우 btree기반 Index가 생성된다
      • {target}%를 쿼리하는 것은 빠르다.
        • btree의 상단에서부터 분기점을 고를 수 있기 때문에
        • O(log(n))
      • %{target}%를 쿼리하는 것은 느리다
        • btree의 상단에서부터 분기점을 고를 수 없으므로 결국 full table search와 같다
        • O(n)

Prefix가 정해지지 않은 target을 위한 Index ?

  • Postgresql 에서는 GiN, GiST와 같은 텍스트 검색을 위한 인덱싱을 제공한다.

GiN, GiST 비교 Docs

  • GIN index lookups are about three times faster than GiST
  • GIN indexes take about three times longer to build than GiST
  • GIN indexes are moderately slower to update than GiST indexes, but about 10 times slower if fast-update support was disabled (docs)
  • GIN indexes are two-to-three times larger than GiST indexes

GiN Index 구현 설명

  • gabcgaga 문자열에서 {'ga': [(0,1), (4,5), (6,7)]}과 같은 형태로 Index를 미리 생성

GiN 적용방법

from django.contrib.postgres.search import SearchVectorField
# Model에 새로운 필드를 생성한다
from django.contrib.postgres.indexes import GinIndex
# Model Meta에 Index를 추가한다.
profile
Ben

0개의 댓글