Showing posts with label elasticsearch. Show all posts
Showing posts with label elasticsearch. Show all posts

Thursday, June 19, 2025

데이터베이스가 있는데 왜 Elasticsearch를 써야 할까?

개발자라면 누구나 한 번쯤 이런 질문을 던져봅니다. "우리에겐 이미 MySQL, PostgreSQL 같은 훌륭한 관계형 데이터베이스(RDBMS)가 있는데, 왜 굳이 Elasticsearch라는 별도의 시스템을 도입해야 할까?" 이 질문은 매우 합리적입니다. 데이터베이스는 데이터 저장소의 왕좌를 굳건히 지키고 있으며, 트랜잭션 처리와 데이터 무결성 보장에 있어서는 타의 추종을 불허합니다. 하지만 '검색'이라는 특정 영역으로 들어가면 이야기는 달라집니다.

결론부터 말하자면, RDBMS와 Elasticsearch는 경쟁 관계가 아닌, 상호 보완적인 관계입니다. RDBMS가 '기록 보관소'의 역할에 충실하다면, Elasticsearch는 그 기록들 속에서 원하는 정보를 빛의 속도로 찾아주는 '전문 사서'와 같습니다. 이 글에서는 왜 우리에게 이 두 시스템이 모두 필요한지, 그리고 언제 Elasticsearch를 선택해야 하는지 그 근본적인 차이점부터 구체적인 사용 사례까지 깊이 있게 파헤쳐 보겠습니다.

근본적인 차이: 데이터 구조의 관점

두 시스템의 가장 핵심적인 차이는 데이터를 저장하고 검색하는 방식에 있습니다. 바로 'B-Tree 인덱스'와 '역색인(Inverted Index)'의 차이입니다.

RDBMS의 B-Tree 인덱스

RDBMS는 주로 B-Tree(Balanced Tree) 구조의 인덱스를 사용합니다. 이 구조는 데이터가 정렬된 상태를 유지하며, 특정 키(예: id = 123)를 찾는 데 매우 효율적입니다. 마치 잘 정리된 사전에서 특정 단어를 찾는 것과 같습니다. 데이터의 추가, 수정, 삭제가 빈번하게 일어나도 균형을 유지하며 일관된 성능을 보장하므로, 트랜잭션 처리(OLTP, Online Transaction Processing)에 최적화되어 있습니다.

하지만 텍스트 내용 전체에서 특정 단어를 검색하는 '전문 검색(Full-text Search)'에는 취약합니다. WHERE content LIKE '%검색어%'와 같은 쿼리는 인덱스를 제대로 활용하지 못하고 테이블 전체를 스캔(Full Table Scan)해야 할 수 있습니다. 이는 데이터가 많아질수록 성능이 기하급수적으로 저하되는 원인이 됩니다.

Elasticsearch의 역색인 (Inverted Index)

Elasticsearch는 루씬(Lucene) 라이브러리를 기반으로 하며, 역색인 구조를 핵심으로 사용합니다. 역색인은 책의 맨 뒤에 있는 '찾아보기'와 같습니다. 어떤 단어가 어떤 페이지(문서)에 등장하는지를 미리 정리해둔 목록입니다.

예를 들어, 다음과 같은 두 개의 문서가 있다고 가정해 봅시다.

  • 문서 1: "The quick brown fox"
  • 문서 2: "A quick brown dog"

역색인은 이 문서들을 다음과 같이 분석(토큰화)하여 저장합니다.

  • quick: [문서 1, 문서 2]
  • brown: [문서 1, 문서 2]
  • the: [문서 1]
  • fox: [문서 1]
  • a: [문서 2]
  • dog: [문서 2]

이제 'quick'과 'brown'이 포함된 문서를 찾고 싶다면, 각 단어의 목록을 보고 교집합인 [문서 1, 문서 2]를 즉시 찾아낼 수 있습니다. 테이블 전체를 훑어볼 필요가 전혀 없습니다. 이것이 Elasticsearch가 방대한 양의 텍스트 데이터 속에서도 놀랍도록 빠른 검색 속도를 보여주는 비결입니다.

