[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6QYWMZFHW16ZATT0F24X3DC":3,"skill-same:01M6QYWMZFHW16ZATT0F24X3DC":67},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":39,"linkOnly":40,"markdownContent":41,"markdownBody":42,"frontMatter":43,"refName":44,"commitSha":45,"skillDirectory":46,"forksCount":47,"repositoryHtmlUrl":48,"repositoryHomepageUrl":49,"ownerHtmlUrl":50,"ownerBlogUrl":6,"ownerDescription":51,"updatedAt":52,"install":53,"resources":66},"01M6QYWMZFHW16ZATT0F24X3DC","lucene-internals",null,"Use this skill when diagnosing ES performance at the segment\u002FLucene level, interpreting _profile or _explain output, understanding scoring internals, tuning merge policies, or reasoning about why an ES setting affects search latency. Covers inverted index structure, segment lifecycle, codec system, scoring models, query execution pipeline, and OS-level performance factors.","Dokkabei97\u002Fdokkabei-harness","Dokkabei97","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F69792585?v=4","01M6QYPVTYK6CGF609W541QNSD","JangMK","01M6QYPVYXBP1GRYHZ7ZABCZC6",1,"Apache-2.0","https:\u002F\u002Fgithub.com\u002FDokkabei97\u002Fdokkabei-harness\u002Fblob\u002Fmain\u002Farchive\u002Fcomponents\u002Fsearch\u002Fskills\u002Flucene-internals\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38],"lucene internals","es","when","at","segment","os","latency","structure","scoring","query","performance","use","system","why","lifecycle","tuning","execution","pipeline","search","merge","2026-11-10 10:12:30",false,"---\nname: lucene-internals\ndescription: Use this skill when diagnosing ES performance at the segment\u002FLucene level, interpreting _profile or _explain output, understanding scoring internals, tuning merge policies, or reasoning about why an ES setting affects search latency. Covers inverted index structure, segment lifecycle, codec system, scoring models, query execution pipeline, and OS-level performance factors.\n---\n\n# Lucene Internals for Elasticsearch Engineers\n\nElasticsearch의 기반인 Apache Lucene의 내부 구조를 다루는 가이드입니다. ES 성능 문제의 근본 원인은 대부분 Lucene 레벨에 있습니다.\n\n## When to Activate\n\n- `_profile` API 출력에서 `build_scorer`, `advance`, `next_doc` 시간이 비정상적일 때\n- `_explain` API 출력에서 IDF\u002FTF\u002Fnorms 값이 예상과 다를 때\n- 세그먼트 수가 증가하거나 force merge 결정이 필요할 때\n- `refresh_interval`, translog, flush 설정 튜닝 시\n- `doc_values` vs `fielddata` 선택이 필요할 때\n- 숫자\u002Fgeo 쿼리 성능 이슈 (BKD tree)\n- OS page cache 사이징 또는 heap vs off-heap 메모리 결정 시\n- `index.sort.*` 설정으로 검색 시 early termination 구현 시\n\n## 1. Architecture Fundamentals -- ES Shard = Lucene Index\n\n### ES-Lucene Concept Mapping\n\n하나의 ES shard는 하나의 Lucene `IndexWriter`\u002F`IndexReader` 인스턴스입니다. ES의 모든 개념은 Lucene 개념 위에 매핑됩니다.\n\n| ES Concept | Lucene Concept | 설명 |\n|------------|---------------|------|\n| Shard | `IndexWriter` + `IndexReader` | 하나의 독립적인 Lucene 인덱스 |\n| Document | `Document` | 필드의 컬렉션 |\n| `text` field | `TextField` | 분석(tokenize)되어 inverted index에 저장 |\n| `keyword` field | `StringField` | 분석 없이 단일 토큰으로 저장 |\n| `doc_values` | `DocValuesField` | 정렬\u002F집계용 column-oriented 저장소 |\n| `_source` | `StoredField` | 원본 JSON을 그대로 저장 |\n| Refresh | `DirectoryReader.openIfChanged()` | 새 세그먼트를 검색 가능하게 만듦 |\n| Flush | `IndexWriter.flush()` | 인메모리 버퍼를 세그먼트로 디스크에 기록 |\n| Commit | `IndexWriter.commit()` | fsync + commit point 기록 (durability) |\n| Merge | `MergePolicy` + `MergeScheduler` | 여러 세그먼트를 하나로 합침 |\n\n### Inverted Index 구조\n\nLucene의 핵심 자료구조입니다. Term Dictionary는 FST(Finite State Transducer)로 구현되어 메모리 효율적인 prefix 탐색을 지원합니다.\n\n```\nInverted Index (하나의 필드에 대해)\n==================================\n\nTerm Dictionary (FST)          Postings List\n-----------------------        ----------------------------------------\n  \"검색\"  ─────────────────→  DocID: [2, 15, 42, 108]\n                               Freq:  [1,  3,  1,   2]\n                               Pos:   [(0), (0,5,12), (3), (0,7)]\n\n  \"엔진\"  ─────────────────→  DocID: [15, 42, 200]\n                               Freq:  [1,   2,   1]\n                               Pos:   [(1), (1,8), (0)]\n\n  \"최적화\" ────────────────→  DocID: [2, 200, 305]\n                               Freq:  [1,   1,   4]\n                               Pos:   [(2), (1), (0,3,7,11)]\n\nFST (Finite State Transducer)\n─────────────────────────────\n  - Term → Postings 파일 오프셋 매핑\n  - 메모리에 상주 (off-heap via mmap)\n  - 공통 prefix\u002Fsuffix 공유로 메모리 절약\n  - O(len(term)) 탐색 시간\n\nPostings List 구성 요소\n─────────────────────────\n  .doc  → DocID + Term Frequency (항상 존재)\n  .pos  → Position + Offset (index_options에 따라)\n  .pay  → Payload (사용자 정의 바이트)\n```\n\n### Doc Values Column Store\n\n`doc_values`는 정렬, 집계, scripting에 사용되는 column-oriented 저장소입니다.\n\n```\nDoc Values 레이아웃 (예: \"price\" 필드)\n=======================================\n\nRow-Oriented (stored fields)     Column-Oriented (doc_values)\n─────────────────────────────    ─────────────────────────────\nDoc0: {name:\"A\", price:1000}     price 컬럼:\nDoc1: {name:\"B\", price:2500}       Doc0 → 1000\nDoc2: {name:\"C\", price:800}        Doc1 → 2500\nDoc3: {name:\"D\", price:3200}       Doc2 →  800\n                                   Doc3 → 3200\n                                   (디스크에 연속 배치, mmap으로 접근)\n\nDocValues 타입:\n  NUMERIC    → long\u002Fdouble 값 (price, timestamp)\n  BINARY     → byte[] (해시, 임의 바이너리)\n  SORTED     → ordinal 기반 사전순 (keyword)\n  SORTED_SET → 다중 값 ordinal (tags)\n  SORTED_NUMERIC → 다중 숫자 값\n```\n\n### doc_values vs stored fields vs fielddata\n\n| 기준 | doc_values | stored fields | fielddata |\n|------|-----------|---------------|-----------|\n| **접근 패턴** | column-oriented (특정 필드, 모든 문서) | row-oriented (특정 문서, 모든 필드) | column-oriented (heap) |\n| **메커니즘** | 디스크 + mmap (off-heap) | 디스크에서 읽기 (decompress) | heap에 역인덱스 반전 로드 |\n| **Heap 비용** | 없음 (OS page cache 사용) | 없음 | 매우 높음 (OOM 위험) |\n| **디스크 레이아웃** | 세그먼트별 `.dvd`\u002F`.dvm` 파일 | `.fdt`\u002F`.fdx` 파일 | 디스크 없음 (런타임 생성) |\n| **용도** | 정렬, 집계, scripting | `_source` 반환, highlight | text 필드 집계 (비권장) |\n| **기본 활성화** | keyword\u002Fnumeric\u002Fdate\u002Fetc 자동 | `_source` 자동 | 비활성화 (명시적 활성화 필요) |\n\n**원칙**: `fielddata`는 text 필드에서 집계가 불가피할 때만 사용. 대부분의 경우 `keyword` sub-field + `doc_values`로 대체.\n\n### Segment 기반 아키텍처\n\nLucene 인덱스는 불변(immutable) 세그먼트의 집합입니다. 삭제는 물리 삭제가 아닌 비트맵 마킹이며, merge 시 실제 제거됩니다.\n\n```\nLucene Index (= 1 ES Shard)\n════════════════════════════════════════════════════════════\n\n  In-Memory Buffer (IndexWriter)\n  ┌─────────────────────────────┐\n  │  새로 인덱싱된 문서들         │ ──── Flush ────┐\n  │  (아직 검색 불가)             │                 │\n  └─────────────────────────────┘                 ▼\n                                          ┌──────────────┐\n  Searchable Segments                     │  Segment_N   │\n  ┌──────────┐ ┌──────────┐ ┌──────────┐ │  (최신)       │\n  │ Segment_0│ │ Segment_1│ │ Segment_2│ └──────────────┘\n  │ 50K docs │ │ 30K docs │ │ 10K docs │\n  │ .si .doc │ │ .si .doc │ │ .si .doc │\n  │ .pos .dvd│ │ .pos .dvd│ │ .pos .dvd│\n  │ .tim .tip│ │ .tim .tip│ │ .tim .tip│\n  └──────────┘ └──────────┘ └──────────┘\n       │              │            │\n       └──────────────┴────────────┘\n                    │\n                  Merge ──→  ┌──────────────────┐\n                             │ Merged_Segment    │\n                             │ 90K docs          │\n                             │ (삭제 문서 제거됨)  │\n                             └──────────────────┘\n\n  Delete Bitmap (per segment)\n  ┌─────────────────────────────────────────┐\n  │ Segment_0: [0,0,1,0,0,0,1,0,...] (bit) │  ← doc 2, 6 삭제됨\n  │ Segment_1: [0,0,0,0,...] (bit)          │  ← 삭제 없음\n  └─────────────────────────────────────────┘\n\n  segments_N 파일 (commit point)\n  ┌───────────────────────────────────┐\n  │ generation: 5                     │\n  │ segments: [Seg_0, Seg_1, Seg_2]   │\n  │ userData: {translog_uuid: \"...\"}  │\n  └───────────────────────────────────┘\n```\n\n### Codec 시스템\n\n각 세그먼트의 데이터 구조는 Codec에 의해 결정됩니다. ES 8.x는 Lucene 9.x 코덱을 사용합니다.\n\n| Codec Format | 파일 확장자 | 역할 |\n|-------------|-----------|------|\n| `Lucene99PostingsFormat` | `.doc`, `.pos`, `.pay` | Postings list (DocID, Freq, Position, Payload) |\n| `Lucene90DocValuesFormat` | `.dvd`, `.dvm` | Doc values (정렬\u002F집계용 column store) |\n| `Lucene90StoredFieldsFormat` | `.fdt`, `.fdx`, `.fdm` | Stored fields (`_source` 포함) |\n| `Lucene90NormsFormat` | `.nvd`, `.nvm` | Norms (필드 길이 인코딩 값) |\n| `Lucene90TermVectorsFormat` | `.tvd`, `.tvx`, `.tvm` | Term vectors (문서별 term 정보) |\n| `Lucene90PointsFormat` | `.kdd`, `.kdi`, `.kdm` | BKD tree (숫자\u002Fgeo\u002FIP 범위 쿼리) |\n| `Lucene90SegmentInfoFormat` | `.si` | 세그먼트 메타데이터 |\n| `Lucene90LiveDocsFormat` | `.liv` | 삭제 비트맵 |\n\n### Directory 추상화와 Page Cache\n\n| Directory 구현 | 메커니즘 | 특성 |\n|---------------|---------|------|\n| `MMapDirectory` | `mmap()` 시스템 콜 | 파일을 가상 메모리에 매핑. OS page cache 활용. **ES 기본값** |\n| `NIOFSDirectory` | `FileChannel.read()` | Java NIO 기반. mmap보다 느리지만 주소 공간 제한 없음 |\n\n**Page Cache가 중요한 이유**: Lucene은 파일을 `mmap`으로 열고, 실제 I\u002FO는 OS page cache에 위임합니다. 충분한 page cache가 없으면 모든 쿼리가 디스크 I\u002FO를 발생시켜 지연 시간이 급증합니다. JVM heap을 물리 메모리의 50% 이하로 설정하고 나머지를 page cache로 남겨야 하는 이유입니다.\n\n## 2. Scoring & Similarity Deep Dive\n\n### BM25 공식 분해\n\nES 8.x의 기본 유사도 함수입니다. 각 term-document 쌍에 대해 다음을 계산합니다:\n\n```\nscore(q, d) = SUM_over_t_in_q [\n    IDF(t) * ( tf(t,d) * (k1 + 1) ) \u002F ( tf(t,d) + k1 * (1 - b + b * dl\u002Favgdl) )\n]\n\n여기서:\n  IDF(t)  = ln(1 + (N - df(t) + 0.5) \u002F (df(t) + 0.5))\n  tf(t,d) = freq(t,d) \u002F (freq(t,d) + k1 * (1 - b + b * dl\u002Favgdl))   -- BM25 saturation (ES 8.x 기본, _explain의 tf 항과 일치)\n            ※ sqrt(freq)는 구식 ClassicSimilarity(TF-IDF) 방식이며 BM25Similarity가 아님\n  dl      = 문서 d의 필드 길이 (토큰 수, norms로 인코딩)\n  avgdl   = 전체 문서의 평균 필드 길이\n  N       = 전체 문서 수 (해당 shard 기준)\n  df(t)   = term t를 포함하는 문서 수\n  k1      = 1.2 (기본값, TF saturation 제어)\n  b       = 0.75 (기본값, 문서 길이 정규화 제어)\n```\n\n### 스코어링 구성 요소 상세\n\n| Component | 소스 | 저장 위치 | 설명 |\n|-----------|------|----------|------|\n| `tf` (Term Frequency) | Postings list `.doc` 파일 | freq 값에서 계산 | 문서 내 term 출현 빈도. BM25는 saturation 식 `freq\u002F(freq+k1*(1-b+b*dl\u002Favgdl))` 적용 (`sqrt(freq)`는 구식 ClassicSimilarity) |\n| `df` (Document Frequency) | Term Dictionary 메타데이터 | 세그먼트별 `.tip` 파일 | term을 포함하는 문서 수 |\n| `dl` (Document Length) | Norms | `.nvd` 파일 | 필드의 토큰 수. `SmallFloat`로 1바이트 인코딩 |\n| `avgdl` | 세그먼트 메타데이터에서 계산 | `sumTotalTermFreq \u002F docCount` | shard 전체의 평균 필드 길이 |\n| `N` (docCount) | 세그먼트 메타데이터 | `SegmentInfo` | 해당 shard의 전체 문서 수 (삭제 포함 주의) |\n| `k1` | Similarity 설정 | 인덱스 settings | TF 포화 곡선 제어. 높을수록 TF 영향 증가 |\n| `b` | Similarity 설정 | 인덱스 settings | 문서 길이 보정. 0이면 길이 무시, 1이면 완전 정규화 |\n\n### Norms: 1바이트 필드 길이 인코딩\n\n`dl`(필드 길이)은 norms로 인코딩됩니다. `SmallFloat.intToByte4()`를 사용하여 정수를 1바이트(256가지 값)로 압축합니다.\n\n```\nNorms 인코딩 예시:\n  필드 길이 1   → norms byte: 100  (정확)\n  필드 길이 2   → norms byte: 120  (정확)\n  필드 길이 3   → norms byte: 126  (정확)\n  필드 길이 5   → norms byte: 122  (근사값)\n  필드 길이 10  → norms byte: 116  (근사값)\n  필드 길이 100 → norms byte: 80   (근사값, 정밀도 ↓)\n  필드 길이 500 → norms byte: 64   (근사값, 정밀도 ↓↓)\n\n주의:\n  - 256가지 값만 표현 가능하므로 긴 필드에서는 정밀도 손실\n  - 필드 길이 1-5 사이에서는 정확하지만, 100 이상은 근사치\n  - norms 비활성화 시 (\"norms\": false) dl=1로 처리되어 길이 정규화 불가\n  - keyword, _id 등은 기본적으로 norms 비활성화\n```\n\n### IDF per-shard 문제와 dfs_query_then_fetch\n\n기본 `query_then_fetch`에서 IDF는 shard-local로 계산됩니다. 문서 분포가 불균등하면 동일 term에 대해 shard마다 다른 IDF를 반환합니다.\n\n```json\n\u002F\u002F 문제 상황: shard 0에 \"검색\" 포함 문서 10,000개, shard 1에 5개\n\u002F\u002F → shard 1에서 \"검색\"의 IDF가 매우 높아져 비정상적인 점수\n\n\u002F\u002F 해결: dfs_query_then_fetch (2-pass 방식)\nGET \u002Fproducts\u002F_search?search_type=dfs_query_then_fetch\n{\n  \"query\": { \"match\": { \"title\": \"검색 엔진\" } }\n}\n\u002F\u002F Pass 1: 모든 shard에서 df, docCount 수집\n\u002F\u002F Pass 2: 글로벌 통계로 스코어링\n\u002F\u002F 트레이드오프: 추가 라운드트립 발생. 대규모 클러스터에서는 오버헤드 주의\n```\n\n> ⚠️ **글로벌 IDF는 `_explain\u002F{id}`로 검증 불가**: `GET \u002Fidx\u002F_explain\u002F{id}`은 `search_type`을 무시한다(issue #2612). `dfs_query_then_fetch`를 줘도 단건 `_explain`은 여전히 per-shard IDF만 보여줘 실제 검색 점수와 어긋난다. dfs 글로벌 IDF·rescore가 반영된 점수는 `_search { \"explain\": true }`로만 확인하라.\n\n### Custom Similarity 설정\n\n```json\n\u002F\u002F ES 인덱스 설정에서 similarity 커스텀\nPUT \u002Fproducts\n{\n  \"settings\": {\n    \"index\": {\n      \"similarity\": {\n        \"custom_bm25\": {\n          \"type\": \"BM25\",\n          \"k1\": \"1.0\",\n          \"b\": \"0.3\",\n          \"discount_overlaps\": \"true\"\n        }\n      }\n    }\n  },\n  \"mappings\": {\n    \"properties\": {\n      \"title\": {\n        \"type\": \"text\",\n        \"similarity\": \"custom_bm25\"\n      }\n    }\n  }\n}\n\n\u002F\u002F Scripted Similarity (고급)\nPUT \u002Fproducts\n{\n  \"settings\": {\n    \"index\": {\n      \"similarity\": {\n        \"scripted_tfidf\": {\n          \"type\": \"scripted\",\n          \"script\": {\n            \"source\": \"double tf = Math.sqrt(doc.freq); double idf = Math.log((field.docCount+1.0)\u002F(term.docFreq+1.0)) + 1.0; double norm = 1\u002FMath.sqrt(doc.length); return query.boost * tf * idf * norm;\"\n          }\n        }\n      }\n    }\n  }\n}\n```\n\n### Alternative Similarity 모델\n\n| Similarity | 설명 | 적합 케이스 |\n|-----------|------|-----------|\n| `BM25` (기본) | Okapi BM25, TF saturation + 길이 정규화 | 대부분의 검색 |\n| `DFR` | Divergence From Randomness | 학술 검색, 긴 문서 |\n| `DFI` | Divergence From Independence | 짧은 문서, 키워드 매칭 |\n| `IB` | Information-Based Model | 자연어 처리 연구용 |\n| `LMDirichlet` | Language Model, Dirichlet smoothing | 짧은 쿼리, 긴 문서 |\n| `LMJelinekMercer` | Language Model, Jelinek-Mercer smoothing | 긴 쿼리 |\n| `scripted` | 사용자 정의 스크립트 | 완전 커스텀 스코어링 |\n| `boolean` | TF\u002FIDF 무시, 매칭 여부만 | filter-like 스코어링 |\n\n### _explain API 출력 읽기\n\n```json\n\u002F\u002F 요청\nGET \u002Fproducts\u002F_explain\u002F42\n{\n  \"query\": {\n    \"bool\": {\n      \"must\": [\n        { \"match\": { \"title\": \"무선 이어폰\" } }\n      ],\n      \"filter\": [\n        { \"term\": { \"status\": \"active\" } }\n      ]\n    }\n  }\n}\n\n\u002F\u002F 응답 해석\n{\n  \"matched\": true,\n  \"_explanation\": {\n    \"value\": 8.234,                          \u002F\u002F ← 최종 스코어\n    \"description\": \"sum of:\",\n    \"details\": [\n      {\n        \"value\": 8.234,\n        \"description\": \"sum of:\",            \u002F\u002F ← bool.must의 합\n        \"details\": [\n          {\n            \"value\": 4.512,\n            \"description\": \"weight(title:무선 in 42) [PerFieldSimilarity]\",\n            \"details\": [\n              {\n                \"value\": 4.512,\n                \"description\": \"score(freq=1.0), computed as boost * idf * tf\",\n                \"details\": [\n                  { \"value\": 2.2, \"description\": \"boost\" },\n                  {\n                    \"value\": 3.145,          \u002F\u002F ← IDF 값\n                    \"description\": \"idf, computed as log(1 + (N - n + 0.5) \u002F (n + 0.5))\",\n                    \"details\": [\n                      { \"value\": 50000, \"description\": \"N, total number of documents\" },\n                      { \"value\": 1200, \"description\": \"n, number of documents containing term\" }\n                    ]\n                  },\n                  {\n                    \"value\": 0.651,          \u002F\u002F ← TF-Norm 값\n                    \"description\": \"tf, computed as freq \u002F (freq + k1 * (1 - b + b * dl \u002F avgdl))\",\n                    \"details\": [\n                      { \"value\": 1.0, \"description\": \"freq, occurrences of term within document\" },\n                      { \"value\": 1.2, \"description\": \"k1\" },\n                      { \"value\": 0.75, \"description\": \"b\" },\n                      { \"value\": 3.0, \"description\": \"dl, length of field\" },\n                      { \"value\": 5.2, \"description\": \"avgdl, average length of field\" }\n                    ]\n                  }\n                ]\n              }\n            ]\n          },\n          {\n            \"value\": 3.722,\n            \"description\": \"weight(title:이어폰 in 42) [PerFieldSimilarity]\"\n            \u002F\u002F ... 동일 구조\n          }\n        ]\n      }\n      \u002F\u002F filter 절은 스코어에 기여하지 않으므로 여기 나타나지 않음\n    ]\n  }\n}\n```\n\n**_explain 읽기 체크리스트**:\n- `N` (total documents)이 예상 shard 크기와 일치하는지 확인\n- `n` (documents containing term)이 합리적인지 확인 (너무 크면 IDF 낮음)\n- `dl` (document length)이 해당 문서의 실제 토큰 수와 일치하는지 확인\n- `freq`가 해당 문서 내 term 출현 수와 일치하는지 확인\n- filter 절은 score에 나타나지 않음 (0.0 기여)\n\n#### _termvectors로 색인된 실제 토큰 확인\n\n`_explain`이 \"왜 이 점수인가\"를 보여준다면, `_termvectors`는 \"이 문서에 실제로 어떤 토큰이 색인되었는가\"를 보여줍니다. 코덱 차원에서는 `.tvd`\u002F`.tvx`\u002F`.tvm`(`Lucene90TermVectorsFormat`, 위 Codec 표 참조)에 저장된 문서별 term 정보를 읽어옵니다.\n\n```json\n\u002F\u002F 요청: 색인된 토큰 + 통계\nGET \u002Fproducts\u002F_termvectors\u002F42\n{\n  \"fields\": [\"title\"],\n  \"term_statistics\": true,\n  \"field_statistics\": true\n}\n\n\u002F\u002F 응답 구조 (루트는 복수형 term_vectors)\n{\n  \"_id\": \"42\",\n  \"found\": true,\n  \"term_vectors\": {\n    \"title\": {\n      \"field_statistics\": {\n        \"sum_doc_freq\": 120000,\n        \"doc_count\": 50000,\n        \"sum_ttf\": 180000\n      },\n      \"terms\": {                          \u002F\u002F ← 키 = 색인된 실제 토큰 (분석기 통과 후)\n        \"무선\": {\n          \"doc_freq\": 1200,               \u002F\u002F ← _explain idf의 n과 동일 출처\n          \"ttf\": 1500,\n          \"term_freq\": 1,\n          \"tokens\": [\n            { \"position\": 0, \"start_offset\": 0, \"end_offset\": 2 }\n          ]\n        },\n        \"이어폰\": {\n          \"doc_freq\": 800,\n          \"term_freq\": 1,\n          \"tokens\": [\n            { \"position\": 1, \"start_offset\": 3, \"end_offset\": 6 }\n          ]\n        }\n      }\n    }\n  }\n}\n```\n\n**교차검증 포인트**:\n- `terms` 맵의 **키가 색인된 실제 토큰**입니다. `_analyze`(search_analyzer)로 얻은 쿼리 토큰과 교집합이 비면 분석기 불일치가 확정됩니다.\n- `term_statistics: true`의 `doc_freq`는 `_explain` idf 설명의 `n`(documents containing term)과 **동일한 출처**입니다. 두 값이 다르면 샤드\u002F세그먼트 경계 또는 통계 갱신 시점 차이를 의심합니다.\n\n**on-the-fly drift 함정**:\n- 매핑이 `term_vector: no`(기본값)이면 색인 시점에 term vector를 저장하지 않으므로, `_termvectors`는 `_source`를 **현재 index_analyzer로 즉석(on-the-fly) 재분석**해 토큰을 만듭니다.\n- 따라서 분석기를 바꾼 뒤 reindex를 누락하면, 실제 색인된(과거 분석기) 토큰과 on-the-fly(현재 분석기) 결과가 어긋나도 `_termvectors`만으로는 drift를 탐지하지 못합니다.\n- 진짜 색인 시점 토큰을 보려면 매핑을 `term_vector: with_positions_offsets`로 두거나(단, 소급 적용 불가 — 설정 이후 색인분부터), reindex로 교차검증해야 합니다.\n\n**offset 단위**: `start_offset`\u002F`end_offset`은 UTF-16 code unit 기준입니다. 한글은 BMP 영역이라 1글자=1단위로 안전하지만, 이모지\u002F보충문자(surrogate pair)는 1글자=2단위로 계산됩니다.\n\n> **[정정] `dfs` 파라미터 금지**: `_termvectors`에 `dfs` 파라미터는 **존재하지 않습니다**(ES 5.0, PR#16452에서 제거됨 — 8.x에 없음). 멀티샤드 간 통계(doc_freq) 편차를 정확히 보려면 단일 샤드 테스트 인덱스를 쓰거나 클라이언트에서 전역 통계를 재계산하십시오. artificial doc은 routing 미지정 시 무작위 샤드에 매핑되어 통계가 부정확해질 수 있습니다.\n\n#### _profile 5대 섹션과 timeout 원인 분리 결정 트리\n\n`_profile`(요청 본문에 `\"profile\": true`)은 **shard-level** 실행을 5개 섹션으로 분해합니다. `profile.shards[]` 배열의 각 샤드마다 다음 키가 (조건부로) 존재합니다.\n\n| 섹션 | 존재 조건 | 의미 |\n|------|----------|------|\n| `searches[].query[]` | 항상 | Lucene Query 실행 트리 (가장 흔한 주범) |\n| `searches[].rewrite_time` | 항상 | Query rewrite에 든 시간(nanos) |\n| `searches[].collector[]` | 항상 | 결과 수집 단계(top hits\u002Fcount 등) |\n| `aggregations[]` | aggs가 있을 때만 | 집계 실행 트리 (aggs 없으면 **이 섹션 자체가 부재**) |\n| `fetch` | 항상 | hit 본문 로딩 단계 |\n\n**1차 절단 — '가장 느린 단일 샤드' 기준**: 샤드별 시간을 단순 합산하면 안 됩니다(병렬 실행이므로 wall-clock과 무관). 가장 느린 단일 샤드 하나를 골라 그 안에서 `Σquery time` vs `collector 루트 time` vs `Σaggregations time` vs `fetch.breakdown 합`을 비교해 주범 단계를 특정합니다.\n\n**query breakdown 9필드** (각각 `*_count` 동반):\n\n| 필드 | 호출 빈도 | 의미 |\n|------|----------|------|\n| `create_weight` | 세그먼트 무관 1회 | Weight 객체 생성(쿼리 정규화) |\n| `build_scorer` | 세그먼트마다 | Scorer 구축 (높으면 term 수\u002F세그먼트 수 과다) |\n| `next_doc` | 매칭 문서 순회 | 다음 매칭 docID로 이동 |\n| `advance` | skip 시 | 특정 docID로 점프(conjunction) |\n| `match` | two-phase | 2단계 확인(phrase 등) |\n| `score` | 스코어링 시 | 점수 계산 |\n| `shallow_advance` | block-max WAND | 블록 단위 advance |\n| `compute_max_score` | block-max WAND | 블록 최대 점수 산출 |\n| `set_min_competitive_score` | top-k 가지치기 | 경쟁 컷 갱신 |\n\n**aggregation breakdown 6필드**: `initialize` \u002F `build_leaf_collector` \u002F `collect`(+`collect_count`) \u002F `post_collection` \u002F `build_aggregation` \u002F `reduce`(= reserved, **항상 0**).\n\n**collector reason 사전**: `search_top_hits` \u002F `search_count` \u002F `search_query_phase` \u002F `search_terminate_after_count` \u002F `search_timeout` \u002F `aggregation` \u002F `global_aggregation`. ⚠️ collector time은 query time과 **시간대가 중복**되므로 두 값을 합산하지 마십시오.\n\n**fetch.breakdown 실제 필드**: `next_reader`\u002F`next_reader_count`, `load_stored_fields`\u002F`load_stored_fields_count`, `load_source`\u002F`load_source_count`. `load_source`가 크면 거대 `_source` 로딩이 병목 — `_source` 필터링\u002F`stored_fields` 검토.\n\n**took vs Σtime_in_nanos 갭**: 응답의 `took`이 profile의 모든 `time_in_nanos` 합보다 **현저히 크면**(took >> 합) 병목이 '단계 밖'에 있다는 신호입니다 — coordinating 노드 머지, 네트워크, rewrite\u002Fglobal ordinals lazy 빌드 등 profile이 측정하지 못하는 영역.\n\n**profile이 측정하지 못하는 항목**: coordinating 머지·네트워크 전송, rewrite\u002Fglobal ordinals 빌드(과소계상 또는 누락).\n\n> **[함정] profiling 오버헤드**: `_profile`은 WAND\u002Fblock-max 등 Lucene 최적화를 **비활성화**하고 모든 단계를 계측하므로 절대 nanos가 부풀려집니다(공식 문서 'non-negligible overhead'). 따라서 (1) 단계 **간 상대 비교** 전용으로만 쓰고 절대 시간으로 SLA를 판단하지 말 것, (2) 프로덕션에서 기본 활성화 금지.\n\n**global ordinals — '첫 쿼리만 느림' 신호**: 고-카디널리티 keyword 필드(예: nori 분석 텍스트와 별개로 운영하는 `brand`\u002F`category` keyword facet)의 terms 집계는 global ordinals를 필요로 합니다.\n- 기본(lazy): 첫 집계 쿼리의 `collect` 단계에 빌드 비용이 **과소계상**되거나 `took` 갭으로만 드러나, \"첫 쿼리만 느리고 이후엔 빠름\" 패턴을 만듭니다.\n- `eager_global_ordinals: true`로 두면 빌드가 refresh-time으로 이동해 쿼리 시점 profile에서 **완전히 사라집니다**(대신 색인\u002Frefresh 비용 증가). 첫 쿼리 지연이 반복 재현되면 이 설정을 검토합니다.\n\n> 증상 기반 진입은 search-diagnostics 스킬 참조\n\n## 3. Segment Lifecycle -- Refresh, Flush, Merge, Commit\n\n### Write Path 타임라인\n\n```\nIndex Request 도착\n       │\n       ▼\n  ┌──────────────────┐\n  │  Translog 기록    │  ← 내구성 보장 (fsync 또는 async)\n  │  (WAL 역할)       │\n  └────────┬─────────┘\n           │\n           ▼\n  ┌──────────────────┐\n  │  In-Memory Buffer │  ← IndexWriter의 DWPT\n  │  (인덱싱 + 분석)   │     (DocumentsWriterPerThread)\n  └────────┬─────────┘\n           │\n     Refresh (기본 1초)\n           │\n           ▼\n  ┌──────────────────┐\n  │  New Segment      │  ← 디스크에 기록되지만 fsync 안 됨\n  │  (검색 가능!)      │     DirectoryReader.openIfChanged()\n  └────────┬─────────┘\n           │\n     Flush \u002F Commit\n           │\n           ▼\n  ┌──────────────────┐\n  │  Committed Seg    │  ← fsync 완료, segments_N에 기록\n  │  (내구성 보장)     │     translog 삭제 가능\n  └────────┬─────────┘\n           │\n     Merge (비동기, MergePolicy가 결정)\n           │\n           ▼\n  ┌──────────────────┐\n  │  Merged Segment   │  ← 여러 세그먼트 합병, 삭제 문서 제거\n  │  (최적화된 상태)   │     구 세그먼트 파일 삭제\n  └──────────────────┘\n```\n\n### Refresh vs Flush vs Commit\n\n| 작업 | 내부 동작 | 트리거 | 검색 가능? | 내구성 보장? |\n|------|----------|--------|-----------|------------|\n| **Refresh** | `DirectoryReader.openIfChanged()` 호출, 새 세그먼트를 reader에 노출 | `refresh_interval` (기본 1초), 수동 `_refresh` | O | X (fsync 없음) |\n| **Flush** | 인메모리 버퍼 → 세그먼트 파일 기록, translog는 유지 | 버퍼 크기 초과, 수동 `_flush` | O (refresh 포함) | 부분적 (translog로 복구) |\n| **Commit** | `IndexWriter.commit()`, fsync + `segments_N` 기록, translog 정리 | translog 크기 초과, 수동 `_flush?force` | O | O (완전한 내구성) |\n\n### ES Settings -> Lucene 메커니즘 매핑\n\n| ES Setting | 기본값 | Lucene 메커니즘 | 영향 |\n|-----------|-------|----------------|------|\n| `refresh_interval` | `\"1s\"` | `DirectoryReader.openIfChanged()` 호출 주기 | 낮추면 near-real-time 지연 감소, 세그먼트 생성 증가 |\n| `translog.durability` | `\"request\"` | 매 요청마다 `fsync` | `\"async\"` 시 성능 증가, 장애 시 최대 `sync_interval`만큼 유실 |\n| `translog.flush_threshold_size` | `\"512mb\"` | Translog 크기 초과 시 commit 트리거 | 높이면 commit 빈도 감소, 복구 시간 증가 |\n| `translog.sync_interval` | `\"5s\"` | async 모드에서 fsync 주기 | 낮추면 유실 위험 감소, I\u002FO 부하 증가 |\n\n### Merge 전후 시각화\n\n```\nMerge 전 (5개 세그먼트)                    Merge 후 (2개 세그먼트)\n═══════════════════════                   ═══════════════════════\n\n Seg_0    Seg_1    Seg_2                   Merged_0\n┌──────┐ ┌──────┐ ┌──────┐               ┌──────────────────┐\n│ 50K  │ │ 30K  │ │ 10K  │  ──Merge──→  │ 85K docs         │\n│ docs │ │ docs │ │ docs │               │ (삭제 5K 제거됨)  │\n│ del:2K│ │ del:3K│ │ del:0│               └──────────────────┘\n└──────┘ └──────┘ └──────┘\n                                           Seg_3    Seg_4\n Seg_3    Seg_4                           ┌──────┐ ┌──────┐\n┌──────┐ ┌──────┐                         │ 20K  │ │  5K  │\n│ 20K  │ │  5K  │  ──(아직 merge 안 됨)   │ docs │ │ docs │\n│ docs │ │ docs │                         └──────┘ └──────┘\n└──────┘ └──────┘\n\n총 문서: 115K (삭제 5K 포함)              총 문서: 110K (삭제 제거됨)\n세그먼트: 5개                             세그먼트: 3개\n디스크: 세그먼트 오버헤드 5x              디스크: 세그먼트 오버헤드 3x\n```\n\n### TieredMergePolicy 파라미터\n\nES의 기본 merge policy입니다. 세그먼트 크기를 기준으로 비슷한 크기의 세그먼트끼리 merge합니다.\n\n| Parameter | 기본값 | 설명 |\n|-----------|-------|------|\n| `max_merged_segment` (`maxMergedSegmentMB`) | `5gb` | merge 결과 세그먼트의 최대 크기. 이보다 큰 세그먼트는 merge 대상에서 제외 |\n| `segments_per_tier` (`segmentsPerTier`) | `10` | tier당 허용 세그먼트 수. 낮추면 merge 빈번, 높이면 세그먼트 많아짐 |\n| `max_merge_at_once` (`maxMergeAtOnce`) | `10` | 한 번의 merge에 합칠 최대 세그먼트 수 |\n| `floor_segment` (`floorSegmentMB`) | `2mb` | 이 크기 이하의 세그먼트는 동일 크기로 취급 (작은 세그먼트 빈번 merge 방지) |\n| `deletes_pct_allowed` (`deletesPctAllowed`) | `33%` | 삭제 비율이 이 값을 초과하면 merge 강제 트리거 |\n\n```json\n\u002F\u002F ES에서 TieredMergePolicy 튜닝\nPUT \u002Fproducts\u002F_settings\n{\n  \"index.merge.policy.max_merged_segment\": \"5gb\",\n  \"index.merge.policy.segments_per_tier\": \"10\",\n  \"index.merge.policy.max_merge_at_once\": \"10\",\n  \"index.merge.policy.floor_segment\": \"2mb\",\n  \"index.merge.policy.deletes_pct_allowed\": \"20\"\n}\n```\n\n### Force Merge 결정 매트릭스\n\n| 시나리오 | Force Merge? | 이유 |\n|---------|-------------|------|\n| 읽기 전용 인덱스 (ILM warm\u002Fcold 전환 후) | **YES** (`max_num_segments=1`) | 세그먼트 통합으로 검색 성능 향상, 더 이상 쓰기 없음 |\n| 활발히 쓰기 중인 인덱스 | **NEVER** | merge 중 I\u002FO 폭증, 새 세그먼트 계속 생성되어 무의미 |\n| Bulk reindex 완료 직후 | **YES** | reindex로 생성된 많은 소규모 세그먼트 정리 |\n| 삭제 비율 > 30%인 읽기 전용 인덱스 | **YES** | 삭제 문서 물리 제거로 디스크 회수 + 검색 성능 회복 |\n| 일별 인덱스, 다음 날로 rollover 완료 | **YES** | 더 이상 쓰기 없으므로 안전하게 최적화 가능 |\n\n### Segment Lifecycle Anti-Patterns\n\n| Anti-Pattern | Fix | Severity |\n|-------------|-----|----------|\n| `refresh_interval: \"1s\"`로 대량 인덱싱 수행 | 대량 적재 시 `\"-1\"`로 비활성화, 완료 후 복원 | **Critical** |\n| 쓰기 중 인덱스에 force merge 실행 | 읽기 전용 전환 후에만 force merge | **Critical** |\n| `segments_per_tier`를 2로 설정하여 과도한 merge | 기본값 10 유지, 필요 시 점진적 조정 | **High** |\n| translog.durability=async를 영구 적용 | 대량 적재 시에만 임시 적용, 완료 후 `request`로 복원 | **High** |\n| 세그먼트 수 모니터링 없이 운영 | `_segments` API 주기적 확인, 세그먼트 > 50개 시 조사 | **Medium** |\n| `max_merged_segment`를 너무 크게 설정 (50gb+) | 5-10gb 범위 유지, merge I\u002FO와 검색 효율 균형 | **Medium** |\n\n## 4. Index-Time Processing -- Analyzer Chain Internals\n\n### Analyzer 파이프라인\n\nLucene의 Analyzer는 3단계 파이프라인으로 구성됩니다. 각 단계는 독립적으로 교체 가능합니다.\n\n```\n입력 텍스트: \"삼성전자 Galaxy S24 울트라\u003Cbr>할인!\"\n       │\n       ▼\n  ┌──────────────────────────────┐\n  │  CharFilter(s)               │  ← 문자 수준 변환 (HTML strip, 매핑 등)\n  │  html_strip: \"\u003Cbr>\" → \" \"    │\n  │  mapping: \"&\" → \"and\"        │\n  │                              │\n  │  결과: \"삼성전자 Galaxy S24   │\n  │         울트라 할인!\"         │\n  └──────────┬───────────────────┘\n             │\n             ▼\n  ┌──────────────────────────────┐\n  │  Tokenizer                   │  ← 텍스트를 토큰 스트림으로 분리\n  │  nori_tokenizer              │\n  │  (decompound_mode: mixed)    │\n  │                              │\n  │  결과:                        │\n  │  [\"삼성전자\",\"삼성\",\"전자\",    │\n  │   \"Galaxy\",\"S24\",\"울트라\",    │\n  │   \"할인\"]                     │\n  └──────────┬───────────────────┘\n             │\n             ▼\n  ┌──────────────────────────────┐\n  │  TokenFilter(s) 체인          │  ← 토큰 수준 변환 (순서 중요!)\n  │                              │\n  │  1. nori_part_of_speech      │  ← 불용 품사 제거 (조사, 감탄사 등)\n  │  2. nori_readingform         │  ← 한자 → 한글 변환\n  │  3. lowercase                │  ← \"Galaxy\" → \"galaxy\"\n  │  4. synonym_graph            │  ← 동의어 확장\n  │  5. stop                     │  ← 불용어 제거\n  │                              │\n  │  최종: [\"삼성전자\",\"삼성\",     │\n  │         \"전자\",\"galaxy\",\"s24\",│\n  │         \"울트라\",\"할인\"]       │\n  └──────────────────────────────┘\n```\n\n### Token Attributes\n\n각 토큰은 여러 속성(attribute)을 가집니다. 이 속성들이 inverted index에 저장되는 방식을 결정합니다.\n\n| Attribute | 설명 | Inverted Index 저장 위치 |\n|-----------|------|------------------------|\n| `PositionIncrementAttribute` | 이전 토큰과의 position 차이 (기본 1) | `.pos` 파일 |\n| `OffsetAttribute` | 원본 텍스트에서의 시작\u002F끝 위치 (highlight 용) | `.pos` 파일 (offsets 활성화 시) |\n| `PayloadAttribute` | 토큰에 부착하는 사용자 정의 바이트 | `.pay` 파일 |\n| `TypeAttribute` | 토큰 타입 (word, synonym, NUM 등) | 인덱스에 저장되지 않음 (분석 시에만 사용) |\n| `CharTermAttribute` | 토큰 문자열 자체 | `.tim`\u002F`.tip` (term dictionary) |\n| `FlagsAttribute` | 비트 플래그 (커스텀 용도) | 인덱스에 저장되지 않음 |\n\n### Position Gap과 Multi-Value Fields\n\n배열 필드에서 값 사이의 position gap은 `position_increment_gap`으로 제어됩니다.\n\n```\n매핑: { \"tags\": { \"type\": \"text\", \"position_increment_gap\": 100 } }\n\n문서: { \"tags\": [\"무선 이어폰\", \"블루투스 헤드셋\"] }\n\n토큰화 결과 (position 포함):\n  \"무선\"     → position 0\n  \"이어폰\"   → position 1\n                                ← gap: 100 (position_increment_gap)\n  \"블루투스\"  → position 101\n  \"헤드셋\"   → position 102\n\nPhrase Query \"이어폰 블루투스\":\n  position 차이 = 101 - 1 = 100 ≠ 1\n  → 매칭 안 됨! (의도한 동작)\n\n만약 position_increment_gap = 0이었다면:\n  \"이어폰\"   → position 1\n  \"블루투스\"  → position 2\n  → \"이어폰 블루투스\" phrase query가 잘못 매칭됨!\n```\n\n### Custom Analyzer Plugin 구조\n\nJava 기반 커스텀 분석기 플러그인을 작성할 때의 핵심 인터페이스:\n\n```\nPlugin JAR 구조\n├── META-INF\u002F\n│   └── services\u002F\n│       └── org.elasticsearch.plugins.AnalysisPlugin\n├── com\u002Fexample\u002F\n│   ├── MyAnalysisPlugin.java          ← implements AnalysisPlugin\n│   ├── MyTokenizerFactory.java        ← extends AbstractTokenizerFactory\n│   ├── MyTokenizer.java               ← extends Tokenizer\n│   ├── MyTokenFilterFactory.java      ← extends AbstractTokenFilterFactory\n│   └── MyTokenFilter.java             ← extends TokenFilter\n└── plugin-descriptor.properties\n\n핵심 인터페이스:\n  AnalysisPlugin\n  ├── getTokenizers()     → Map\u003CString, AnalysisModule.AnalysisProvider\u003CTokenizerFactory>>\n  ├── getTokenFilters()   → Map\u003CString, AnalysisModule.AnalysisProvider\u003CTokenFilterFactory>>\n  ├── getCharFilters()    → Map\u003CString, AnalysisModule.AnalysisProvider\u003CCharFilterFactory>>\n  └── getAnalyzers()      → Map\u003CString, AnalysisModule.AnalysisProvider\u003CAnalyzerProvider>>\n```\n\n## 5. Query Execution Internals\n\n### Query Lifecycle\n\nES DSL부터 최종 결과 반환까지의 전체 파이프라인입니다.\n\n```\nES Query DSL (JSON)\n       │\n       ▼\n  ┌─────────────────────────┐\n  │  QueryBuilder.toQuery()  │  ← DSL → Lucene Query 변환\n  │  (ES 레이어)              │\n  └───────────┬─────────────┘\n              │\n              ▼\n  ┌─────────────────────────┐\n  │  Query.rewrite()         │  ← 쿼리 최적화\u002F단순화\n  │  - MultiTermQuery 확장   │     (와일드카드 → 개별 TermQuery들)\n  │  - Boolean 단순화         │     (단일 clause → 내부 쿼리로 언래핑)\n  └───────────┬─────────────┘\n              │\n              ▼\n  ┌─────────────────────────┐\n  │  Query.createWeight()    │  ← 글로벌 통계 수집 (IDF 등)\n  │  → Weight 객체 생성       │     검색 컨텍스트 준비\n  └───────────┬─────────────┘\n              │\n              ▼\n     ┌────────┴────────┐\n     │  foreach Segment │  ← 세그먼트별 병렬 처리\n     │                  │\n     │  ┌─────────────────────────┐\n     │  │  Weight.scorer(segment)  │  ← 세그먼트별 Scorer 생성\n     │  │  → Scorer 객체 (iterator)│     Postings 접근 준비\n     │  └───────────┬─────────────┘\n     │              │\n     │              ▼\n     │  ┌─────────────────────────┐\n     │  │  Scorer.iterator()       │  ← DocID 순회\n     │  │  .nextDoc() \u002F .advance() │     matching + scoring\n     │  │  .score()                │\n     │  └───────────┬─────────────┘\n     │              │\n     │              ▼\n     │  ┌─────────────────────────┐\n     │  │  Collector.collect()     │  ← 결과 수집 (top-N heap)\n     │  │  → LeafCollector         │     정렬\u002F집계 처리\n     │  └─────────────────────────┘\n     └─────────────────────┘\n              │\n              ▼\n  ┌─────────────────────────┐\n  │  TopDocs 병합             │  ← 세그먼트별 결과를 priority queue로 합침\n  │  → 최종 결과 반환          │     (shard 간에도 동일 과정)\n  └─────────────────────────┘\n```\n\n### ES Query DSL -> Lucene Query 매핑\n\n| ES Query DSL | Lucene Query | 설명 |\n|-------------|-------------|------|\n| `match` (단일 term) | `TermQuery` | 분석 후 단일 term이면 TermQuery |\n| `match` (복수 term) | `BooleanQuery(SHOULD)` | 분석 후 여러 term이면 BooleanQuery |\n| `match_phrase` | `PhraseQuery` | position 기반 인접 매칭 |\n| `match_phrase_prefix` | `PhraseQuery` + `PrefixQuery` | 마지막 term만 prefix 매칭 |\n| `bool.filter` | `ConstantScoreQuery` + `BooleanQuery(FILTER)` | 스코어 0, bitset 캐시 가능 |\n| `term` | `TermQuery` | 분석 없이 exact match |\n| `range` (numeric) | `PointRangeQuery` | BKD tree 탐색 |\n| `range` (keyword) | `TermRangeQuery` | term dictionary 범위 스캔 |\n| `wildcard` | `AutomatonQuery` | finite automaton으로 term 매칭 |\n| `prefix` | `PrefixQuery` → `MultiTermQuery` | term dictionary prefix 스캔 |\n| `nested` | `ToParentBlockJoinQuery` | 블록 단위 parent-child 조인 |\n| `function_score` | `FunctionScoreQuery` | 커스텀 스코어 함수 래핑 |\n| `dis_max` | `DisjunctionMaxQuery` | 최고 점수 clause + tie_breaker |\n| `constant_score` | `ConstantScoreQuery` | 내부 쿼리 매칭, 고정 점수 |\n| `exists` | `FieldExistsQuery` (DocValues\u002FNorms 기반) | 필드 존재 여부 |\n\n### Collector 계층\n\n| Collector | 역할 | 사용 시점 |\n|-----------|------|----------|\n| `TopScoreDocCollector` | 점수 기반 top-N 수집, min-heap | `sort` 미지정 시 기본 |\n| `TopFieldCollector` | 필드 기반 정렬 top-N 수집 | `sort` 지정 시 |\n| `TotalHitCountCollector` | 총 매칭 문서 수만 계산 | `size: 0` + `track_total_hits: true` |\n| `BucketCollector` | aggregation용 수집기 | `aggs` 사용 시 |\n| `MultiCollector` | 여러 collector를 동시 실행 | 검색 + 집계 동시 수행 시 |\n| `EarlyTerminatingCollector` | N개 수집 후 세그먼트 스킵 | `terminate_after` 설정 시 |\n| `FilteredCollector` | post_filter 적용 후 수집 | `post_filter` 사용 시 |\n\n### Early Termination 전략\n\n**WAND\u002FMaxScore (track_total_hits: false)**\n\n```json\n\u002F\u002F track_total_hits를 false로 설정하면 정확한 총 매칭 수를 계산하지 않음\n\u002F\u002F Lucene의 WAND(Weak AND) \u002F MaxScore 알고리즘이 활성화되어\n\u002F\u002F 현재 top-N의 최저 점수보다 높은 점수를 낼 수 없는 문서를 건너뜀\nGET \u002Fproducts\u002F_search\n{\n  \"track_total_hits\": false,\n  \"size\": 10,\n  \"query\": { \"match\": { \"title\": \"무선 이어폰\" } }\n}\n\u002F\u002F 효과: 대규모 인덱스에서 쿼리 지연 시간 크게 감소\n\u002F\u002F 트레이드오프: total.hits.value가 정확하지 않음 (lower bound만 제공)\n```\n\n**Index Sorting으로 Early Termination**\n\n```json\n\u002F\u002F 인덱스 생성 시 정렬 기준 설정\nPUT \u002Fproducts\n{\n  \"settings\": {\n    \"index\": {\n      \"sort.field\": [\"created_at\", \"price\"],\n      \"sort.order\": [\"desc\", \"asc\"]\n    }\n  },\n  \"mappings\": {\n    \"properties\": {\n      \"created_at\": { \"type\": \"date\" },\n      \"price\": { \"type\": \"long\" }\n    }\n  }\n}\n\n\u002F\u002F 검색 시 동일 정렬 기준 사용하면 early termination 가능\nGET \u002Fproducts\u002F_search\n{\n  \"sort\": [\n    { \"created_at\": \"desc\" },\n    { \"price\": \"asc\" }\n  ],\n  \"size\": 10,\n  \"query\": { \"match_all\": {} }\n}\n\u002F\u002F Lucene이 정렬된 세그먼트에서 상위 N개를 빠르게 수집한 후\n\u002F\u002F 나머지 문서를 안전하게 건너뜀\n```\n\n**Index Sorting 결정 테이블**\n\n| 기준 | Index Sorting 적합 | Index Sorting 부적합 |\n|------|-------------------|-------------------|\n| 주요 쿼리 패턴 | 항상 동일 필드로 정렬 | 다양한 정렬 기준 사용 |\n| 쿼리 유형 | range\u002Fdate 기반 필터 | full-text relevance 검색 |\n| 인덱싱 성능 | 다소 느려도 무방 | 인덱싱 처리량이 최우선 |\n| 사용 사례 | 로그\u002F이벤트 (타임스탬프 정렬) | 상품 검색 (복합 정렬) |\n\n### BKD Tree (숫자\u002FGeo 쿼리)\n\n```\nBKD Tree (Block KD-Tree)\n========================\n숫자, 날짜, IP, geo_point 필드에 사용되는 다차원 공간 인덱스\n\n예: price 필드 (1차원)\n\n                    [100, 500, 200, 800, 150, 350, 900, 50]\n                                    │\n                         Split at median (300)\n                        ┌───────────┴───────────┐\n                   [100,200,150,50]         [500,800,350,900]\n                        │                        │\n                  Split at 125               Split at 625\n                 ┌──────┴──────┐          ┌──────┴──────┐\n              [100,50]    [200,150]    [500,350]    [800,900]\n                (leaf)      (leaf)      (leaf)       (leaf)\n\nRange Query: price >= 100 AND price \u003C= 400\n  1. Root: 300으로 분할 → 양쪽 모두 탐색 필요\n  2. 좌측: 125로 분할 → [100,50] 중 100 매칭, [200,150] 전체 매칭\n  3. 우측: 625로 분할 → [500,350] 중 350 매칭, [800,900] 스킵!\n  결과: [100, 200, 150, 350] → 4개 문서\n\n특성:\n  - O(sqrt(N)) 탐색 시간 (1차원)\n  - leaf 블록은 연속 디스크 배치 (I\u002FO 효율적)\n  - 다차원 지원 (geo_point = 2D, geo_shape = 2D+)\n  - Lucene 파일: .kdd (data), .kdi (inner nodes), .kdm (meta)\n```\n\n## 6. Performance Deep Dive\n\n### 물리 메모리 레이아웃\n\n```\nPhysical RAM (예: 64GB)\n═══════════════════════════════════════════════════════════\n\n┌───────────────────────────────┬──────────────────────────────┐\n│   JVM Heap (~50%, 31GB 이하)  │   OS Page Cache (~50%)        │\n│                               │                              │\n│  ┌─────────────────────────┐  │  ┌────────────────────────┐  │\n│  │ Lucene Segment Readers  │  │  │ .doc\u002F.pos\u002F.pay 파일     │  │\n│  │ (SegmentCoreReaders)    │  │  │ (postings)             │  │\n│  ├─────────────────────────┤  │  ├────────────────────────┤  │\n│  │ Indexing Buffers        │  │  │ .dvd\u002F.dvm 파일          │  │\n│  │ (indices.memory.        │  │  │ (doc values)           │  │\n│  │  index_buffer_size)     │  │  ├────────────────────────┤  │\n│  ├─────────────────────────┤  │  │ .tim\u002F.tip 파일          │  │\n│  │ Query\u002FRequest Cache     │  │  │ (term dictionary FST)  │  │\n│  ├─────────────────────────┤  │  ├────────────────────────┤  │\n│  │ Field Data Cache        │  │  │ .kdd\u002F.kdi 파일          │  │\n│  │ (text 집계 시에만)       │  │  │ (BKD tree)             │  │\n│  ├─────────────────────────┤  │  ├────────────────────────┤  │\n│  │ Aggregation Buffers     │  │  │ .fdt\u002F.fdx 파일          │  │\n│  │ (bucket 계산 등)         │  │  │ (stored fields\u002F_source)│  │\n│  ├─────────────────────────┤  │  └────────────────────────┘  │\n│  │ Network\u002FTransport       │  │                              │\n│  │ Buffers                 │  │  mmap()으로 가상 주소에 매핑   │\n│  └─────────────────────────┘  │  실제 I\u002FO는 OS가 관리         │\n└───────────────────────────────┴──────────────────────────────┘\n\n핵심 원칙:\n  - JVM Heap은 물리 메모리의 50% 이하, 절대 31GB 초과 금지\n    (CompressedOops 비활성화로 heap 효율 급감)\n  - 나머지 50%는 Lucene 파일의 page cache로 활용\n  - page cache miss → 디스크 I\u002FO → 쿼리 지연 시간 급증\n```\n\n### 왜 31GB가 상한인가? (Compressed Oops 동작 원리)\n\n64비트 JVM은 객체 참조(`oop`, ordinary object pointer)를 기본 8바이트가 아닌 **4바이트로 압축**해서 표현합니다 (`-XX:+UseCompressedOops`, JDK 7+ 기본 활성화). 이 압축이 가능한 이유와 32GB에서 깨지는 메커니즘은 다음과 같습니다.\n\n**32GB 경계의 수학적 근거**:\n\n```\n일반 64비트 포인터:   8 bytes (64 bit)  →  주소 공간: 2^64 = 16 EB\nCompressed Oops:    4 bytes (32 bit)  →  주소 공간: 2^32 = 4 GB\n\n하지만 JVM 객체는 8-byte alignment 보장 (객체 시작 주소가 항상 8의 배수)\n→ 포인터 하위 3비트는 항상 0 → 저장하지 않고 shift로 복원\n\n   실제 주소 = (compressed_oop \u003C\u003C 3)\n   실효 주소 공간 = 2^32 × 2^3 = 2^35 = 32 GB ★\n```\n\n힙이 32GB를 **단 1바이트라도 초과**하면 JVM이 4바이트 포인터로 모든 객체를 가리킬 수 없게 되어 Compressed Oops를 자동 비활성화합니다.\n\n**32GB를 넘기는 순간 발생하는 변화**:\n\n| 항목 | Compressed (≤31GB) | Uncompressed (>32GB) | 영향 |\n|------|-------------------|---------------------|------|\n| 객체 참조 크기 | 4 bytes | 8 bytes | 모든 필드 참조가 2배 |\n| 객체 헤더 (klass pointer 포함) | 12 bytes | 16 bytes | 작은 객체일수록 비율 ↑ |\n| 동일 객체 heap 사용량 | 기준 | **+30 ~ 50%** | 실효 용량 감소 |\n| **실효 heap 용량** | 31GB | **약 25 ~ 28GB** | ★ **역전 현상** |\n| CPU L1\u002FL2 캐시 효율 | 높음 | 낮음 (cache line당 객체 수 ↓) | 모든 메모리 접근 지연 |\n| GC pause 시간 | 기준 | 길어짐 (스캔할 포인터 크기 ↑) | tail latency 악화 |\n| 메모리 대역폭 | 기준 | 압박 증가 | scan-heavy 워크로드 직격 |\n\n**역전 현상이 핵심**: 32GB → 33GB로 올리면 가용 객체 수가 오히려 **줄어듭니다**. 31GB가 필요하면 31GB로 두고, 정말 더 필요하면 **48GB 이상** (가급적 64GB+)까지 점프해야 압축 비활성화 손실을 상쇄할 수 있습니다. **32~47GB 구간은 전 구간이 안티패턴**입니다.\n\n**ES 권장 설정 및 검증**:\n\n```bash\n# jvm.options\n-Xms30g\n-Xmx30g          # 31GB가 아닌 30GB로 1GB 안전 마진 (메타스페이스, 정렬 오버헤드 고려)\n\n# 압축 oops 활성화 여부 확인\njcmd \u003CES_PID> VM.flags | grep -i CompressedOops\n# → -XX:+UseCompressedOops 가 보이면 OK\n\n# ES 시작 로그에서 확인\ngrep \"compressed ordinary object pointers\" \u002Fvar\u002Flog\u002Felasticsearch\u002F*.log\n# → \"heap size [29.8gb], compressed ordinary object pointers [true]\" 형태\n```\n\nJDK 15+에서는 `-XX:+UseCompressedClassPointers`까지 비활성화되면 추가 손실이 발생하므로, 위 검증 한 줄은 노드 부팅 시 반드시 확인해야 합니다.\n\n### Heap vs Off-Heap 구성 요소\n\n| 구성 요소 | 위치 | 크기 결정 요인 | 관리 방법 |\n|----------|------|-------------|----------|\n| Segment Readers (SegmentCoreReaders) | Heap | 열려 있는 세그먼트 수 | merge로 세그먼트 수 감소 |\n| Indexing Buffer | Heap | `indices.memory.index_buffer_size` (10%) | 설정값 조정 |\n| Query Cache (bitset) | Heap | `indices.queries.cache.size` (10%) | LRU 자동 eviction |\n| Request Cache | Heap | `indices.requests.cache.size` (1%) | 인덱스 refresh 시 무효화 |\n| Field Data | Heap | 필드 cardinality * 포인터 크기 | circuit breaker로 제한 |\n| Aggregation Buffers | Heap | 쿼리 복잡도, bucket 수 | request circuit breaker |\n| FST (Term Dictionary) | Off-Heap (mmap) | unique term 수, prefix 공유율 | page cache에 의존 |\n| Doc Values | Off-Heap (mmap) | 문서 수 * 필드당 바이트 | page cache에 의존 |\n| Postings Lists | Off-Heap (mmap) | 인덱스 총 크기 | page cache에 의존 |\n| BKD Tree | Off-Heap (mmap) | 숫자\u002Fgeo 필드 문서 수 | page cache에 의존 |\n| Stored Fields | Off-Heap (mmap) | `_source` 크기 합계 | page cache에 의존 |\n\n### Query Cache 동작 상세\n\nQuery cache는 세그먼트별 LRU bitset으로 구현됩니다. 모든 쿼리가 캐싱되지는 않습니다.\n\n```\nQuery Cache 적격 조건:\n  1. filter context에서 실행된 쿼리만 (query context는 캐시 불가)\n  2. 해당 쿼리가 5회 이상 실행됨 (history count >= 5)\n  3. 세그먼트의 문서 수가 10,000개 이상\n  4. 세그먼트가 전체 인덱스 문서의 3% 이상을 포함\n  5. TermQuery, MatchAllDocsQuery 등 비용이 낮은 쿼리는 제외\n\n캐시 구조 (세그먼트별):\n  Segment_0:\n    Query(\"status:active\") → BitSet [1,1,0,1,0,1,1,...] (문서 매칭 비트맵)\n    Query(\"price:[100 TO 500]\") → BitSet [0,1,1,0,0,1,0,...]\n\n  Segment_1:\n    Query(\"status:active\") → BitSet [1,0,1,1,0,0,1,...]\n    (다른 세그먼트이므로 별도 BitSet)\n\n무효화:\n  - 세그먼트가 merge되면 해당 세그먼트의 캐시 전체 무효화\n  - refresh로 새 세그먼트가 생기면 해당 세그먼트에는 캐시 없음\n  - LRU eviction: 메모리 한도 초과 시 가장 오래된 엔트리 제거\n```\n\n### Circuit Breakers\n\n| Circuit Breaker | 기본 한도 | 보호 대상 | 트리거 상황 |\n|----------------|----------|----------|-----------|\n| `fielddata` | Heap의 40% | field data 로드 | text 필드에 대한 집계\u002F정렬 |\n| `request` | Heap의 60% | 단일 요청 메모리 | 대규모 aggregation, 큰 결과셋 |\n| `in_flight_requests` | Heap의 100% | 전송 중인 요청 | 동시 요청 과다 |\n| `parent` | Heap의 95% | 전체 heap 사용량 | 여러 breaker 합산 초과 |\n| `accounting` | Heap의 100% | Lucene 세그먼트 메모리 | 세그먼트 과다 |\n\n```json\n\u002F\u002F Circuit breaker 설정 조정\nPUT \u002F_cluster\u002Fsettings\n{\n  \"persistent\": {\n    \"indices.breaker.fielddata.limit\": \"30%\",\n    \"indices.breaker.request.limit\": \"50%\",\n    \"indices.breaker.total.limit\": \"90%\"\n  }\n}\n```\n\n### Skip Lists (Postings 내부)\n\nPostings list 탐색을 가속하는 multi-level skip list 구조입니다.\n\n```\nSkip List 구조 (Postings List 가속)\n═══════════════════════════════════\n\nLevel 2:  1 ─────────────────────────── 97 ──────────────────── 193\n          │                              │                       │\nLevel 1:  1 ──────── 33 ──────── 65 ── 97 ──── 129 ──── 161 ── 193\n          │          │           │      │       │        │       │\nLevel 0:  1,2,3,...  33,34,35..  65,66  97,98   129,130  161,162 193,...\n          (DocIDs in postings list)\n\nadvance(150) 실행 과정:\n  1. Level 2: 1 → 97 (150 > 97, 계속)  → 193 (150 \u003C 193, Level 1로)\n  2. Level 1: 97 → 129 (150 > 129)     → 161 (150 \u003C 161, Level 0로)\n  3. Level 0: 129 → 130 → ... → 150 (찾음!)\n\nskip 없이 선형 탐색: 150 steps\nskip list 탐색:     ~15 steps (O(sqrt(N)))\n\nBooleanQuery에서의 활용:\n  AND(term_A, term_B): 짧은 리스트의 DocID로 긴 리스트를 advance()\n  → skip list 덕분에 긴 리스트 대부분을 건너뜀\n```\n\n### Block Encoding (FOR Delta Encoding)\n\nPostings list의 DocID는 Frame of Reference (FOR) delta encoding으로 압축됩니다.\n\n```\n원본 DocIDs:   [101, 105, 108, 115, 120, 133, 140, 145]\n\nStep 1 - Delta Encoding:\n  [101, 4, 3, 7, 5, 13, 7, 5]   ← 첫 값은 그대로, 나머지는 이전 값과의 차이\n\nStep 2 - Frame of Reference:\n  Block (128개 단위): 블록 내 최대 delta = 13\n  → 4 bits면 충분 (2^4 = 16 > 13)\n  → 128개 값 * 4 bits = 64 bytes (vs 원본 128 * 4 bytes = 512 bytes)\n  → 압축률: ~87.5%\n\nSIMD 최적화:\n  - 128개 정수를 한 블록으로 묶어 CPU SIMD 명령으로 일괄 디코딩\n  - vectorized bit-unpacking으로 높은 처리량\n  - Lucene의 ForUtil 클래스에서 구현\n```\n\n### Selective Filter가 BooleanQuery 성능을 극적으로 개선하는 이유\n\n```\n시나리오: 100만 문서 인덱스에서 검색\n\n쿼리 1 (filter 없음):\n  { \"match\": { \"title\": \"이어폰\" } }\n  → \"이어폰\" postings: 50,000 docs\n  → 50,000개 문서 전부 scoring 필요\n  → 소요: ~50ms\n\n쿼리 2 (선택적 filter 추가):\n  { \"bool\": {\n      \"must\": { \"match\": { \"title\": \"이어폰\" } },\n      \"filter\": { \"term\": { \"brand\": \"삼성\" } }\n  }}\n  → \"이어폰\" postings: 50,000 docs\n  → \"삼성\" filter bitset: 5,000 docs (캐시됨!)\n  → 교집합: 리드 쿼리가 짧은 리스트(5,000)를 순회하며 긴 리스트를 advance()\n  → scoring 대상: ~500 docs\n  → 소요: ~5ms (10x 개선!)\n\n핵심 메커니즘:\n  1. filter는 bitset으로 캐시되어 재사용 (scoring 오버헤드 없음)\n  2. BooleanQuery의 conjunction은 가장 짧은 postings list를 리드로 선택\n  3. skip list의 advance()로 긴 리스트의 대부분을 건너뜀\n  4. scoring은 교집합에 포함된 문서에 대해서만 수행\n```\n\n## 7. Lucene-ES Setting Mapping Reference\n\nES의 인덱스\u002F클러스터 설정이 Lucene 내부에서 어떤 메커니즘으로 구현되는지 종합 정리합니다.\n\n| ES Setting | 기본값 | Lucene 메커니즘 | 성능 영향 |\n|-----------|-------|----------------|----------|\n| `number_of_shards` | 1 | shard당 하나의 `IndexWriter` 인스턴스 | shard 수 = Lucene 인덱스 수. 과다 시 heap\u002FFD 낭비, 과소 시 병렬성 부족 |\n| `refresh_interval` | `\"1s\"` | `DirectoryReader.openIfChanged()` 호출 주기 | 짧으면 작은 세그먼트 다수 생성 → merge 부하. `\"-1\"`로 비활성화 가능 |\n| `merge.policy.max_merged_segment` | `\"5gb\"` | `TieredMergePolicy.maxMergedSegmentMB` | 큰 세그먼트는 merge 제외됨. 너무 낮으면 세그먼트 파편화 |\n| `merge.policy.segments_per_tier` | `10` | `TieredMergePolicy.segmentsPerTier` | 낮추면 merge 빈번 (I\u002FO 증가), 높이면 세그먼트 수 증가 |\n| `merge.policy.deletes_pct_allowed` | `33` | `TieredMergePolicy.deletesPctAllowed` | 삭제 비율 한도. 낮추면 삭제 문서가 빨리 정리됨 |\n| `merge.scheduler.max_thread_count` | `Math.max(1, Math.min(4, cores\u002F2))` | `ConcurrentMergeScheduler.maxThreadCount` | merge 병렬성. I\u002FO 바운드이므로 과다 스레드는 비효율 |\n| `sort.field` \u002F `sort.order` | (없음) | `IndexWriterConfig.indexSort` | 세그먼트 내부가 정렬됨. 동일 정렬의 쿼리에서 early termination 가능 |\n| `codec` | `\"default\"` | `Lucene99Codec` | `best_compression` 시 `DEFLATE` 사용 (stored fields 압축률 향상, CPU 비용 증가) |\n| `max_result_window` | `10000` | `TopDocsCollector` heap 크기 제한 | 깊은 페이징 방지. 초과 시 `search_after` 사용 |\n| `mapping.total_fields.limit` | `1000` | 세그먼트 메타데이터, 필드별 인덱스 구조 | 필드 과다 시 세그먼트 오버헤드 증가, mapping explosion |\n| `highlight.max_analyzed_offset` | `1000000` | `UnifiedHighlighter` 오프셋 탐색 범위 | 큰 문서의 highlight 시 메모리\u002FCPU 보호 |\n| `indices.memory.index_buffer_size` | `10%` | `IndexWriter`의 RAM buffer 총량 | indexing throughput에 영향. 대량 적재 시 증가 고려 |\n| `indices.queries.cache.size` | `10%` | LRU BitSet 캐시 (세그먼트별) | filter 쿼리 캐시. 높이면 반복 쿼리 가속, heap 사용 증가 |\n| `index.translog.durability` | `\"request\"` | 매 요청 `fsync` | `\"async\"` 시 배치 fsync로 인덱싱 성능 향상, 데이터 유실 위험 |\n| `index.translog.flush_threshold_size` | `\"512mb\"` | translog 크기 초과 시 Lucene commit 트리거 | 높이면 commit 빈도 감소, 노드 재시작 시 복구 시간 증가 |\n\n---\n\n**Remember**: Elasticsearch는 Lucene 위에 구축된 분산 시스템입니다. ES 성능 문제의 근본 원인은 대부분 Lucene 레벨에 있습니다 -- 세그먼트가 너무 많은지, 적절한 필드 타입을 사용하는지, filter context를 활용하는지, OS 페이지 캐시를 위한 메모리가 충분한지 확인하세요. `_profile` API와 `_explain` API는 Lucene 내부를 들여다보는 창입니다. 추측하지 말고, 측정하세요.\n","# Lucene Internals for Elasticsearch Engineers\n\nElasticsearch의 기반인 Apache Lucene의 내부 구조를 다루는 가이드입니다. ES 성능 문제의 근본 원인은 대부분 Lucene 레벨에 있습니다.\n\n## When to Activate\n\n- `_profile` API 출력에서 `build_scorer`, `advance`, `next_doc` 시간이 비정상적일 때\n- `_explain` API 출력에서 IDF\u002FTF\u002Fnorms 값이 예상과 다를 때\n- 세그먼트 수가 증가하거나 force merge 결정이 필요할 때\n- `refresh_interval`, translog, flush 설정 튜닝 시\n- `doc_values` vs `fielddata` 선택이 필요할 때\n- 숫자\u002Fgeo 쿼리 성능 이슈 (BKD tree)\n- OS page cache 사이징 또는 heap vs off-heap 메모리 결정 시\n- `index.sort.*` 설정으로 검색 시 early termination 구현 시\n\n## 1. Architecture Fundamentals -- ES Shard = Lucene Index\n\n### ES-Lucene Concept Mapping\n\n하나의 ES shard는 하나의 Lucene `IndexWriter`\u002F`IndexReader` 인스턴스입니다. ES의 모든 개념은 Lucene 개념 위에 매핑됩니다.\n\n| ES Concept | Lucene Concept | 설명 |\n|------------|---------------|------|\n| Shard | `IndexWriter` + `IndexReader` | 하나의 독립적인 Lucene 인덱스 |\n| Document | `Document` | 필드의 컬렉션 |\n| `text` field | `TextField` | 분석(tokenize)되어 inverted index에 저장 |\n| `keyword` field | `StringField` | 분석 없이 단일 토큰으로 저장 |\n| `doc_values` | `DocValuesField` | 정렬\u002F집계용 column-oriented 저장소 |\n| `_source` | `StoredField` | 원본 JSON을 그대로 저장 |\n| Refresh | `DirectoryReader.openIfChanged()` | 새 세그먼트를 검색 가능하게 만듦 |\n| Flush | `IndexWriter.flush()` | 인메모리 버퍼를 세그먼트로 디스크에 기록 |\n| Commit | `IndexWriter.commit()` | fsync + commit point 기록 (durability) |\n| Merge | `MergePolicy` + `MergeScheduler` | 여러 세그먼트를 하나로 합침 |\n\n### Inverted Index 구조\n\nLucene의 핵심 자료구조입니다. Term Dictionary는 FST(Finite State Transducer)로 구현되어 메모리 효율적인 prefix 탐색을 지원합니다.\n\n```\nInverted Index (하나의 필드에 대해)\n==================================\n\nTerm Dictionary (FST)          Postings List\n-----------------------        ----------------------------------------\n  \"검색\"  ─────────────────→  DocID: [2, 15, 42, 108]\n                               Freq:  [1,  3,  1,   2]\n                               Pos:   [(0), (0,5,12), (3), (0,7)]\n\n  \"엔진\"  ─────────────────→  DocID: [15, 42, 200]\n                               Freq:  [1,   2,   1]\n                               Pos:   [(1), (1,8), (0)]\n\n  \"최적화\" ────────────────→  DocID: [2, 200, 305]\n                               Freq:  [1,   1,   4]\n                               Pos:   [(2), (1), (0,3,7,11)]\n\nFST (Finite State Transducer)\n─────────────────────────────\n  - Term → Postings 파일 오프셋 매핑\n  - 메모리에 상주 (off-heap via mmap)\n  - 공통 prefix\u002Fsuffix 공유로 메모리 절약\n  - O(len(term)) 탐색 시간\n\nPostings List 구성 요소\n─────────────────────────\n  .doc  → DocID + Term Frequency (항상 존재)\n  .pos  → Position + Offset (index_options에 따라)\n  .pay  → Payload (사용자 정의 바이트)\n```\n\n### Doc Values Column Store\n\n`doc_values`는 정렬, 집계, scripting에 사용되는 column-oriented 저장소입니다.\n\n```\nDoc Values 레이아웃 (예: \"price\" 필드)\n=======================================\n\nRow-Oriented (stored fields)     Column-Oriented (doc_values)\n─────────────────────────────    ─────────────────────────────\nDoc0: {name:\"A\", price:1000}     price 컬럼:\nDoc1: {name:\"B\", price:2500}       Doc0 → 1000\nDoc2: {name:\"C\", price:800}        Doc1 → 2500\nDoc3: {name:\"D\", price:3200}       Doc2 →  800\n                                   Doc3 → 3200\n                                   (디스크에 연속 배치, mmap으로 접근)\n\nDocValues 타입:\n  NUMERIC    → long\u002Fdouble 값 (price, timestamp)\n  BINARY     → byte[] (해시, 임의 바이너리)\n  SORTED     → ordinal 기반 사전순 (keyword)\n  SORTED_SET → 다중 값 ordinal (tags)\n  SORTED_NUMERIC → 다중 숫자 값\n```\n\n### doc_values vs stored fields vs fielddata\n\n| 기준 | doc_values | stored fields | fielddata |\n|------|-----------|---------------|-----------|\n| **접근 패턴** | column-oriented (특정 필드, 모든 문서) | row-oriented (특정 문서, 모든 필드) | column-oriented (heap) |\n| **메커니즘** | 디스크 + mmap (off-heap) | 디스크에서 읽기 (decompress) | heap에 역인덱스 반전 로드 |\n| **Heap 비용** | 없음 (OS page cache 사용) | 없음 | 매우 높음 (OOM 위험) |\n| **디스크 레이아웃** | 세그먼트별 `.dvd`\u002F`.dvm` 파일 | `.fdt`\u002F`.fdx` 파일 | 디스크 없음 (런타임 생성) |\n| **용도** | 정렬, 집계, scripting | `_source` 반환, highlight | text 필드 집계 (비권장) |\n| **기본 활성화** | keyword\u002Fnumeric\u002Fdate\u002Fetc 자동 | `_source` 자동 | 비활성화 (명시적 활성화 필요) |\n\n**원칙**: `fielddata`는 text 필드에서 집계가 불가피할 때만 사용. 대부분의 경우 `keyword` sub-field + `doc_values`로 대체.\n\n### Segment 기반 아키텍처\n\nLucene 인덱스는 불변(immutable) 세그먼트의 집합입니다. 삭제는 물리 삭제가 아닌 비트맵 마킹이며, merge 시 실제 제거됩니다.\n\n```\nLucene Index (= 1 ES Shard)\n════════════════════════════════════════════════════════════\n\n  In-Memory Buffer (IndexWriter)\n  ┌─────────────────────────────┐\n  │  새로 인덱싱된 문서들         │ ──── Flush ────┐\n  │  (아직 검색 불가)             │                 │\n  └─────────────────────────────┘                 ▼\n                                          ┌──────────────┐\n  Searchable Segments                     │  Segment_N   │\n  ┌──────────┐ ┌──────────┐ ┌──────────┐ │  (최신)       │\n  │ Segment_0│ │ Segment_1│ │ Segment_2│ └──────────────┘\n  │ 50K docs │ │ 30K docs │ │ 10K docs │\n  │ .si .doc │ │ .si .doc │ │ .si .doc │\n  │ .pos .dvd│ │ .pos .dvd│ │ .pos .dvd│\n  │ .tim .tip│ │ .tim .tip│ │ .tim .tip│\n  └──────────┘ └──────────┘ └──────────┘\n       │              │            │\n       └──────────────┴────────────┘\n                    │\n                  Merge ──→  ┌──────────────────┐\n                             │ Merged_Segment    │\n                             │ 90K docs          │\n                             │ (삭제 문서 제거됨)  │\n                             └──────────────────┘\n\n  Delete Bitmap (per segment)\n  ┌─────────────────────────────────────────┐\n  │ Segment_0: [0,0,1,0,0,0,1,0,...] (bit) │  ← doc 2, 6 삭제됨\n  │ Segment_1: [0,0,0,0,...] (bit)          │  ← 삭제 없음\n  └─────────────────────────────────────────┘\n\n  segments_N 파일 (commit point)\n  ┌───────────────────────────────────┐\n  │ generation: 5                     │\n  │ segments: [Seg_0, Seg_1, Seg_2]   │\n  │ userData: {translog_uuid: \"...\"}  │\n  └───────────────────────────────────┘\n```\n\n### Codec 시스템\n\n각 세그먼트의 데이터 구조는 Codec에 의해 결정됩니다. ES 8.x는 Lucene 9.x 코덱을 사용합니다.\n\n| Codec Format | 파일 확장자 | 역할 |\n|-------------|-----------|------|\n| `Lucene99PostingsFormat` | `.doc`, `.pos`, `.pay` | Postings list (DocID, Freq, Position, Payload) |\n| `Lucene90DocValuesFormat` | `.dvd`, `.dvm` | Doc values (정렬\u002F집계용 column store) |\n| `Lucene90StoredFieldsFormat` | `.fdt`, `.fdx`, `.fdm` | Stored fields (`_source` 포함) |\n| `Lucene90NormsFormat` | `.nvd`, `.nvm` | Norms (필드 길이 인코딩 값) |\n| `Lucene90TermVectorsFormat` | `.tvd`, `.tvx`, `.tvm` | Term vectors (문서별 term 정보) |\n| `Lucene90PointsFormat` | `.kdd`, `.kdi`, `.kdm` | BKD tree (숫자\u002Fgeo\u002FIP 범위 쿼리) |\n| `Lucene90SegmentInfoFormat` | `.si` | 세그먼트 메타데이터 |\n| `Lucene90LiveDocsFormat` | `.liv` | 삭제 비트맵 |\n\n### Directory 추상화와 Page Cache\n\n| Directory 구현 | 메커니즘 | 특성 |\n|---------------|---------|------|\n| `MMapDirectory` | `mmap()` 시스템 콜 | 파일을 가상 메모리에 매핑. OS page cache 활용. **ES 기본값** |\n| `NIOFSDirectory` | `FileChannel.read()` | Java NIO 기반. mmap보다 느리지만 주소 공간 제한 없음 |\n\n**Page Cache가 중요한 이유**: Lucene은 파일을 `mmap`으로 열고, 실제 I\u002FO는 OS page cache에 위임합니다. 충분한 page cache가 없으면 모든 쿼리가 디스크 I\u002FO를 발생시켜 지연 시간이 급증합니다. JVM heap을 물리 메모리의 50% 이하로 설정하고 나머지를 page cache로 남겨야 하는 이유입니다.\n\n## 2. Scoring & Similarity Deep Dive\n\n### BM25 공식 분해\n\nES 8.x의 기본 유사도 함수입니다. 각 term-document 쌍에 대해 다음을 계산합니다:\n\n```\nscore(q, d) = SUM_over_t_in_q [\n    IDF(t) * ( tf(t,d) * (k1 + 1) ) \u002F ( tf(t,d) + k1 * (1 - b + b * dl\u002Favgdl) )\n]\n\n여기서:\n  IDF(t)  = ln(1 + (N - df(t) + 0.5) \u002F (df(t) + 0.5))\n  tf(t,d) = freq(t,d) \u002F (freq(t,d) + k1 * (1 - b + b * dl\u002Favgdl))   -- BM25 saturation (ES 8.x 기본, _explain의 tf 항과 일치)\n            ※ sqrt(freq)는 구식 ClassicSimilarity(TF-IDF) 방식이며 BM25Similarity가 아님\n  dl      = 문서 d의 필드 길이 (토큰 수, norms로 인코딩)\n  avgdl   = 전체 문서의 평균 필드 길이\n  N       = 전체 문서 수 (해당 shard 기준)\n  df(t)   = term t를 포함하는 문서 수\n  k1      = 1.2 (기본값, TF saturation 제어)\n  b       = 0.75 (기본값, 문서 길이 정규화 제어)\n```\n\n### 스코어링 구성 요소 상세\n\n| Component | 소스 | 저장 위치 | 설명 |\n|-----------|------|----------|------|\n| `tf` (Term Frequency) | Postings list `.doc` 파일 | freq 값에서 계산 | 문서 내 term 출현 빈도. BM25는 saturation 식 `freq\u002F(freq+k1*(1-b+b*dl\u002Favgdl))` 적용 (`sqrt(freq)`는 구식 ClassicSimilarity) |\n| `df` (Document Frequency) | Term Dictionary 메타데이터 | 세그먼트별 `.tip` 파일 | term을 포함하는 문서 수 |\n| `dl` (Document Length) | Norms | `.nvd` 파일 | 필드의 토큰 수. `SmallFloat`로 1바이트 인코딩 |\n| `avgdl` | 세그먼트 메타데이터에서 계산 | `sumTotalTermFreq \u002F docCount` | shard 전체의 평균 필드 길이 |\n| `N` (docCount) | 세그먼트 메타데이터 | `SegmentInfo` | 해당 shard의 전체 문서 수 (삭제 포함 주의) |\n| `k1` | Similarity 설정 | 인덱스 settings | TF 포화 곡선 제어. 높을수록 TF 영향 증가 |\n| `b` | Similarity 설정 | 인덱스 settings | 문서 길이 보정. 0이면 길이 무시, 1이면 완전 정규화 |\n\n### Norms: 1바이트 필드 길이 인코딩\n\n`dl`(필드 길이)은 norms로 인코딩됩니다. `SmallFloat.intToByte4()`를 사용하여 정수를 1바이트(256가지 값)로 압축합니다.\n\n```\nNorms 인코딩 예시:\n  필드 길이 1   → norms byte: 100  (정확)\n  필드 길이 2   → norms byte: 120  (정확)\n  필드 길이 3   → norms byte: 126  (정확)\n  필드 길이 5   → norms byte: 122  (근사값)\n  필드 길이 10  → norms byte: 116  (근사값)\n  필드 길이 100 → norms byte: 80   (근사값, 정밀도 ↓)\n  필드 길이 500 → norms byte: 64   (근사값, 정밀도 ↓↓)\n\n주의:\n  - 256가지 값만 표현 가능하므로 긴 필드에서는 정밀도 손실\n  - 필드 길이 1-5 사이에서는 정확하지만, 100 이상은 근사치\n  - norms 비활성화 시 (\"norms\": false) dl=1로 처리되어 길이 정규화 불가\n  - keyword, _id 등은 기본적으로 norms 비활성화\n```\n\n### IDF per-shard 문제와 dfs_query_then_fetch\n\n기본 `query_then_fetch`에서 IDF는 shard-local로 계산됩니다. 문서 분포가 불균등하면 동일 term에 대해 shard마다 다른 IDF를 반환합니다.\n\n```json\n\u002F\u002F 문제 상황: shard 0에 \"검색\" 포함 문서 10,000개, shard 1에 5개\n\u002F\u002F → shard 1에서 \"검색\"의 IDF가 매우 높아져 비정상적인 점수\n\n\u002F\u002F 해결: dfs_query_then_fetch (2-pass 방식)\nGET \u002Fproducts\u002F_search?search_type=dfs_query_then_fetch\n{\n  \"query\": { \"match\": { \"title\": \"검색 엔진\" } }\n}\n\u002F\u002F Pass 1: 모든 shard에서 df, docCount 수집\n\u002F\u002F Pass 2: 글로벌 통계로 스코어링\n\u002F\u002F 트레이드오프: 추가 라운드트립 발생. 대규모 클러스터에서는 오버헤드 주의\n```\n\n> ⚠️ **글로벌 IDF는 `_explain\u002F{id}`로 검증 불가**: `GET \u002Fidx\u002F_explain\u002F{id}`은 `search_type`을 무시한다(issue #2612). `dfs_query_then_fetch`를 줘도 단건 `_explain`은 여전히 per-shard IDF만 보여줘 실제 검색 점수와 어긋난다. dfs 글로벌 IDF·rescore가 반영된 점수는 `_search { \"explain\": true }`로만 확인하라.\n\n### Custom Similarity 설정\n\n```json\n\u002F\u002F ES 인덱스 설정에서 similarity 커스텀\nPUT \u002Fproducts\n{\n  \"settings\": {\n    \"index\": {\n      \"similarity\": {\n        \"custom_bm25\": {\n          \"type\": \"BM25\",\n          \"k1\": \"1.0\",\n          \"b\": \"0.3\",\n          \"discount_overlaps\": \"true\"\n        }\n      }\n    }\n  },\n  \"mappings\": {\n    \"properties\": {\n      \"title\": {\n        \"type\": \"text\",\n        \"similarity\": \"custom_bm25\"\n      }\n    }\n  }\n}\n\n\u002F\u002F Scripted Similarity (고급)\nPUT \u002Fproducts\n{\n  \"settings\": {\n    \"index\": {\n      \"similarity\": {\n        \"scripted_tfidf\": {\n          \"type\": \"scripted\",\n          \"script\": {\n            \"source\": \"double tf = Math.sqrt(doc.freq); double idf = Math.log((field.docCount+1.0)\u002F(term.docFreq+1.0)) + 1.0; double norm = 1\u002FMath.sqrt(doc.length); return query.boost * tf * idf * norm;\"\n          }\n        }\n      }\n    }\n  }\n}\n```\n\n### Alternative Similarity 모델\n\n| Similarity | 설명 | 적합 케이스 |\n|-----------|------|-----------|\n| `BM25` (기본) | Okapi BM25, TF saturation + 길이 정규화 | 대부분의 검색 |\n| `DFR` | Divergence From Randomness | 학술 검색, 긴 문서 |\n| `DFI` | Divergence From Independence | 짧은 문서, 키워드 매칭 |\n| `IB` | Information-Based Model | 자연어 처리 연구용 |\n| `LMDirichlet` | Language Model, Dirichlet smoothing | 짧은 쿼리, 긴 문서 |\n| `LMJelinekMercer` | Language Model, Jelinek-Mercer smoothing | 긴 쿼리 |\n| `scripted` | 사용자 정의 스크립트 | 완전 커스텀 스코어링 |\n| `boolean` | TF\u002FIDF 무시, 매칭 여부만 | filter-like 스코어링 |\n\n### _explain API 출력 읽기\n\n```json\n\u002F\u002F 요청\nGET \u002Fproducts\u002F_explain\u002F42\n{\n  \"query\": {\n    \"bool\": {\n      \"must\": [\n        { \"match\": { \"title\": \"무선 이어폰\" } }\n      ],\n      \"filter\": [\n        { \"term\": { \"status\": \"active\" } }\n      ]\n    }\n  }\n}\n\n\u002F\u002F 응답 해석\n{\n  \"matched\": true,\n  \"_explanation\": {\n    \"value\": 8.234,                          \u002F\u002F ← 최종 스코어\n    \"description\": \"sum of:\",\n    \"details\": [\n      {\n        \"value\": 8.234,\n        \"description\": \"sum of:\",            \u002F\u002F ← bool.must의 합\n        \"details\": [\n          {\n            \"value\": 4.512,\n            \"description\": \"weight(title:무선 in 42) [PerFieldSimilarity]\",\n            \"details\": [\n              {\n                \"value\": 4.512,\n                \"description\": \"score(freq=1.0), computed as boost * idf * tf\",\n                \"details\": [\n                  { \"value\": 2.2, \"description\": \"boost\" },\n                  {\n                    \"value\": 3.145,          \u002F\u002F ← IDF 값\n                    \"description\": \"idf, computed as log(1 + (N - n + 0.5) \u002F (n + 0.5))\",\n                    \"details\": [\n                      { \"value\": 50000, \"description\": \"N, total number of documents\" },\n                      { \"value\": 1200, \"description\": \"n, number of documents containing term\" }\n                    ]\n                  },\n                  {\n                    \"value\": 0.651,          \u002F\u002F ← TF-Norm 값\n                    \"description\": \"tf, computed as freq \u002F (freq + k1 * (1 - b + b * dl \u002F avgdl))\",\n                    \"details\": [\n                      { \"value\": 1.0, \"description\": \"freq, occurrences of term within document\" },\n                      { \"value\": 1.2, \"description\": \"k1\" },\n                      { \"value\": 0.75, \"description\": \"b\" },\n                      { \"value\": 3.0, \"description\": \"dl, length of field\" },\n                      { \"value\": 5.2, \"description\": \"avgdl, average length of field\" }\n                    ]\n                  }\n                ]\n              }\n            ]\n          },\n          {\n            \"value\": 3.722,\n            \"description\": \"weight(title:이어폰 in 42) [PerFieldSimilarity]\"\n            \u002F\u002F ... 동일 구조\n          }\n        ]\n      }\n      \u002F\u002F filter 절은 스코어에 기여하지 않으므로 여기 나타나지 않음\n    ]\n  }\n}\n```\n\n**_explain 읽기 체크리스트**:\n- `N` (total documents)이 예상 shard 크기와 일치하는지 확인\n- `n` (documents containing term)이 합리적인지 확인 (너무 크면 IDF 낮음)\n- `dl` (document length)이 해당 문서의 실제 토큰 수와 일치하는지 확인\n- `freq`가 해당 문서 내 term 출현 수와 일치하는지 확인\n- filter 절은 score에 나타나지 않음 (0.0 기여)\n\n#### _termvectors로 색인된 실제 토큰 확인\n\n`_explain`이 \"왜 이 점수인가\"를 보여준다면, `_termvectors`는 \"이 문서에 실제로 어떤 토큰이 색인되었는가\"를 보여줍니다. 코덱 차원에서는 `.tvd`\u002F`.tvx`\u002F`.tvm`(`Lucene90TermVectorsFormat`, 위 Codec 표 참조)에 저장된 문서별 term 정보를 읽어옵니다.\n\n```json\n\u002F\u002F 요청: 색인된 토큰 + 통계\nGET \u002Fproducts\u002F_termvectors\u002F42\n{\n  \"fields\": [\"title\"],\n  \"term_statistics\": true,\n  \"field_statistics\": true\n}\n\n\u002F\u002F 응답 구조 (루트는 복수형 term_vectors)\n{\n  \"_id\": \"42\",\n  \"found\": true,\n  \"term_vectors\": {\n    \"title\": {\n      \"field_statistics\": {\n        \"sum_doc_freq\": 120000,\n        \"doc_count\": 50000,\n        \"sum_ttf\": 180000\n      },\n      \"terms\": {                          \u002F\u002F ← 키 = 색인된 실제 토큰 (분석기 통과 후)\n        \"무선\": {\n          \"doc_freq\": 1200,               \u002F\u002F ← _explain idf의 n과 동일 출처\n          \"ttf\": 1500,\n          \"term_freq\": 1,\n          \"tokens\": [\n            { \"position\": 0, \"start_offset\": 0, \"end_offset\": 2 }\n          ]\n        },\n        \"이어폰\": {\n          \"doc_freq\": 800,\n          \"term_freq\": 1,\n          \"tokens\": [\n            { \"position\": 1, \"start_offset\": 3, \"end_offset\": 6 }\n          ]\n        }\n      }\n    }\n  }\n}\n```\n\n**교차검증 포인트**:\n- `terms` 맵의 **키가 색인된 실제 토큰**입니다. `_analyze`(search_analyzer)로 얻은 쿼리 토큰과 교집합이 비면 분석기 불일치가 확정됩니다.\n- `term_statistics: true`의 `doc_freq`는 `_explain` idf 설명의 `n`(documents containing term)과 **동일한 출처**입니다. 두 값이 다르면 샤드\u002F세그먼트 경계 또는 통계 갱신 시점 차이를 의심합니다.\n\n**on-the-fly drift 함정**:\n- 매핑이 `term_vector: no`(기본값)이면 색인 시점에 term vector를 저장하지 않으므로, `_termvectors`는 `_source`를 **현재 index_analyzer로 즉석(on-the-fly) 재분석**해 토큰을 만듭니다.\n- 따라서 분석기를 바꾼 뒤 reindex를 누락하면, 실제 색인된(과거 분석기) 토큰과 on-the-fly(현재 분석기) 결과가 어긋나도 `_termvectors`만으로는 drift를 탐지하지 못합니다.\n- 진짜 색인 시점 토큰을 보려면 매핑을 `term_vector: with_positions_offsets`로 두거나(단, 소급 적용 불가 — 설정 이후 색인분부터), reindex로 교차검증해야 합니다.\n\n**offset 단위**: `start_offset`\u002F`end_offset`은 UTF-16 code unit 기준입니다. 한글은 BMP 영역이라 1글자=1단위로 안전하지만, 이모지\u002F보충문자(surrogate pair)는 1글자=2단위로 계산됩니다.\n\n> **[정정] `dfs` 파라미터 금지**: `_termvectors`에 `dfs` 파라미터는 **존재하지 않습니다**(ES 5.0, PR#16452에서 제거됨 — 8.x에 없음). 멀티샤드 간 통계(doc_freq) 편차를 정확히 보려면 단일 샤드 테스트 인덱스를 쓰거나 클라이언트에서 전역 통계를 재계산하십시오. artificial doc은 routing 미지정 시 무작위 샤드에 매핑되어 통계가 부정확해질 수 있습니다.\n\n#### _profile 5대 섹션과 timeout 원인 분리 결정 트리\n\n`_profile`(요청 본문에 `\"profile\": true`)은 **shard-level** 실행을 5개 섹션으로 분해합니다. `profile.shards[]` 배열의 각 샤드마다 다음 키가 (조건부로) 존재합니다.\n\n| 섹션 | 존재 조건 | 의미 |\n|------|----------|------|\n| `searches[].query[]` | 항상 | Lucene Query 실행 트리 (가장 흔한 주범) |\n| `searches[].rewrite_time` | 항상 | Query rewrite에 든 시간(nanos) |\n| `searches[].collector[]` | 항상 | 결과 수집 단계(top hits\u002Fcount 등) |\n| `aggregations[]` | aggs가 있을 때만 | 집계 실행 트리 (aggs 없으면 **이 섹션 자체가 부재**) |\n| `fetch` | 항상 | hit 본문 로딩 단계 |\n\n**1차 절단 — '가장 느린 단일 샤드' 기준**: 샤드별 시간을 단순 합산하면 안 됩니다(병렬 실행이므로 wall-clock과 무관). 가장 느린 단일 샤드 하나를 골라 그 안에서 `Σquery time` vs `collector 루트 time` vs `Σaggregations time` vs `fetch.breakdown 합`을 비교해 주범 단계를 특정합니다.\n\n**query breakdown 9필드** (각각 `*_count` 동반):\n\n| 필드 | 호출 빈도 | 의미 |\n|------|----------|------|\n| `create_weight` | 세그먼트 무관 1회 | Weight 객체 생성(쿼리 정규화) |\n| `build_scorer` | 세그먼트마다 | Scorer 구축 (높으면 term 수\u002F세그먼트 수 과다) |\n| `next_doc` | 매칭 문서 순회 | 다음 매칭 docID로 이동 |\n| `advance` | skip 시 | 특정 docID로 점프(conjunction) |\n| `match` | two-phase | 2단계 확인(phrase 등) |\n| `score` | 스코어링 시 | 점수 계산 |\n| `shallow_advance` | block-max WAND | 블록 단위 advance |\n| `compute_max_score` | block-max WAND | 블록 최대 점수 산출 |\n| `set_min_competitive_score` | top-k 가지치기 | 경쟁 컷 갱신 |\n\n**aggregation breakdown 6필드**: `initialize` \u002F `build_leaf_collector` \u002F `collect`(+`collect_count`) \u002F `post_collection` \u002F `build_aggregation` \u002F `reduce`(= reserved, **항상 0**).\n\n**collector reason 사전**: `search_top_hits` \u002F `search_count` \u002F `search_query_phase` \u002F `search_terminate_after_count` \u002F `search_timeout` \u002F `aggregation` \u002F `global_aggregation`. ⚠️ collector time은 query time과 **시간대가 중복**되므로 두 값을 합산하지 마십시오.\n\n**fetch.breakdown 실제 필드**: `next_reader`\u002F`next_reader_count`, `load_stored_fields`\u002F`load_stored_fields_count`, `load_source`\u002F`load_source_count`. `load_source`가 크면 거대 `_source` 로딩이 병목 — `_source` 필터링\u002F`stored_fields` 검토.\n\n**took vs Σtime_in_nanos 갭**: 응답의 `took`이 profile의 모든 `time_in_nanos` 합보다 **현저히 크면**(took >> 합) 병목이 '단계 밖'에 있다는 신호입니다 — coordinating 노드 머지, 네트워크, rewrite\u002Fglobal ordinals lazy 빌드 등 profile이 측정하지 못하는 영역.\n\n**profile이 측정하지 못하는 항목**: coordinating 머지·네트워크 전송, rewrite\u002Fglobal ordinals 빌드(과소계상 또는 누락).\n\n> **[함정] profiling 오버헤드**: `_profile`은 WAND\u002Fblock-max 등 Lucene 최적화를 **비활성화**하고 모든 단계를 계측하므로 절대 nanos가 부풀려집니다(공식 문서 'non-negligible overhead'). 따라서 (1) 단계 **간 상대 비교** 전용으로만 쓰고 절대 시간으로 SLA를 판단하지 말 것, (2) 프로덕션에서 기본 활성화 금지.\n\n**global ordinals — '첫 쿼리만 느림' 신호**: 고-카디널리티 keyword 필드(예: nori 분석 텍스트와 별개로 운영하는 `brand`\u002F`category` keyword facet)의 terms 집계는 global ordinals를 필요로 합니다.\n- 기본(lazy): 첫 집계 쿼리의 `collect` 단계에 빌드 비용이 **과소계상**되거나 `took` 갭으로만 드러나, \"첫 쿼리만 느리고 이후엔 빠름\" 패턴을 만듭니다.\n- `eager_global_ordinals: true`로 두면 빌드가 refresh-time으로 이동해 쿼리 시점 profile에서 **완전히 사라집니다**(대신 색인\u002Frefresh 비용 증가). 첫 쿼리 지연이 반복 재현되면 이 설정을 검토합니다.\n\n> 증상 기반 진입은 search-diagnostics 스킬 참조\n\n## 3. Segment Lifecycle -- Refresh, Flush, Merge, Commit\n\n### Write Path 타임라인\n\n```\nIndex Request 도착\n       │\n       ▼\n  ┌──────────────────┐\n  │  Translog 기록    │  ← 내구성 보장 (fsync 또는 async)\n  │  (WAL 역할)       │\n  └────────┬─────────┘\n           │\n           ▼\n  ┌──────────────────┐\n  │  In-Memory Buffer │  ← IndexWriter의 DWPT\n  │  (인덱싱 + 분석)   │     (DocumentsWriterPerThread)\n  └────────┬─────────┘\n           │\n     Refresh (기본 1초)\n           │\n           ▼\n  ┌──────────────────┐\n  │  New Segment      │  ← 디스크에 기록되지만 fsync 안 됨\n  │  (검색 가능!)      │     DirectoryReader.openIfChanged()\n  └────────┬─────────┘\n           │\n     Flush \u002F Commit\n           │\n           ▼\n  ┌──────────────────┐\n  │  Committed Seg    │  ← fsync 완료, segments_N에 기록\n  │  (내구성 보장)     │     translog 삭제 가능\n  └────────┬─────────┘\n           │\n     Merge (비동기, MergePolicy가 결정)\n           │\n           ▼\n  ┌──────────────────┐\n  │  Merged Segment   │  ← 여러 세그먼트 합병, 삭제 문서 제거\n  │  (최적화된 상태)   │     구 세그먼트 파일 삭제\n  └──────────────────┘\n```\n\n### Refresh vs Flush vs Commit\n\n| 작업 | 내부 동작 | 트리거 | 검색 가능? | 내구성 보장? |\n|------|----------|--------|-----------|------------|\n| **Refresh** | `DirectoryReader.openIfChanged()` 호출, 새 세그먼트를 reader에 노출 | `refresh_interval` (기본 1초), 수동 `_refresh` | O | X (fsync 없음) |\n| **Flush** | 인메모리 버퍼 → 세그먼트 파일 기록, translog는 유지 | 버퍼 크기 초과, 수동 `_flush` | O (refresh 포함) | 부분적 (translog로 복구) |\n| **Commit** | `IndexWriter.commit()`, fsync + `segments_N` 기록, translog 정리 | translog 크기 초과, 수동 `_flush?force` | O | O (완전한 내구성) |\n\n### ES Settings -> Lucene 메커니즘 매핑\n\n| ES Setting | 기본값 | Lucene 메커니즘 | 영향 |\n|-----------|-------|----------------|------|\n| `refresh_interval` | `\"1s\"` | `DirectoryReader.openIfChanged()` 호출 주기 | 낮추면 near-real-time 지연 감소, 세그먼트 생성 증가 |\n| `translog.durability` | `\"request\"` | 매 요청마다 `fsync` | `\"async\"` 시 성능 증가, 장애 시 최대 `sync_interval`만큼 유실 |\n| `translog.flush_threshold_size` | `\"512mb\"` | Translog 크기 초과 시 commit 트리거 | 높이면 commit 빈도 감소, 복구 시간 증가 |\n| `translog.sync_interval` | `\"5s\"` | async 모드에서 fsync 주기 | 낮추면 유실 위험 감소, I\u002FO 부하 증가 |\n\n### Merge 전후 시각화\n\n```\nMerge 전 (5개 세그먼트)                    Merge 후 (2개 세그먼트)\n═══════════════════════                   ═══════════════════════\n\n Seg_0    Seg_1    Seg_2                   Merged_0\n┌──────┐ ┌──────┐ ┌──────┐               ┌──────────────────┐\n│ 50K  │ │ 30K  │ │ 10K  │  ──Merge──→  │ 85K docs         │\n│ docs │ │ docs │ │ docs │               │ (삭제 5K 제거됨)  │\n│ del:2K│ │ del:3K│ │ del:0│               └──────────────────┘\n└──────┘ └──────┘ └──────┘\n                                           Seg_3    Seg_4\n Seg_3    Seg_4                           ┌──────┐ ┌──────┐\n┌──────┐ ┌──────┐                         │ 20K  │ │  5K  │\n│ 20K  │ │  5K  │  ──(아직 merge 안 됨)   │ docs │ │ docs │\n│ docs │ │ docs │                         └──────┘ └──────┘\n└──────┘ └──────┘\n\n총 문서: 115K (삭제 5K 포함)              총 문서: 110K (삭제 제거됨)\n세그먼트: 5개                             세그먼트: 3개\n디스크: 세그먼트 오버헤드 5x              디스크: 세그먼트 오버헤드 3x\n```\n\n### TieredMergePolicy 파라미터\n\nES의 기본 merge policy입니다. 세그먼트 크기를 기준으로 비슷한 크기의 세그먼트끼리 merge합니다.\n\n| Parameter | 기본값 | 설명 |\n|-----------|-------|------|\n| `max_merged_segment` (`maxMergedSegmentMB`) | `5gb` | merge 결과 세그먼트의 최대 크기. 이보다 큰 세그먼트는 merge 대상에서 제외 |\n| `segments_per_tier` (`segmentsPerTier`) | `10` | tier당 허용 세그먼트 수. 낮추면 merge 빈번, 높이면 세그먼트 많아짐 |\n| `max_merge_at_once` (`maxMergeAtOnce`) | `10` | 한 번의 merge에 합칠 최대 세그먼트 수 |\n| `floor_segment` (`floorSegmentMB`) | `2mb` | 이 크기 이하의 세그먼트는 동일 크기로 취급 (작은 세그먼트 빈번 merge 방지) |\n| `deletes_pct_allowed` (`deletesPctAllowed`) | `33%` | 삭제 비율이 이 값을 초과하면 merge 강제 트리거 |\n\n```json\n\u002F\u002F ES에서 TieredMergePolicy 튜닝\nPUT \u002Fproducts\u002F_settings\n{\n  \"index.merge.policy.max_merged_segment\": \"5gb\",\n  \"index.merge.policy.segments_per_tier\": \"10\",\n  \"index.merge.policy.max_merge_at_once\": \"10\",\n  \"index.merge.policy.floor_segment\": \"2mb\",\n  \"index.merge.policy.deletes_pct_allowed\": \"20\"\n}\n```\n\n### Force Merge 결정 매트릭스\n\n| 시나리오 | Force Merge? | 이유 |\n|---------|-------------|------|\n| 읽기 전용 인덱스 (ILM warm\u002Fcold 전환 후) | **YES** (`max_num_segments=1`) | 세그먼트 통합으로 검색 성능 향상, 더 이상 쓰기 없음 |\n| 활발히 쓰기 중인 인덱스 | **NEVER** | merge 중 I\u002FO 폭증, 새 세그먼트 계속 생성되어 무의미 |\n| Bulk reindex 완료 직후 | **YES** | reindex로 생성된 많은 소규모 세그먼트 정리 |\n| 삭제 비율 > 30%인 읽기 전용 인덱스 | **YES** | 삭제 문서 물리 제거로 디스크 회수 + 검색 성능 회복 |\n| 일별 인덱스, 다음 날로 rollover 완료 | **YES** | 더 이상 쓰기 없으므로 안전하게 최적화 가능 |\n\n### Segment Lifecycle Anti-Patterns\n\n| Anti-Pattern | Fix | Severity |\n|-------------|-----|----------|\n| `refresh_interval: \"1s\"`로 대량 인덱싱 수행 | 대량 적재 시 `\"-1\"`로 비활성화, 완료 후 복원 | **Critical** |\n| 쓰기 중 인덱스에 force merge 실행 | 읽기 전용 전환 후에만 force merge | **Critical** |\n| `segments_per_tier`를 2로 설정하여 과도한 merge | 기본값 10 유지, 필요 시 점진적 조정 | **High** |\n| translog.durability=async를 영구 적용 | 대량 적재 시에만 임시 적용, 완료 후 `request`로 복원 | **High** |\n| 세그먼트 수 모니터링 없이 운영 | `_segments` API 주기적 확인, 세그먼트 > 50개 시 조사 | **Medium** |\n| `max_merged_segment`를 너무 크게 설정 (50gb+) | 5-10gb 범위 유지, merge I\u002FO와 검색 효율 균형 | **Medium** |\n\n## 4. Index-Time Processing -- Analyzer Chain Internals\n\n### Analyzer 파이프라인\n\nLucene의 Analyzer는 3단계 파이프라인으로 구성됩니다. 각 단계는 독립적으로 교체 가능합니다.\n\n```\n입력 텍스트: \"삼성전자 Galaxy S24 울트라\u003Cbr>할인!\"\n       │\n       ▼\n  ┌──────────────────────────────┐\n  │  CharFilter(s)               │  ← 문자 수준 변환 (HTML strip, 매핑 등)\n  │  html_strip: \"\u003Cbr>\" → \" \"    │\n  │  mapping: \"&\" → \"and\"        │\n  │                              │\n  │  결과: \"삼성전자 Galaxy S24   │\n  │         울트라 할인!\"         │\n  └──────────┬───────────────────┘\n             │\n             ▼\n  ┌──────────────────────────────┐\n  │  Tokenizer                   │  ← 텍스트를 토큰 스트림으로 분리\n  │  nori_tokenizer              │\n  │  (decompound_mode: mixed)    │\n  │                              │\n  │  결과:                        │\n  │  [\"삼성전자\",\"삼성\",\"전자\",    │\n  │   \"Galaxy\",\"S24\",\"울트라\",    │\n  │   \"할인\"]                     │\n  └──────────┬───────────────────┘\n             │\n             ▼\n  ┌──────────────────────────────┐\n  │  TokenFilter(s) 체인          │  ← 토큰 수준 변환 (순서 중요!)\n  │                              │\n  │  1. nori_part_of_speech      │  ← 불용 품사 제거 (조사, 감탄사 등)\n  │  2. nori_readingform         │  ← 한자 → 한글 변환\n  │  3. lowercase                │  ← \"Galaxy\" → \"galaxy\"\n  │  4. synonym_graph            │  ← 동의어 확장\n  │  5. stop                     │  ← 불용어 제거\n  │                              │\n  │  최종: [\"삼성전자\",\"삼성\",     │\n  │         \"전자\",\"galaxy\",\"s24\",│\n  │         \"울트라\",\"할인\"]       │\n  └──────────────────────────────┘\n```\n\n### Token Attributes\n\n각 토큰은 여러 속성(attribute)을 가집니다. 이 속성들이 inverted index에 저장되는 방식을 결정합니다.\n\n| Attribute | 설명 | Inverted Index 저장 위치 |\n|-----------|------|------------------------|\n| `PositionIncrementAttribute` | 이전 토큰과의 position 차이 (기본 1) | `.pos` 파일 |\n| `OffsetAttribute` | 원본 텍스트에서의 시작\u002F끝 위치 (highlight 용) | `.pos` 파일 (offsets 활성화 시) |\n| `PayloadAttribute` | 토큰에 부착하는 사용자 정의 바이트 | `.pay` 파일 |\n| `TypeAttribute` | 토큰 타입 (word, synonym, NUM 등) | 인덱스에 저장되지 않음 (분석 시에만 사용) |\n| `CharTermAttribute` | 토큰 문자열 자체 | `.tim`\u002F`.tip` (term dictionary) |\n| `FlagsAttribute` | 비트 플래그 (커스텀 용도) | 인덱스에 저장되지 않음 |\n\n### Position Gap과 Multi-Value Fields\n\n배열 필드에서 값 사이의 position gap은 `position_increment_gap`으로 제어됩니다.\n\n```\n매핑: { \"tags\": { \"type\": \"text\", \"position_increment_gap\": 100 } }\n\n문서: { \"tags\": [\"무선 이어폰\", \"블루투스 헤드셋\"] }\n\n토큰화 결과 (position 포함):\n  \"무선\"     → position 0\n  \"이어폰\"   → position 1\n                                ← gap: 100 (position_increment_gap)\n  \"블루투스\"  → position 101\n  \"헤드셋\"   → position 102\n\nPhrase Query \"이어폰 블루투스\":\n  position 차이 = 101 - 1 = 100 ≠ 1\n  → 매칭 안 됨! (의도한 동작)\n\n만약 position_increment_gap = 0이었다면:\n  \"이어폰\"   → position 1\n  \"블루투스\"  → position 2\n  → \"이어폰 블루투스\" phrase query가 잘못 매칭됨!\n```\n\n### Custom Analyzer Plugin 구조\n\nJava 기반 커스텀 분석기 플러그인을 작성할 때의 핵심 인터페이스:\n\n```\nPlugin JAR 구조\n├── META-INF\u002F\n│   └── services\u002F\n│       └── org.elasticsearch.plugins.AnalysisPlugin\n├── com\u002Fexample\u002F\n│   ├── MyAnalysisPlugin.java          ← implements AnalysisPlugin\n│   ├── MyTokenizerFactory.java        ← extends AbstractTokenizerFactory\n│   ├── MyTokenizer.java               ← extends Tokenizer\n│   ├── MyTokenFilterFactory.java      ← extends AbstractTokenFilterFactory\n│   └── MyTokenFilter.java             ← extends TokenFilter\n└── plugin-descriptor.properties\n\n핵심 인터페이스:\n  AnalysisPlugin\n  ├── getTokenizers()     → Map\u003CString, AnalysisModule.AnalysisProvider\u003CTokenizerFactory>>\n  ├── getTokenFilters()   → Map\u003CString, AnalysisModule.AnalysisProvider\u003CTokenFilterFactory>>\n  ├── getCharFilters()    → Map\u003CString, AnalysisModule.AnalysisProvider\u003CCharFilterFactory>>\n  └── getAnalyzers()      → Map\u003CString, AnalysisModule.AnalysisProvider\u003CAnalyzerProvider>>\n```\n\n## 5. Query Execution Internals\n\n### Query Lifecycle\n\nES DSL부터 최종 결과 반환까지의 전체 파이프라인입니다.\n\n```\nES Query DSL (JSON)\n       │\n       ▼\n  ┌─────────────────────────┐\n  │  QueryBuilder.toQuery()  │  ← DSL → Lucene Query 변환\n  │  (ES 레이어)              │\n  └───────────┬─────────────┘\n              │\n              ▼\n  ┌─────────────────────────┐\n  │  Query.rewrite()         │  ← 쿼리 최적화\u002F단순화\n  │  - MultiTermQuery 확장   │     (와일드카드 → 개별 TermQuery들)\n  │  - Boolean 단순화         │     (단일 clause → 내부 쿼리로 언래핑)\n  └───────────┬─────────────┘\n              │\n              ▼\n  ┌─────────────────────────┐\n  │  Query.createWeight()    │  ← 글로벌 통계 수집 (IDF 등)\n  │  → Weight 객체 생성       │     검색 컨텍스트 준비\n  └───────────┬─────────────┘\n              │\n              ▼\n     ┌────────┴────────┐\n     │  foreach Segment │  ← 세그먼트별 병렬 처리\n     │                  │\n     │  ┌─────────────────────────┐\n     │  │  Weight.scorer(segment)  │  ← 세그먼트별 Scorer 생성\n     │  │  → Scorer 객체 (iterator)│     Postings 접근 준비\n     │  └───────────┬─────────────┘\n     │              │\n     │              ▼\n     │  ┌─────────────────────────┐\n     │  │  Scorer.iterator()       │  ← DocID 순회\n     │  │  .nextDoc() \u002F .advance() │     matching + scoring\n     │  │  .score()                │\n     │  └───────────┬─────────────┘\n     │              │\n     │              ▼\n     │  ┌─────────────────────────┐\n     │  │  Collector.collect()     │  ← 결과 수집 (top-N heap)\n     │  │  → LeafCollector         │     정렬\u002F집계 처리\n     │  └─────────────────────────┘\n     └─────────────────────┘\n              │\n              ▼\n  ┌─────────────────────────┐\n  │  TopDocs 병합             │  ← 세그먼트별 결과를 priority queue로 합침\n  │  → 최종 결과 반환          │     (shard 간에도 동일 과정)\n  └─────────────────────────┘\n```\n\n### ES Query DSL -> Lucene Query 매핑\n\n| ES Query DSL | Lucene Query | 설명 |\n|-------------|-------------|------|\n| `match` (단일 term) | `TermQuery` | 분석 후 단일 term이면 TermQuery |\n| `match` (복수 term) | `BooleanQuery(SHOULD)` | 분석 후 여러 term이면 BooleanQuery |\n| `match_phrase` | `PhraseQuery` | position 기반 인접 매칭 |\n| `match_phrase_prefix` | `PhraseQuery` + `PrefixQuery` | 마지막 term만 prefix 매칭 |\n| `bool.filter` | `ConstantScoreQuery` + `BooleanQuery(FILTER)` | 스코어 0, bitset 캐시 가능 |\n| `term` | `TermQuery` | 분석 없이 exact match |\n| `range` (numeric) | `PointRangeQuery` | BKD tree 탐색 |\n| `range` (keyword) | `TermRangeQuery` | term dictionary 범위 스캔 |\n| `wildcard` | `AutomatonQuery` | finite automaton으로 term 매칭 |\n| `prefix` | `PrefixQuery` → `MultiTermQuery` | term dictionary prefix 스캔 |\n| `nested` | `ToParentBlockJoinQuery` | 블록 단위 parent-child 조인 |\n| `function_score` | `FunctionScoreQuery` | 커스텀 스코어 함수 래핑 |\n| `dis_max` | `DisjunctionMaxQuery` | 최고 점수 clause + tie_breaker |\n| `constant_score` | `ConstantScoreQuery` | 내부 쿼리 매칭, 고정 점수 |\n| `exists` | `FieldExistsQuery` (DocValues\u002FNorms 기반) | 필드 존재 여부 |\n\n### Collector 계층\n\n| Collector | 역할 | 사용 시점 |\n|-----------|------|----------|\n| `TopScoreDocCollector` | 점수 기반 top-N 수집, min-heap | `sort` 미지정 시 기본 |\n| `TopFieldCollector` | 필드 기반 정렬 top-N 수집 | `sort` 지정 시 |\n| `TotalHitCountCollector` | 총 매칭 문서 수만 계산 | `size: 0` + `track_total_hits: true` |\n| `BucketCollector` | aggregation용 수집기 | `aggs` 사용 시 |\n| `MultiCollector` | 여러 collector를 동시 실행 | 검색 + 집계 동시 수행 시 |\n| `EarlyTerminatingCollector` | N개 수집 후 세그먼트 스킵 | `terminate_after` 설정 시 |\n| `FilteredCollector` | post_filter 적용 후 수집 | `post_filter` 사용 시 |\n\n### Early Termination 전략\n\n**WAND\u002FMaxScore (track_total_hits: false)**\n\n```json\n\u002F\u002F track_total_hits를 false로 설정하면 정확한 총 매칭 수를 계산하지 않음\n\u002F\u002F Lucene의 WAND(Weak AND) \u002F MaxScore 알고리즘이 활성화되어\n\u002F\u002F 현재 top-N의 최저 점수보다 높은 점수를 낼 수 없는 문서를 건너뜀\nGET \u002Fproducts\u002F_search\n{\n  \"track_total_hits\": false,\n  \"size\": 10,\n  \"query\": { \"match\": { \"title\": \"무선 이어폰\" } }\n}\n\u002F\u002F 효과: 대규모 인덱스에서 쿼리 지연 시간 크게 감소\n\u002F\u002F 트레이드오프: total.hits.value가 정확하지 않음 (lower bound만 제공)\n```\n\n**Index Sorting으로 Early Termination**\n\n```json\n\u002F\u002F 인덱스 생성 시 정렬 기준 설정\nPUT \u002Fproducts\n{\n  \"settings\": {\n    \"index\": {\n      \"sort.field\": [\"created_at\", \"price\"],\n      \"sort.order\": [\"desc\", \"asc\"]\n    }\n  },\n  \"mappings\": {\n    \"properties\": {\n      \"created_at\": { \"type\": \"date\" },\n      \"price\": { \"type\": \"long\" }\n    }\n  }\n}\n\n\u002F\u002F 검색 시 동일 정렬 기준 사용하면 early termination 가능\nGET \u002Fproducts\u002F_search\n{\n  \"sort\": [\n    { \"created_at\": \"desc\" },\n    { \"price\": \"asc\" }\n  ],\n  \"size\": 10,\n  \"query\": { \"match_all\": {} }\n}\n\u002F\u002F Lucene이 정렬된 세그먼트에서 상위 N개를 빠르게 수집한 후\n\u002F\u002F 나머지 문서를 안전하게 건너뜀\n```\n\n**Index Sorting 결정 테이블**\n\n| 기준 | Index Sorting 적합 | Index Sorting 부적합 |\n|------|-------------------|-------------------|\n| 주요 쿼리 패턴 | 항상 동일 필드로 정렬 | 다양한 정렬 기준 사용 |\n| 쿼리 유형 | range\u002Fdate 기반 필터 | full-text relevance 검색 |\n| 인덱싱 성능 | 다소 느려도 무방 | 인덱싱 처리량이 최우선 |\n| 사용 사례 | 로그\u002F이벤트 (타임스탬프 정렬) | 상품 검색 (복합 정렬) |\n\n### BKD Tree (숫자\u002FGeo 쿼리)\n\n```\nBKD Tree (Block KD-Tree)\n========================\n숫자, 날짜, IP, geo_point 필드에 사용되는 다차원 공간 인덱스\n\n예: price 필드 (1차원)\n\n                    [100, 500, 200, 800, 150, 350, 900, 50]\n                                    │\n                         Split at median (300)\n                        ┌───────────┴───────────┐\n                   [100,200,150,50]         [500,800,350,900]\n                        │                        │\n                  Split at 125               Split at 625\n                 ┌──────┴──────┐          ┌──────┴──────┐\n              [100,50]    [200,150]    [500,350]    [800,900]\n                (leaf)      (leaf)      (leaf)       (leaf)\n\nRange Query: price >= 100 AND price \u003C= 400\n  1. Root: 300으로 분할 → 양쪽 모두 탐색 필요\n  2. 좌측: 125로 분할 → [100,50] 중 100 매칭, [200,150] 전체 매칭\n  3. 우측: 625로 분할 → [500,350] 중 350 매칭, [800,900] 스킵!\n  결과: [100, 200, 150, 350] → 4개 문서\n\n특성:\n  - O(sqrt(N)) 탐색 시간 (1차원)\n  - leaf 블록은 연속 디스크 배치 (I\u002FO 효율적)\n  - 다차원 지원 (geo_point = 2D, geo_shape = 2D+)\n  - Lucene 파일: .kdd (data), .kdi (inner nodes), .kdm (meta)\n```\n\n## 6. Performance Deep Dive\n\n### 물리 메모리 레이아웃\n\n```\nPhysical RAM (예: 64GB)\n═══════════════════════════════════════════════════════════\n\n┌───────────────────────────────┬──────────────────────────────┐\n│   JVM Heap (~50%, 31GB 이하)  │   OS Page Cache (~50%)        │\n│                               │                              │\n│  ┌─────────────────────────┐  │  ┌────────────────────────┐  │\n│  │ Lucene Segment Readers  │  │  │ .doc\u002F.pos\u002F.pay 파일     │  │\n│  │ (SegmentCoreReaders)    │  │  │ (postings)             │  │\n│  ├─────────────────────────┤  │  ├────────────────────────┤  │\n│  │ Indexing Buffers        │  │  │ .dvd\u002F.dvm 파일          │  │\n│  │ (indices.memory.        │  │  │ (doc values)           │  │\n│  │  index_buffer_size)     │  │  ├────────────────────────┤  │\n│  ├─────────────────────────┤  │  │ .tim\u002F.tip 파일          │  │\n│  │ Query\u002FRequest Cache     │  │  │ (term dictionary FST)  │  │\n│  ├─────────────────────────┤  │  ├────────────────────────┤  │\n│  │ Field Data Cache        │  │  │ .kdd\u002F.kdi 파일          │  │\n│  │ (text 집계 시에만)       │  │  │ (BKD tree)             │  │\n│  ├─────────────────────────┤  │  ├────────────────────────┤  │\n│  │ Aggregation Buffers     │  │  │ .fdt\u002F.fdx 파일          │  │\n│  │ (bucket 계산 등)         │  │  │ (stored fields\u002F_source)│  │\n│  ├─────────────────────────┤  │  └────────────────────────┘  │\n│  │ Network\u002FTransport       │  │                              │\n│  │ Buffers                 │  │  mmap()으로 가상 주소에 매핑   │\n│  └─────────────────────────┘  │  실제 I\u002FO는 OS가 관리         │\n└───────────────────────────────┴──────────────────────────────┘\n\n핵심 원칙:\n  - JVM Heap은 물리 메모리의 50% 이하, 절대 31GB 초과 금지\n    (CompressedOops 비활성화로 heap 효율 급감)\n  - 나머지 50%는 Lucene 파일의 page cache로 활용\n  - page cache miss → 디스크 I\u002FO → 쿼리 지연 시간 급증\n```\n\n### 왜 31GB가 상한인가? (Compressed Oops 동작 원리)\n\n64비트 JVM은 객체 참조(`oop`, ordinary object pointer)를 기본 8바이트가 아닌 **4바이트로 압축**해서 표현합니다 (`-XX:+UseCompressedOops`, JDK 7+ 기본 활성화). 이 압축이 가능한 이유와 32GB에서 깨지는 메커니즘은 다음과 같습니다.\n\n**32GB 경계의 수학적 근거**:\n\n```\n일반 64비트 포인터:   8 bytes (64 bit)  →  주소 공간: 2^64 = 16 EB\nCompressed Oops:    4 bytes (32 bit)  →  주소 공간: 2^32 = 4 GB\n\n하지만 JVM 객체는 8-byte alignment 보장 (객체 시작 주소가 항상 8의 배수)\n→ 포인터 하위 3비트는 항상 0 → 저장하지 않고 shift로 복원\n\n   실제 주소 = (compressed_oop \u003C\u003C 3)\n   실효 주소 공간 = 2^32 × 2^3 = 2^35 = 32 GB ★\n```\n\n힙이 32GB를 **단 1바이트라도 초과**하면 JVM이 4바이트 포인터로 모든 객체를 가리킬 수 없게 되어 Compressed Oops를 자동 비활성화합니다.\n\n**32GB를 넘기는 순간 발생하는 변화**:\n\n| 항목 | Compressed (≤31GB) | Uncompressed (>32GB) | 영향 |\n|------|-------------------|---------------------|------|\n| 객체 참조 크기 | 4 bytes | 8 bytes | 모든 필드 참조가 2배 |\n| 객체 헤더 (klass pointer 포함) | 12 bytes | 16 bytes | 작은 객체일수록 비율 ↑ |\n| 동일 객체 heap 사용량 | 기준 | **+30 ~ 50%** | 실효 용량 감소 |\n| **실효 heap 용량** | 31GB | **약 25 ~ 28GB** | ★ **역전 현상** |\n| CPU L1\u002FL2 캐시 효율 | 높음 | 낮음 (cache line당 객체 수 ↓) | 모든 메모리 접근 지연 |\n| GC pause 시간 | 기준 | 길어짐 (스캔할 포인터 크기 ↑) | tail latency 악화 |\n| 메모리 대역폭 | 기준 | 압박 증가 | scan-heavy 워크로드 직격 |\n\n**역전 현상이 핵심**: 32GB → 33GB로 올리면 가용 객체 수가 오히려 **줄어듭니다**. 31GB가 필요하면 31GB로 두고, 정말 더 필요하면 **48GB 이상** (가급적 64GB+)까지 점프해야 압축 비활성화 손실을 상쇄할 수 있습니다. **32~47GB 구간은 전 구간이 안티패턴**입니다.\n\n**ES 권장 설정 및 검증**:\n\n```bash\n# jvm.options\n-Xms30g\n-Xmx30g          # 31GB가 아닌 30GB로 1GB 안전 마진 (메타스페이스, 정렬 오버헤드 고려)\n\n# 압축 oops 활성화 여부 확인\njcmd \u003CES_PID> VM.flags | grep -i CompressedOops\n# → -XX:+UseCompressedOops 가 보이면 OK\n\n# ES 시작 로그에서 확인\ngrep \"compressed ordinary object pointers\" \u002Fvar\u002Flog\u002Felasticsearch\u002F*.log\n# → \"heap size [29.8gb], compressed ordinary object pointers [true]\" 형태\n```\n\nJDK 15+에서는 `-XX:+UseCompressedClassPointers`까지 비활성화되면 추가 손실이 발생하므로, 위 검증 한 줄은 노드 부팅 시 반드시 확인해야 합니다.\n\n### Heap vs Off-Heap 구성 요소\n\n| 구성 요소 | 위치 | 크기 결정 요인 | 관리 방법 |\n|----------|------|-------------|----------|\n| Segment Readers (SegmentCoreReaders) | Heap | 열려 있는 세그먼트 수 | merge로 세그먼트 수 감소 |\n| Indexing Buffer | Heap | `indices.memory.index_buffer_size` (10%) | 설정값 조정 |\n| Query Cache (bitset) | Heap | `indices.queries.cache.size` (10%) | LRU 자동 eviction |\n| Request Cache | Heap | `indices.requests.cache.size` (1%) | 인덱스 refresh 시 무효화 |\n| Field Data | Heap | 필드 cardinality * 포인터 크기 | circuit breaker로 제한 |\n| Aggregation Buffers | Heap | 쿼리 복잡도, bucket 수 | request circuit breaker |\n| FST (Term Dictionary) | Off-Heap (mmap) | unique term 수, prefix 공유율 | page cache에 의존 |\n| Doc Values | Off-Heap (mmap) | 문서 수 * 필드당 바이트 | page cache에 의존 |\n| Postings Lists | Off-Heap (mmap) | 인덱스 총 크기 | page cache에 의존 |\n| BKD Tree | Off-Heap (mmap) | 숫자\u002Fgeo 필드 문서 수 | page cache에 의존 |\n| Stored Fields | Off-Heap (mmap) | `_source` 크기 합계 | page cache에 의존 |\n\n### Query Cache 동작 상세\n\nQuery cache는 세그먼트별 LRU bitset으로 구현됩니다. 모든 쿼리가 캐싱되지는 않습니다.\n\n```\nQuery Cache 적격 조건:\n  1. filter context에서 실행된 쿼리만 (query context는 캐시 불가)\n  2. 해당 쿼리가 5회 이상 실행됨 (history count >= 5)\n  3. 세그먼트의 문서 수가 10,000개 이상\n  4. 세그먼트가 전체 인덱스 문서의 3% 이상을 포함\n  5. TermQuery, MatchAllDocsQuery 등 비용이 낮은 쿼리는 제외\n\n캐시 구조 (세그먼트별):\n  Segment_0:\n    Query(\"status:active\") → BitSet [1,1,0,1,0,1,1,...] (문서 매칭 비트맵)\n    Query(\"price:[100 TO 500]\") → BitSet [0,1,1,0,0,1,0,...]\n\n  Segment_1:\n    Query(\"status:active\") → BitSet [1,0,1,1,0,0,1,...]\n    (다른 세그먼트이므로 별도 BitSet)\n\n무효화:\n  - 세그먼트가 merge되면 해당 세그먼트의 캐시 전체 무효화\n  - refresh로 새 세그먼트가 생기면 해당 세그먼트에는 캐시 없음\n  - LRU eviction: 메모리 한도 초과 시 가장 오래된 엔트리 제거\n```\n\n### Circuit Breakers\n\n| Circuit Breaker | 기본 한도 | 보호 대상 | 트리거 상황 |\n|----------------|----------|----------|-----------|\n| `fielddata` | Heap의 40% | field data 로드 | text 필드에 대한 집계\u002F정렬 |\n| `request` | Heap의 60% | 단일 요청 메모리 | 대규모 aggregation, 큰 결과셋 |\n| `in_flight_requests` | Heap의 100% | 전송 중인 요청 | 동시 요청 과다 |\n| `parent` | Heap의 95% | 전체 heap 사용량 | 여러 breaker 합산 초과 |\n| `accounting` | Heap의 100% | Lucene 세그먼트 메모리 | 세그먼트 과다 |\n\n```json\n\u002F\u002F Circuit breaker 설정 조정\nPUT \u002F_cluster\u002Fsettings\n{\n  \"persistent\": {\n    \"indices.breaker.fielddata.limit\": \"30%\",\n    \"indices.breaker.request.limit\": \"50%\",\n    \"indices.breaker.total.limit\": \"90%\"\n  }\n}\n```\n\n### Skip Lists (Postings 내부)\n\nPostings list 탐색을 가속하는 multi-level skip list 구조입니다.\n\n```\nSkip List 구조 (Postings List 가속)\n═══════════════════════════════════\n\nLevel 2:  1 ─────────────────────────── 97 ──────────────────── 193\n          │                              │                       │\nLevel 1:  1 ──────── 33 ──────── 65 ── 97 ──── 129 ──── 161 ── 193\n          │          │           │      │       │        │       │\nLevel 0:  1,2,3,...  33,34,35..  65,66  97,98   129,130  161,162 193,...\n          (DocIDs in postings list)\n\nadvance(150) 실행 과정:\n  1. Level 2: 1 → 97 (150 > 97, 계속)  → 193 (150 \u003C 193, Level 1로)\n  2. Level 1: 97 → 129 (150 > 129)     → 161 (150 \u003C 161, Level 0로)\n  3. Level 0: 129 → 130 → ... → 150 (찾음!)\n\nskip 없이 선형 탐색: 150 steps\nskip list 탐색:     ~15 steps (O(sqrt(N)))\n\nBooleanQuery에서의 활용:\n  AND(term_A, term_B): 짧은 리스트의 DocID로 긴 리스트를 advance()\n  → skip list 덕분에 긴 리스트 대부분을 건너뜀\n```\n\n### Block Encoding (FOR Delta Encoding)\n\nPostings list의 DocID는 Frame of Reference (FOR) delta encoding으로 압축됩니다.\n\n```\n원본 DocIDs:   [101, 105, 108, 115, 120, 133, 140, 145]\n\nStep 1 - Delta Encoding:\n  [101, 4, 3, 7, 5, 13, 7, 5]   ← 첫 값은 그대로, 나머지는 이전 값과의 차이\n\nStep 2 - Frame of Reference:\n  Block (128개 단위): 블록 내 최대 delta = 13\n  → 4 bits면 충분 (2^4 = 16 > 13)\n  → 128개 값 * 4 bits = 64 bytes (vs 원본 128 * 4 bytes = 512 bytes)\n  → 압축률: ~87.5%\n\nSIMD 최적화:\n  - 128개 정수를 한 블록으로 묶어 CPU SIMD 명령으로 일괄 디코딩\n  - vectorized bit-unpacking으로 높은 처리량\n  - Lucene의 ForUtil 클래스에서 구현\n```\n\n### Selective Filter가 BooleanQuery 성능을 극적으로 개선하는 이유\n\n```\n시나리오: 100만 문서 인덱스에서 검색\n\n쿼리 1 (filter 없음):\n  { \"match\": { \"title\": \"이어폰\" } }\n  → \"이어폰\" postings: 50,000 docs\n  → 50,000개 문서 전부 scoring 필요\n  → 소요: ~50ms\n\n쿼리 2 (선택적 filter 추가):\n  { \"bool\": {\n      \"must\": { \"match\": { \"title\": \"이어폰\" } },\n      \"filter\": { \"term\": { \"brand\": \"삼성\" } }\n  }}\n  → \"이어폰\" postings: 50,000 docs\n  → \"삼성\" filter bitset: 5,000 docs (캐시됨!)\n  → 교집합: 리드 쿼리가 짧은 리스트(5,000)를 순회하며 긴 리스트를 advance()\n  → scoring 대상: ~500 docs\n  → 소요: ~5ms (10x 개선!)\n\n핵심 메커니즘:\n  1. filter는 bitset으로 캐시되어 재사용 (scoring 오버헤드 없음)\n  2. BooleanQuery의 conjunction은 가장 짧은 postings list를 리드로 선택\n  3. skip list의 advance()로 긴 리스트의 대부분을 건너뜀\n  4. scoring은 교집합에 포함된 문서에 대해서만 수행\n```\n\n## 7. Lucene-ES Setting Mapping Reference\n\nES의 인덱스\u002F클러스터 설정이 Lucene 내부에서 어떤 메커니즘으로 구현되는지 종합 정리합니다.\n\n| ES Setting | 기본값 | Lucene 메커니즘 | 성능 영향 |\n|-----------|-------|----------------|----------|\n| `number_of_shards` | 1 | shard당 하나의 `IndexWriter` 인스턴스 | shard 수 = Lucene 인덱스 수. 과다 시 heap\u002FFD 낭비, 과소 시 병렬성 부족 |\n| `refresh_interval` | `\"1s\"` | `DirectoryReader.openIfChanged()` 호출 주기 | 짧으면 작은 세그먼트 다수 생성 → merge 부하. `\"-1\"`로 비활성화 가능 |\n| `merge.policy.max_merged_segment` | `\"5gb\"` | `TieredMergePolicy.maxMergedSegmentMB` | 큰 세그먼트는 merge 제외됨. 너무 낮으면 세그먼트 파편화 |\n| `merge.policy.segments_per_tier` | `10` | `TieredMergePolicy.segmentsPerTier` | 낮추면 merge 빈번 (I\u002FO 증가), 높이면 세그먼트 수 증가 |\n| `merge.policy.deletes_pct_allowed` | `33` | `TieredMergePolicy.deletesPctAllowed` | 삭제 비율 한도. 낮추면 삭제 문서가 빨리 정리됨 |\n| `merge.scheduler.max_thread_count` | `Math.max(1, Math.min(4, cores\u002F2))` | `ConcurrentMergeScheduler.maxThreadCount` | merge 병렬성. I\u002FO 바운드이므로 과다 스레드는 비효율 |\n| `sort.field` \u002F `sort.order` | (없음) | `IndexWriterConfig.indexSort` | 세그먼트 내부가 정렬됨. 동일 정렬의 쿼리에서 early termination 가능 |\n| `codec` | `\"default\"` | `Lucene99Codec` | `best_compression` 시 `DEFLATE` 사용 (stored fields 압축률 향상, CPU 비용 증가) |\n| `max_result_window` | `10000` | `TopDocsCollector` heap 크기 제한 | 깊은 페이징 방지. 초과 시 `search_after` 사용 |\n| `mapping.total_fields.limit` | `1000` | 세그먼트 메타데이터, 필드별 인덱스 구조 | 필드 과다 시 세그먼트 오버헤드 증가, mapping explosion |\n| `highlight.max_analyzed_offset` | `1000000` | `UnifiedHighlighter` 오프셋 탐색 범위 | 큰 문서의 highlight 시 메모리\u002FCPU 보호 |\n| `indices.memory.index_buffer_size` | `10%` | `IndexWriter`의 RAM buffer 총량 | indexing throughput에 영향. 대량 적재 시 증가 고려 |\n| `indices.queries.cache.size` | `10%` | LRU BitSet 캐시 (세그먼트별) | filter 쿼리 캐시. 높이면 반복 쿼리 가속, heap 사용 증가 |\n| `index.translog.durability` | `\"request\"` | 매 요청 `fsync` | `\"async\"` 시 배치 fsync로 인덱싱 성능 향상, 데이터 유실 위험 |\n| `index.translog.flush_threshold_size` | `\"512mb\"` | translog 크기 초과 시 Lucene commit 트리거 | 높이면 commit 빈도 감소, 노드 재시작 시 복구 시간 증가 |\n\n---\n\n**Remember**: Elasticsearch는 Lucene 위에 구축된 분산 시스템입니다. ES 성능 문제의 근본 원인은 대부분 Lucene 레벨에 있습니다 -- 세그먼트가 너무 많은지, 적절한 필드 타입을 사용하는지, filter context를 활용하는지, OS 페이지 캐시를 위한 메모리가 충분한지 확인하세요. `_profile` API와 `_explain` API는 Lucene 내부를 들여다보는 창입니다. 추측하지 말고, 측정하세요.\n",{"name":5,"description":7},"main","e9f37e996e3d2b1b6ac9c879e9dfba1223b597c3","archive\u002Fcomponents\u002Fsearch\u002Fskills\u002Flucene-internals",0,"https:\u002F\u002Fgithub.com\u002FDokkabei97\u002Fdokkabei-harness","https:\u002F\u002Fdokkabei97.github.io\u002Fdokkabei-harness\u002F","https:\u002F\u002Fgithub.com\u002FDokkabei97","Contact: wkdrn970@gmail.com","2026-10-29 06:49:16",{"source":8,"skillName":5,"commands":54,"prompt":64,"zipAvailable":65},[55,58,61],{"tool":56,"command":57},"npx","npx skills add Dokkabei97\u002Fdokkabei-harness --skill lucene-internals",{"tool":59,"command":60},"bunx","bunx skills add Dokkabei97\u002Fdokkabei-harness --skill lucene-internals",{"tool":62,"command":63},"pnpm","pnpm dlx skills add Dokkabei97\u002Fdokkabei-harness --skill lucene-internals","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FDokkabei97\u002Fdokkabei-harness\u002Fblob\u002Fmain\u002Farchive\u002Fcomponents\u002Fsearch\u002Fskills\u002Flucene-internals\u002FSKILL.md",true,[],[68,98,129,151,172,194],{"skillNo":69,"name":70,"nameZh":6,"description":71,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":72,"categories":73,"keywords":79,"publishedAt":39},"01M6QZQTNF815AWYMAMJ3B25GY","sync-claude-md","커밋·푸시·PR\u002FMR 직전에 이번 변경이 프로젝트 CLAUDE.md 를 낡게 만드는지 검토하고, 필요할 때만 갱신 diff 를 제안한다 — 아키텍처·디렉터리 구조, 새 통합\u002FMCP, 컨벤션, 빌드·CI·도구, 주요 의존성 변화가 대상. 해당 없으면 한 줄로 끝낸다.\nReviews whether pending changes make the project CLAUDE.md stale (architecture, integrations, conventions, build\u002FCI\u002Ftooling, major dependencies) and proposes a minimal update diff only when needed.\nUse when: \"CLAUDE.md 갱신 필요해?\", \"CLAUDE.md 동기화\", 커밋\u002F푸시\u002FMR 전에 구조·도구가 바뀐 변경을 정리할 때, sync CLAUDE.md, check CLAUDE.md before commit or PR.","https:\u002F\u002Fgithub.com\u002FDokkabei97\u002Fdokkabei-harness\u002Fblob\u002Fmain\u002Fplugins\u002Fworkflow\u002Fskills\u002Fsync-claude-md\u002FSKILL.md",[74],{"categoryNo":75,"categoryName":76,"taxonomyType":77,"taxonomyTypeDesc":78},"01JBSEEDCAT000000000000023","Skill与智能体开发","SCENARIO","使用场景",[80,81,82,83,84,85,86,87,88,89,30,90,91,92,93,94,95,96,97,21],"sync","claude md","sync claude md","MCP","commit","architecture","pr","update","ci","integrations","diff","only","minimal","project","make","reviews","pending","mr",{"skillNo":99,"name":100,"nameZh":6,"description":101,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":102,"categories":103,"keywords":110,"publishedAt":39},"01M6QZQEK94G00N955VQH9EFQN","spec-driven-dev","새 기능·프로젝트·큰 변경을 코드보다 스펙 먼저로 진행하는 게이트 워크플로(SPECIFY → PLAN → TASKS → IMPLEMENT) — 가정 명시, 측정 가능한 성공 기준, Always\u002FAsk\u002FNever 경계, 단계별 사람 검토로 범위 이탈과 재작업을 줄인다.\nSpec-before-code gated workflow for new features or significant changes: explicit assumptions, measurable success criteria, boundaries, and a human review between stages.\nUse when: \"스펙 먼저\", \"기능 명세\", \"요구사항 정리\", starting a new feature or project, a significant change with vague requirements. 단순 버그 수정·1~2줄 변경엔 불필요.","https:\u002F\u002Fgithub.com\u002FDokkabei97\u002Fdokkabei-harness\u002Fblob\u002Fmain\u002Fplugins\u002Fworkflow\u002Fskills\u002Fspec-driven-dev\u002FSKILL.md",[104,105],{"categoryNo":75,"categoryName":76,"taxonomyType":77,"taxonomyTypeDesc":78},{"categoryNo":106,"categoryName":107,"taxonomyType":108,"taxonomyTypeDesc":109},"01JBSEEDCAT000000000000030","开发工程师","PROFESSION","适用职业",[111,112,113,114,115,116,117,118,119,120,121,122,123,124,93,125,126,127,128,21],"spec","spec driven","dev","spec driven dev","driven","review","workflow","change","tasks","code","plan","ask","never","human","feature","for","vague","features",{"skillNo":130,"name":131,"nameZh":6,"description":132,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":133,"categories":134,"keywords":135,"publishedAt":39},"01M6QZQA9F6QVGTVDMJ28YQGDV","shipping-guide","프로덕션 배포 전후 가이드 — 배포 전 체크리스트, 피처 플래그 수명주기, 단계적 롤아웃과 진행\u002F보류\u002F롤백 임계값, 롤백 계획 템플릿, 배포 후 모니터링.\nProduction shipping guide: pre-launch checklist, feature-flag lifecycle, staged rollout with go\u002Fhold\u002Frollback thresholds, rollback plan template, post-launch monitoring.\nUse when: \"배포 준비\", \"릴리즈 전 점검\", \"롤아웃 계획\", \"롤백 계획\", preparing a production deploy, staged rollout, feature flags.","https:\u002F\u002Fgithub.com\u002FDokkabei97\u002Fdokkabei-harness\u002Fblob\u002Fmain\u002Fplugins\u002Fworkflow\u002Fskills\u002Fshipping-guide\u002FSKILL.md",[],[136,137,138,139,140,33,141,121,142,143,30,144,145,125,146,147,148,149,150,21],"shipping","guide","shipping guide","launch","monitoring","feature flags","template","rollback","rollout","flags","thresholds","post","with","pre-launch","rollback plan",{"skillNo":152,"name":153,"nameZh":6,"description":154,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":155,"categories":156,"keywords":157,"publishedAt":39},"01M6QZQ3M962PCWYM6YH62D76Z","retro","세션 회고·교훈 컴파운딩 — 이번 세션의 교정·실수·발견을 추출해 품질 기준(재현·일반화·판정 가능성)으로 거르고, 컨벤션 변화는 sync-claude-md 위임, 반복 실수는 tasks\u002Flessons.md(#가드-훅-후보 태그), 스킬 지식 갱신은 수정 제안으로 나눈다. 모든 적용은 승인 후.\nSession retrospective that turns corrections, mistakes, and discoveries into vetted lessons routed to CLAUDE.md sync, tasks\u002Flessons.md, or skill-edit proposals, with user approval before any write.\nUse when: \"회고\", \"레트로\", \"교훈 정리\", \"같은 실수 반복\", \"재발 방지 규칙\", retrospective, lessons learned, wrapping up a task, review, or loop. 여러 실행에 걸친 하네스 개선은 harness:evolve.","https:\u002F\u002Fgithub.com\u002FDokkabei97\u002Fdokkabei-harness\u002Fblob\u002Fmain\u002Fplugins\u002Fworkflow\u002Fskills\u002Fretro\u002FSKILL.md",[],[153,116,80,119,158,159,160,161,162,163,164,165,91,166,167,168,169,170,171,21],"run","harness","loop","evolve","write","edit","proposals","session","up","dry","learned","Session Retrospective","lessons","mistakes",{"skillNo":173,"name":174,"nameZh":6,"description":175,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":176,"categories":177,"keywords":179,"publishedAt":39},"01M6QZPPDATJ7DAGNP0JCXFGRV","project-rules","현재 프로젝트의 스택(빌드 파일 버전, 마이그레이션 도구, ORM 유무, ES 사용, git 호스트)을 감지해 프로젝트 루트 AGENTS.md 의 마커 블록(스택 사실 + 항상 적용되는 스페셜리스트 핵심 ≤15줄 — Claude Code·Codex·Antigravity 공통)과 CLAUDE.md 의 `@AGENTS.md` 연결, Claude 전용 경로 한정 .claude\u002Frules\u002F\u003Cstack>-specialist.md(해당 버전에 실제로 맞는 상세 함정)를 diff 로 제안하고, 스택 플러그인을 런타임별로 프로젝트 범위에서 켜는 법을 안내한다. 이전 버전 출력(CLAUDE.md 블록·specialist-core.md)은 AGENTS.md 로 이전을 제안. --check 는 버전 불일치·사라진 ID·크기 한도·연결 누락을 점검.\nDetects the project's stack and proposes a cross-runtime AGENTS.md block (stack facts + always-on specialist core) linked from CLAUDE.md via @AGENTS.md, plus Claude-only path-scoped specialist rules; migrates the older CLAUDE.md-block layout; --check audits drift.\nUse when: \"이 프로젝트 세팅\", \"프로젝트 규칙 생성\", \"AGENTS.md\u002FCLAUDE.md 점검\", project setup, generate project rules, audit AGENTS.md or CLAUDE.md drift.","https:\u002F\u002Fgithub.com\u002FDokkabei97\u002Fdokkabei-harness\u002Fblob\u002Fmain\u002Fplugins\u002Fworkflow\u002Fskills\u002Fproject-rules\u002FSKILL.md",[178],{"categoryNo":106,"categoryName":107,"taxonomyType":108,"taxonomyTypeDesc":109},[180,93,181,182,183,120,184,185,186,187,90,91,20,188,189,190,191,192,193,21],"Rules","project rules","core","generate","git","audit","stack","orm","drift","layout","runtime","-specialist","path","scoped",{"skillNo":195,"name":196,"nameZh":6,"description":197,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":198,"categories":199,"keywords":204,"publishedAt":39},"01M6QZPF3S8YAM27F297F6GVD7","post-merge","MR 머지 완료 후 Plane 이슈 종료와 Outline 문서 업데이트를 자동으로 처리하는 오케스트레이터 스킬입니다.\nissue-tracker와 document-latest 스킬을 연계 실행하여 머지 후 후속 작업을 일괄 처리합니다.\nOrchestrates post-merge follow-up after an MR is merged: chains the issue-tracker and document-latest skills to close the Plane issue and update Outline wiki docs in a single batch. Use when: an MR was just merged, closing tickets and syncing documentation after a merge, post-merge cleanup.","https:\u002F\u002Fgithub.com\u002FDokkabei97\u002Fdokkabei-harness\u002Fblob\u002Fmain\u002Fplugins\u002Fworkflow\u002Fskills\u002Fpost-merge\u002FSKILL.md",[200,203],{"categoryNo":201,"categoryName":202,"taxonomyType":77,"taxonomyTypeDesc":78},"01JBSEEDCAT000000000000002","文档处理",{"categoryNo":75,"categoryName":76,"taxonomyType":77,"taxonomyTypeDesc":78},[38,205,147,206,207,87,208,209,210,166,211,212,213,214,215,216,217,218,97,21],"post merge","documentation","cleanup","batch","wiki","just","issue","tracker","close","closing","follow-up","true","plane","single"]