🗄️ Databases

Elasticsearch

Elasticsearch

A distributed search and analytics engine. Used for log analysis and full-text search. The core of the ELK stack.

📖 Detailed Explanation

What is Elasticsearch?

Elasticsearch is a distributed open-source search and analytics engine based on Apache Lucene. Through its RESTful API, it can store, search, and analyze large volumes of data in real time, and it is widely used for Full-text Search, log analysis, and time-series data analysis.

Key concepts

  • Index: A logical collection of documents (similar to a table in an RDB)
  • Document: A unit of data in JSON format (similar to a row in an RDB)
  • Field: A key-value pair within a document (similar to a column in an RDB)
  • Shard: A physical unit into which an index is divided; enables horizontal scaling
  • Replica: A copy of a shard; improves high availability and read performance

ELK/Elastic Stack

  • Elasticsearch: Search and analytics engine
  • Logstash: Data collection, transformation, and delivery pipeline
  • Kibana: Data visualization and dashboards
  • Beats: Lightweight data shippers (Filebeat, Metricbeat, etc.)

Key Use Cases

  • Full-text Search: Website search, product search, document search
  • Log/Event Analysis: Application logs, security events
  • APM: Application Performance Monitoring
  • SIEM: Security Information and Event Management
  • Metrics Analysis: Time-series data visualization

Search Methods

  • Match Query: Matches after analyzing the text (morphological analysis applied)
  • Term Query: Searches for exactly matching values (no analysis)
  • Bool Query: Combination of must, should, must_not, and filter
  • Aggregation: Grouping, statistics, bucketing

💻 Code Example

Index Creation and Mapping

HTTP
PUT /products
{
  "settings": {
    "number_of_shards": 3,
    "number_of_replicas": 1,
    "analysis": {
      "analyzer": {
        "korean": {
          "type": "custom",
          "tokenizer": "nori_tokenizer"
        }
      }
    }
  },
  "mappings": {
    "properties": {
      "name": {
        "type": "text",
        "analyzer": "korean",
        "fields": {
          "keyword": { "type": "keyword" }
        }
      },
      "description": { "type": "text", "analyzer": "korean" },
      "price": { "type": "integer" },
      "category": { "type": "keyword" },
      "created_at": { "type": "date" },
      "tags": { "type": "keyword" }
    }
  }
}

Document Indexing and Retrieval

HTTP
# 문서 색인
POST /products/_doc
{
  "name": "맥북 프로 16인치",
  "description": "M3 Pro 칩 탑재 고성능 노트북",
  "price": 3490000,
  "category": "electronics",
  "tags": ["laptop", "apple", "premium"],
  "created_at": "2024-01-15"
}

# ID 지정 색인
PUT /products/_doc/1
{
  "name": "아이패드 프로",
  "description": "M2 칩, Liquid Retina XDR 디스플레이",
  "price": 1729000,
  "category": "electronics",
  "tags": ["tablet", "apple"]
}

# 문서 조회
GET /products/_doc/1

Search Query

HTTP
# Match Query (전문 검색)
GET /products/_search
{
  "query": {
    "match": {
      "description": "고성능 노트북"
    }
  }
}

# Bool Query (복합 조건)
GET /products/_search
{
  "query": {
    "bool": {
      "must": [
        { "match": { "description": "노트북" } }
      ],
      "filter": [
        { "term": { "category": "electronics" } },
        { "range": { "price": { "gte": 1000000, "lte": 3000000 } } }
      ],
      "should": [
        { "term": { "tags": "premium" } }
      ],
      "minimum_should_match": 1
    }
  },
  "sort": [
    { "price": "asc" },
    "_score"
  ],
  "from": 0,
  "size": 10
}

Aggregation

HTTP
GET /products/_search
{
  "size": 0,
  "aggs": {
    "category_stats": {
      "terms": {
        "field": "category",
        "size": 10
      },
      "aggs": {
        "avg_price": { "avg": { "field": "price" } },
        "max_price": { "max": { "field": "price" } },
        "price_ranges": {
          "range": {
            "field": "price",
            "ranges": [
              { "to": 1000000 },
              { "from": 1000000, "to": 2000000 },
              { "from": 2000000 }
            ]
          }
        }
      }
    },
    "daily_sales": {
      "date_histogram": {
        "field": "created_at",
        "calendar_interval": "day"
      }
    }
  }
}

Python (elasticsearch-py)

Python
from elasticsearch import Elasticsearch

es = Elasticsearch(['http://localhost:9200'])

# 문서 색인
doc = {
    'name': '맥북 에어',
    'price': 1690000,
    'category': 'electronics'
}
es.index(index='products', id=1, document=doc)

# 검색
query = {
    'bool': {
        'must': [{'match': {'name': '맥북'}}],
        'filter': [{'range': {'price': {'lte': 2000000}}}]
    }
}
results = es.search(index='products', query=query)

for hit in results['hits']['hits']:
    print(f"Score: {hit['_score']}, Name: {hit['_source']['name']}")

# Bulk 색인 (대량 데이터)
from elasticsearch.helpers import bulk

actions = [
    {'_index': 'products', '_id': i, '_source': {'name': f'Product {i}'}}
    for i in range(1000)
]
bulk(es, actions)

💬 Real-world conversation examples

Backend developer
"I need a product search feature. Can you make it show '노트북' (laptop) when someone types 'ㄴㅌㅂ'?"
Search Engineer
"That's initial-consonant search. Set up the Korean morphological analyzer (Nori) and add an initial-consonant conversion filter. If you build a custom analyzer in Elasticsearch and apply it, you can even implement autocomplete."
DevOps engineer
"The ES cluster's disk usage has exceeded 90%. What should we do?"
DBA
"First, set up a deletion policy for old indices with ILM. Then add nodes or adjust the number of shards to rebalance the data. Once it goes over 95%, it switches to read-only mode, and that's a big problem."
Frontend Developer
"Why do products that look unrelated show up first in the search results?"
Search Engineer
"It's because of the default TF-IDF-based scoring. You need to use function_score to reflect business logic such as popularity and recency and boost the scores. Or applying a Learning to Rank model is another option."

⚠️ Cautions

⚠️ Do Not Use as a Primary Data Store
Elasticsearch is a search engine, not a Primary Database. Because data loss is possible, store the original data in a separate DB and use ES only as a search index.
⚠️ Mappings Cannot Be Changed
Field types cannot be changed after an index is created. If a schema change is needed, you must create a new index and Reindex. Designing the initial mapping is extremely important.
⚠️ Memory Management
Set the JVM heap memory to no more than 50% of total RAM, with a maximum of 32GB. The rest must be left for the file system cache for good search performance. If OOM occurs, the node goes down.
⚠️ Shard Planning
Too many shards increase cluster overhead; too few make scaling difficult. The recommendation is 20-50GB per shard and no more than 600-800 shards per node. They cannot be changed after creation.

🔗 Related Terms

📚 Learn More