Elasticsearch가 빛을 발하는 순간: 주요 사용 사례

이러한 구조적 차이 때문에 Elasticsearch는 특정 시나리오에서 RDBMS를 압도하는 성능과 기능을 제공합니다.

1. 압도적인 전문 검색 (Full-Text Search)

가장 대표적인 사용 사례입니다. 쇼핑몰의 상품 검색, 블로그의 게시물 검색, 기업 내부의 문서 검색 등 텍스트 기반 검색이 필요한 거의 모든 곳에 사용됩니다.

  • 유연한 검색: '파란 운동화'를 검색했을 때, '하늘색 러닝 슈즈'까지 찾아주는 형태소 분석, 동의어 처리, 오타 교정 등이 가능합니다. RDBMS의 LIKE 연산자로는 구현하기 거의 불가능한 기능들입니다.
  • 관련도 점수(Relevance Score): 검색 결과에 순위를 매길 수 있습니다. 검색어가 제목에 있는지, 본문에 몇 번 등장하는지 등 다양한 요소를 조합하여 사용자에게 가장 관련성 높은 결과를 먼저 보여줍니다.
  • 다양한 쿼리 지원: 단순 키워드 검색을 넘어 구문 검색, 불리언(Boolean) 검색, 범위 검색 등 복잡한 검색 요구사항을 손쉽게 처리할 수 있습니다.

2. 로그 및 이벤트 데이터 분석

서버, 애플리케이션, 네트워크 장비 등에서 쏟아져 나오는 방대한 양의 로그 데이터를 실시간으로 수집하고 분석하는 데 탁월합니다. 흔히 ELK 스택(Elasticsearch, Logstash, Kibana) 또는 Elastic Stack으로 불리는 조합이 바로 이 용도입니다.

  • 스키마리스(Schema-less): 정형화되지 않은 다양한 형태의 로그 데이터를 별도의 스키마 정의 없이 유연하게 저장할 수 있습니다.
  • 빠른 집계(Aggregation): 특정 기간 동안의 에러 발생 횟수, IP 주소별 요청 수, 응답 시간 분포 등 복잡한 통계 데이터를 거의 실시간으로 집계하고 시각화할 수 있습니다. RDBMS의 GROUP BY와는 비교할 수 없는 속도를 자랑합니다.

3. 실시간 메트릭 분석 및 APM

시스템의 CPU 사용량, 메모리, 디스크 I/O와 같은 메트릭 데이터나 애플리케이션의 성능 지표(APM, Application Performance Monitoring)를 수집하고 분석하는 데에도 널리 사용됩니다. 시계열 데이터(Time-series data)를 효율적으로 저장하고 빠르게 쿼리할 수 있는 능력 덕분입니다.

4. 지리 공간 데이터 검색 (Geospatial Search)

"내 주변 2km 이내의 카페 찾기"와 같은 위치 기반 서비스를 구현할 때 강력한 성능을 발휘합니다. 위도, 경도 좌표를 기반으로 특정 거리 내의 데이터를 검색하거나, 특정 다각형 영역 내에 포함된 데이터를 찾는 등의 지리 공간 쿼리를 매우 효율적으로 처리합니다.

그럼에도 RDBMS가 필요한 이유

Elasticsearch가 만능은 아닙니다. 데이터의 '원본'을 안전하게 보관하고, 데이터의 일관성과 무결성을 보장해야 하는 영역에서는 여전히 RDBMS가 절대적인 강자입니다.

1. ACID 트랜잭션

