Skip to content

Query Performance Improvement Template Search

정회성 edited this page Oct 29, 2024 · 1 revision

Step-by-Step Improvement of Query Average Speed

스크린샷 2024-10-29 11 46 32

Final Improvement: 26s -> 16s

Queries Executed in the Search API

When a search API request is made, the following four query methods are executed:

  • TemplateJpaRepository.findAll()

    • Fetches "templates" along with the "categories," resulting in an N + 1 problem.
  • TemplateTagJpaRepository.findAllByTemplate()

    • Fetches tags for each template individually.
    • Fetches "template tags" while querying "tags," resulting in an N + 1 problem.
  • ThumbnailJpaRepository.fetchByTemplate()

    • Fetches thumbnails for each template individually.
    • Fetches "thumbnails" while querying "source codes," resulting in an N + 1 problem.
  • MemberJpaRepository.fetchByTemplateId()

    • Fetches the author member of the template.
    • Contains unnecessary logic.

The total number of templates is N, the total number of categories is C, the average number of tags per template is T, and the average number of source codes per template is SC. The following number of queries will be executed:

-> O(N * (C + T + SC))

1. Improving the N + 1 Problem

Improving Category Retrieval for N + 1 Problem

Before Improvement

  • Each of the M "templates" fetches the "category" once.
image

Improving Tag Retrieval for N + 1 Problem

TemplateTagJpaRepository.findAllByTemplate() -> TemplateTag(1) + Tag(N)

Before Improvement

  • Each of the M "templates" fetches "template tags" once.
  • For the N "template tags" fetched, queries the "tags."
image

After Applying Fetch Join

@Query("""
        SELECT tt, t
        FROM TemplateTag tt
        JOIN FETCH tt.tag t
        WHERE tt.id.templateId = :templateId
        """)
List<TemplateTag> findAllByTemplate(Template template);
image

Improving Thumbnail Retrieval

Before Improvement

image

After Applying Fetch Join

@Query("""
        SELECT t, sc
        FROM Thumbnail t
        JOIN FETCH t.sourceCode sc
        WHERE t.template = :template
        """)
image

2. Improving Logic

  • Fetch the Template's TemplateTags into a List.
  • Fetch the Template's Thumbnails into a List.

Before Improvement

After Improvement

3. Creating Full-Text Search Index

ALTER TABLE template ADD FULLTEXT INDEX idx_template_fulltext (title, description);
ALTER TABLE source_code ADD FULLTEXT INDEX idx_source_code_fulltext (content, filename);

⚡️ 코드zap

프로젝트

규칙 및 정책

공통

백엔드

프론트엔드

매뉴얼

백엔드

기술 문서

백엔드

프론트엔드

회의록


Clone this wiki locally