은행 계좌 이체, 주문 처리, 결제 시스템 등 데이터의 정합성이 무엇보다 중요한 작업에는 ACID(원자성, 일관성, 고립성, 지속성)를 완벽하게 보장하는 RDBMS가 필수적입니다. Elasticsearch는 분산 시스템의 특성상 '거의 실시간(Near Real-Time)'으로 동작하며, 엄격한 의미의 트랜잭션을 지원하지 않습니다. 데이터가 색인되기까지 약간의 지연(기본 1초)이 존재할 수 있습니다.

2. 복잡한 관계와 조인(Join)

정교하게 정규화된 여러 테이블을 조인하여 복잡한 관계를 표현하고 데이터를 조회하는 작업은 RDBMS의 고유 영역입니다. Elasticsearch는 nested 객체나 parent-child 관계를 통해 제한적인 조인을 흉내 낼 수는 있지만, RDBMS의 유연하고 강력한 조인 성능에는 미치지 못합니다.

3. 데이터의 '진실의 원천(Source of Truth)'

대부분의 아키텍처에서 데이터의 최종 원본은 RDBMS에 저장합니다. Elasticsearch는 이 원본 데이터를 기반으로 검색과 분석을 위한 '사본'을 구축하는 보조 데이터 저장소로 활용되는 경우가 많습니다. 데이터가 유실되거나 불일치가 발생했을 때 최종적으로 신뢰할 수 있는 기준은 RDBMS가 되어야 합니다.

최적의 조합: 함께 사용하는 아키텍처

현대적인 서비스 아키텍처는 두 시스템의 장점을 모두 활용하는 방향으로 진화하고 있습니다.

  1. 데이터 생성: 사용자의 요청(예: 상품 등록)은 먼저 RDBMS(예: PostgreSQL)에 저장됩니다. 이로써 데이터의 무결성과 트랜잭션이 보장됩니다.
  2. 데이터 동기화: RDBMS에 데이터가 변경(생성/수정/삭제)되면, 이 변경 사항을 비동기적으로 Elasticsearch에 전달하여 색인합니다. Logstash, Debezium 같은 CDC(Change Data Capture) 도구나 메시지 큐(Kafka, RabbitMQ)를 활용할 수 있습니다.
  3. 데이터 조회:
    • '마이페이지'에서 내 주문 내역을 정확히 조회하는 등 트랜잭션이 중요한 정보는 RDBMS에서 직접 읽어옵니다.
    • 메인 페이지에서 상품을 검색하는 기능은 Elasticsearch에 쿼리하여 빠르고 관련도 높은 결과를 얻습니다.

이러한 구조를 통해 시스템의 안정성과 검색 성능이라는 두 마리 토끼를 모두 잡을 수 있습니다.

결론: '무엇을'이 아닌 '언제, 어떻게'의 문제

이제 "데이터베이스가 있는데 왜 Elasticsearch를 써야 할까?"라는 질문에 대한 답이 명확해졌을 것입니다. 이것은 어느 한쪽을 선택하는 'if'의 문제가 아니라, 각자의 강점을 이해하고 적재적소에 활용하는 'when'과 'how'의 문제입니다.

RDBMS는 데이터의 무결성과 안정적인 저장을 책임지는 우리 시스템의 든든한 심장입니다. 반면, Elasticsearch는 방대한 정보의 바다 속에서 사용자가 원하는 것을 정확하고 빠르게 찾아주는 강력한 두뇌와 같습니다. 이 두 가지를 현명하게 조합할 때, 우리는 비로소 사용자에게 최고의 경험을 제공하는 견고하고 확장 가능한 시스템을 구축할 수 있을 것입니다.

Database vs. Elasticsearch: When to Use Which?

It's a question every developer faces sooner or later: "We already have a robust relational database (RDBMS) like PostgreSQL or MySQL. Why do we need to add another system like Elasticsearch to our stack?" This is a perfectly valid question. Databases are the undisputed kings of data storage, excelling at transactional integrity and ensuring data consistency. However, when the conversation shifts to the specific domain of 'search', the story changes.

To put it simply, RDBMS and Elasticsearch are not competitors; they are collaborators. If an RDBMS is the meticulous 'archivist' responsible for keeping records safe, Elasticsearch is the 'expert librarian' who can find any piece of information within those archives at lightning speed. This article will take a deep dive into why you often need both, exploring their fundamental differences and the specific use cases where Elasticsearch truly shines.

The Fundamental Difference: How Data Is Indexed

The core distinction between the two systems lies in how they store and retrieve data. It all comes down to the difference between a 'B-Tree index' and an 'Inverted Index'.

RDBMS and the B-Tree Index

Relational databases primarily use a B-Tree (Balanced Tree) index structure. This structure keeps data sorted and is highly efficient for finding specific records based on an exact key match (e.g., WHERE user_id = 54321). It's like looking up a word in a well-organized dictionary. B-Trees maintain their balance and consistent performance even with frequent inserts, updates, and deletes, making them ideal for Online Transaction Processing (OLTP).

However, they struggle with full-text search—searching for a term within a large block of text. A query like WHERE description LIKE '%search_term%' often cannot use the index effectively and may result in a Full Table Scan. As the dataset grows, the performance of such queries degrades exponentially.

Elasticsearch and the Inverted Index

Elasticsearch, built on the Apache Lucene library, uses an Inverted Index at its core. An inverted index is conceptually similar to the index at the back of a book. It's a pre-compiled list of every unique word and the documents in which it appears.

For instance, imagine you have two documents:

  • Document 1: "The quick brown fox jumps"
  • Document 2: "A quick brown dog barks"

An inverted index would analyze (tokenize) these documents and store the information like this:

  • quick: [Document 1, Document 2]
  • brown: [Document 1, Document 2]
  • the: [Document 1]
  • fox: [Document 1]
  • jumps: [Document 1]
  • a: [Document 2]
  • dog: [Document 2]
  • barks: [Document 2]

Now, if you want to find documents containing both "quick" and "brown," Elasticsearch simply looks up the lists for each term and finds their intersection: [Document 1, Document 2]. There's no need to scan the full text of every document. This is the secret behind Elasticsearch's incredible speed for searching through massive volumes of text data.

When Elasticsearch Shines: Key Use Cases

This structural difference allows Elasticsearch to offer performance and features that are simply out of reach for an RDBMS in certain scenarios.

1. Unmatched Full-Text Search

This is its flagship use case. From e-commerce product search and blog post discovery to internal corporate document retrieval, Elasticsearch is the go-to solution.

  • Linguistic Flexibility: It can handle typos, synonyms, and stemming (e.g., a search for "running shoes" can match a document containing "ran in my shoe"). These are features that are extremely difficult to implement with a database's LIKE operator.
  • Relevance Scoring: Search results are not just found; they are ranked. Elasticsearch calculates a relevance score (e.g., using algorithms like TF-IDF or BM25) based on factors like term frequency and where the term appears (title vs. body), ensuring the most relevant results are shown first.
  • Rich Query DSL: It supports a wide array of queries, from simple keyword searches to phrase matching, boolean logic, range queries, and more, all through a powerful JSON-based Query DSL.

2. Log and Event Data Analysis

Elasticsearch is exceptionally good at ingesting, storing, and analyzing the vast streams of log data generated by servers, applications, and network devices. The famous ELK Stack (Elasticsearch, Logstash, Kibana)—now the Elastic Stack—was built for this purpose.

  • Schema-on-Read: It can flexibly handle unstructured and semi-structured log data without requiring a predefined schema.
  • Powerful Aggregations: You can perform complex statistical analysis in near real-time. Calculating error rates over time, counting requests by IP address, or creating a histogram of API response times are incredibly fast operations, far outperforming a typical RDBMS GROUP BY clause.

3. Real-time Metrics and APM

It's widely used for storing and visualizing metrics like CPU usage, memory, and disk I/O, as well as Application Performance Monitoring (APM) data. Its ability to efficiently store and query time-series data makes it a perfect fit.

4. Geospatial Search

Implementing location-based services, such as "find all coffee shops within a 2-mile radius," is a strength of Elasticsearch. It handles geospatial queries—like searching for data points within a certain distance or inside a specific polygon—very efficiently.

Why You Still Need Your Database

Elasticsearch is not a silver bullet. For tasks that demand data integrity, consistency, and a single source of truth, the RDBMS remains the undisputed champion.

1. ACID Transactions

For operations like financial transactions, order processing, or inventory management, the guarantees of ACID (Atomicity, Consistency, Isolation, Durability) provided by an RDBMS are non-negotiable. Elasticsearch is a "near real-time" system due to its distributed nature; there's a slight delay (typically 1 second by default) before new data becomes searchable, and it does not support ACID transactions in the traditional sense.

2. Complex Joins and Relational Data

RDBMSs are designed to handle complex relationships through joins across multiple, well-normalized tables. While Elasticsearch offers workarounds like nested objects and parent-child relationships, they are not as flexible or performant as SQL joins for highly relational data models.

3. The "Source of Truth"

In most modern architectures, the RDBMS serves as the primary data store or the "source of truth." Elasticsearch is often used as a secondary data store, a "copy" of the data that is optimized for search and analysis. If there's a data discrepancy, the RDBMS is the system you trust.

The Best of Both Worlds: A Common Architecture

Modern application architecture often leverages the strengths of both systems in harmony.

  1. Data Write: A user action (e.g., creating a new product) writes the data to the primary RDBMS (e.g., PostgreSQL). This ensures transactional integrity.
  2. Data Sync: The change in the RDBMS is then asynchronously propagated to Elasticsearch for indexing. This can be achieved using Change Data Capture (CDC) tools like Debezium, or via a message queue like Kafka or RabbitMQ.
  3. Data Read:
    • For transactional reads, like fetching a user's exact order history from their profile page, the application queries the RDBMS directly.
    • For discovery features, like searching for products on the homepage, the application queries Elasticsearch to get fast, relevant results.

This pattern allows you to build a system that is both robust and offers a high-performance user experience.

Conclusion: It's Not "If," but "When and How"

The question "Why use Elasticsearch when we have a database?" now has a clear answer. It's not a matter of choosing one over the other, but of understanding their respective strengths and using them appropriately.

Your RDBMS is the reliable heart of your system, responsible for data integrity and stable storage. Elasticsearch is the powerful brain, capable of navigating the vast ocean of information to find exactly what the user needs, instantly. By intelligently combining the two, you can build scalable, resilient systems that deliver a truly superior user experience.

データベースがあるのに、なぜElasticsearchを使うのか?

開発者であれば、一度はこんな疑問を抱いたことがあるでしょう。「私たちのシステムには、MySQLやPostgreSQLといった優れたリレーショナルデータベース(RDBMS)が既にある。なぜわざわざElasticsearchという別のシステムを導入する必要があるのだろうか?」これは非常に合理的な問いです。データベースはデータストレージの王座に君臨し、トランザクション処理やデータ整合性の保証においては、他の追随を許しません。しかし、「検索」という特定の領域に焦点を当てると、話は大きく変わってきます。

結論から言えば、RDBMSとElasticsearchは競合する関係ではなく、相互に補完し合う関係にあります。RDBMSが「記録保管庫」としての役割を忠実に果たすなら、Elasticsearchはその記録の中から目的の情報を光の速さで見つけ出す「専門の司書」のような存在です。この記事では、なぜ私たちに両方のシステムが必要なのか、そしてどのような場合にElasticsearchを選択すべきなのか、その根本的な違いから具体的な利用シーンまでを深く掘り下げて解説します。

根本的な違い:データ構造の観点から

両システムの最も核心的な違いは、データの保存と検索の方法にあります。それは「B-Treeインデックス」と「転置インデックス(Inverted Index)」の違いです。

RDBMSのB-Treeインデックス

RDBMSは主にB-Tree(平衡木)構造のインデックスを使用します。この構造はデータがソートされた状態を維持し、特定のキー(例:id = 123)を検索するのに非常に効率的です。これは、よく整理された辞書で特定の単語を探すようなものです。データの追加、更新、削除が頻繁に発生してもバランスを保ち、一貫したパフォーマンスを保証するため、オンライントランザクション処理(OLTP)に最適化されています。

しかし、テキスト全体から特定の単語を検索する「全文検索(Full-text Search)」には弱点を抱えています。WHERE content LIKE '%検索語%'のようなクエリはインデックスを有効に活用できず、テーブル全体をスキャン(フルテーブルスキャン)する必要が生じることがあります。これはデータ量が増えるにつれて、パフォーマンスが指数関数的に低下する原因となります。

Elasticsearchの転置インデックス

Elasticsearchは、Apache Luceneライブラリを基盤としており、転置インデックスをその中核技術として使用しています。転置インデックスとは、本の巻末にある「索引」のようなものです。どの単語がどのページ(ドキュメント)に出現するかをあらかじめ整理したリストです。

例えば、以下のような2つのドキュメントがあるとします。

  • ドキュメント1: "The quick brown fox"
  • ドキュメント2: "A quick brown dog"

転置インデックスは、これらのドキュメントを以下のように分析(トークン化)して保存します。

  • quick: [ドキュメント1, ドキュメント2]
  • brown: [ドキュメント1, ドキュメント2]
  • the: [ドキュメント1]
  • fox: [ドキュメント1]
  • a: [ドキュメント2]
  • dog: [ドキュメント2]

ここで「quick」と「brown」を含むドキュメントを探したい場合、それぞれの単語のリストを参照し、その積集合である[ドキュメント1, ドキュメント2]を即座に見つけ出すことができます。テーブル全体を走査する必要は一切ありません。これこそが、Elasticsearchが膨大なテキストデータの中からでも驚異的な検索速度を実現できる秘訣なのです。

Elasticsearchが輝く瞬間:主な利用シーン

このような構造的な違いにより、Elasticsearchは特定のシナリオにおいてRDBMSを圧倒するパフォーマンスと機能を提供します。

1. 圧倒的な全文検索

最も代表的な利用シーンです。ECサイトの商品検索、ブログの投稿検索、企業内の文書検索など、テキストベースの検索が必要とされるほぼすべての場面で活用されています。

  • 柔軟な検索:「青い運動靴」と検索した際に、「水色のランニングシューズ」まで見つけ出すような形態素解析、同義語処理、タイポ(入力ミス)修正などが可能です。これらはRDBMSのLIKE演算子では実装がほぼ不可能です。
  • 関連度スコア(Relevance Score):検索結果に順位を付けることができます。検索語がタイトルに含まれているか、本文中に何回出現するかといった多様な要素を組み合わせて、ユーザーにとって最も関連性の高い結果を優先的に表示します。
  • 豊富なクエリ:単純なキーワード検索だけでなく、フレーズ検索、ブール検索、範囲検索など、複雑な検索要件を容易に処理できます。

2. ログおよびイベントデータの分析

サーバー、アプリケーション、ネットワーク機器などから絶え間なく生成される膨大なログデータをリアルタイムで収集・分析するのに非常に優れています。一般的にELKスタック(Elasticsearch, Logstash, Kibana)またはElastic Stackと呼ばれる組み合わせは、まさにこの目的のためにあります。

  • スキーマレス:定型化されていない様々な形式のログデータを、事前のスキーマ定義なしに柔軟に保存できます。
  • 高速な集計(Aggregation):特定期間のエラー発生回数、IPアドレスごとのリクエスト数、レスポンスタイムの分布など、複雑な統計データをほぼリアルタイムで集計し、可視化できます。これはRDBMSのGROUP BYとは比較にならないほどの速度を誇ります。

3. リアルタイムメトリクス分析とAPM

システムのCPU使用率、メモリ、ディスクI/Oといったメトリクスデータや、アプリケーションパフォーマンス監視(APM)のデータを収集・分析するためにも広く使われています。時系列データ(Time-series data)を効率的に保存し、高速にクエリできる能力がこの用途に適しています。

4. 地理空間データ検索(Geospatial Search)

「現在地から2km以内にあるカフェを探す」といった位置情報ベースのサービスを実装する際に、強力なパフォーマンスを発揮します。緯度経度情報に基づいて特定距離内のデータを検索したり、特定の多角形領域に含まれるデータを探したりといった地理空間クエリを非常に効率的に処理します。

それでもRDBMSが必要な理由

しかし、Elasticsearchは万能ではありません。データの「原本」を安全に保管し、データの一貫性と整合性を保証する必要がある領域では、依然としてRDBMSが絶対的な強者です。

1. ACIDトランザクション

銀行の口座振替、注文処理、決済システムなど、データの整合性が何よりも重要な処理には、ACID(原子性、一貫性、独立性、永続性)を完全に保証するRDBMSが不可欠です。Elasticsearchは分散システムの特性上、「ほぼリアルタイム(Near Real-Time)」で動作し、厳密な意味でのトランザクションはサポートしていません。データがインデックス化されるまでにはわずかな遅延(デフォルトで1秒)が存在する可能性があります。

2. 複雑なリレーションとJOIN

精緻に正規化された複数のテーブルをJOINして複雑な関係を表現し、データを照会する作業はRDBMSの独壇場です。Elasticsearchはnestedオブジェクトやparent-child関係によって限定的なJOINを模倣できますが、RDBMSの柔軟で強力なJOIN性能には及びません。

3. データの「信頼できる唯一の情報源(Source of Truth)」

多くのアーキテクチャでは、データの最終的な原本はRDBMSに保存されます。Elasticsearchは、この原本データを基に検索と分析のための「複製」を構築する補助的なデータストアとして利用されることがほとんどです。データが失われたり不整合が発生したりした場合に、最終的に信頼できる基準となるのはRDBMSです。

最適な組み合わせ:共存するアーキテクチャ

現代的なサービスアーキテクチャは、両システムの長所を最大限に活用する方向で進化しています。

  1. データ書き込み:ユーザーのリクエスト(例:商品登録)は、まずRDBMS(例:PostgreSQL)に保存されます。これにより、データの整合性とトランザクションが保証されます。
  2. データ同期:RDBMSのデータが変更(作成/更新/削除)されると、その変更内容が非同期でElasticsearchに転送され、インデックス化されます。これにはLogstashやDebeziumのようなCDC(Change Data Capture)ツール、あるいはKafkaやRabbitMQのようなメッセージキューが利用できます。
  3. データ読み取り
    • 「マイページ」で自分の注文履歴を正確に照会するなど、トランザクションが重要な情報はRDBMSから直接読み取ります。
    • トップページで商品を検索するような機能は、Elasticsearchにクエリを送り、高速で関連性の高い結果を取得します。

このような構成により、システムの安定性と検索パフォーマンスという二兎を追うことが可能になります。

結論:「どちらか」ではなく「いつ、どのように」の問題

「データベースがあるのに、なぜElasticsearchを使うのか?」という問いへの答えは、今や明確になったはずです。これはどちらか一方を選択する「if」の問題ではなく、それぞれの強みを理解し、適材適所で活用する「when」と「how」の問題なのです。

RDBMSは、データの整合性と安定した保存を担う、システムの信頼できる心臓部です。一方、Elasticsearchは、広大な情報の海の中からユーザーが求めるものを正確かつ迅速に見つけ出す、強力な頭脳のような存在です。この2つを賢く組み合わせることで、私たちは初めて、ユーザーに最高の体験を提供する、堅牢でスケーラブルなシステムを構築できるのです。