[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6QYWDT5HXDZ99FDNSWP5HPV":3,"skill-same:01M6QYWDT5HXDZ99FDNSWP5HPV":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},"01M6QYWDT5HXDZ99FDNSWP5HPV","kotlin-es-client-patterns",null,"Use this skill when implementing Elasticsearch integration in Kotlin or Python applications. Covers client setup, search implementation, bulk indexing, testing, and common mistakes with the elasticsearch-java v8 client and elasticsearch-py.","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\u002Fkotlin-es-client-patterns\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38],"patterns","kotlin es client patterns","client","es","kotlin","applications","elasticsearch","common","use","search","testing","indexing","java","bulk","with","search implementation","implementing","mistakes","when","python","2026-11-10 10:12:30",false,"---\nname: kotlin-es-client-patterns\ndescription: Use this skill when implementing Elasticsearch integration in Kotlin or Python applications. Covers client setup, search implementation, bulk indexing, testing, and common mistakes with the elasticsearch-java v8 client and elasticsearch-py.\n---\n\n# Kotlin + Elasticsearch Client Patterns\n\nKotlin 기반 Elasticsearch 클라이언트 구현 패턴을 제공합니다. elasticsearch-java v8 (co.elastic.clients) 중심으로, coroutine 통합, 테스트 전략, 그리고 Python 서브스택 패턴까지 다룹니다.\n\n## When to Activate\n\n- Elasticsearch Java\u002FKotlin 클라이언트 설정 또는 업그레이드 시\n- 검색 API 구현 또는 쿼리 빌더 작성 시\n- Bulk indexing 파이프라인 구축 또는 성능 튜닝 시\n- ES 관련 테스트 코드 작성 또는 리팩토링 시\n- Kotlin coroutine과 ES 클라이언트 통합 시\n- Python elasticsearch-py 클라이언트 사용 시\n\n## 1. Client Setup\n\n### elasticsearch-java v8 Configuration\n\n```kotlin\n@Configuration\nclass ElasticsearchConfig(\n    @Value(\"\\${elasticsearch.hosts}\") private val hosts: List\u003CString>,\n    @Value(\"\\${elasticsearch.username}\") private val username: String,\n    @Value(\"\\${elasticsearch.password}\") private val password: String\n) {\n    @Bean\n    fun elasticsearchClient(): ElasticsearchClient {\n        \u002F\u002F RestClient (low-level HTTP transport)\n        val restClient = RestClient.builder(\n            *hosts.map { HttpHost.create(it) }.toTypedArray()\n        ).setHttpClientConfigCallback { httpBuilder ->\n            httpBuilder.setDefaultCredentialsProvider(\n                BasicCredentialsProvider().apply {\n                    setCredentials(\n                        AuthScope.ANY,\n                        UsernamePasswordCredentials(username, password)\n                    )\n                }\n            )\n            \u002F\u002F 커넥션 풀 설정\n            httpBuilder.setMaxConnTotal(100)\n            httpBuilder.setMaxConnPerRoute(20)\n        }.setRequestConfigCallback { requestBuilder ->\n            requestBuilder\n                .setConnectTimeout(5_000)\n                .setSocketTimeout(60_000)\n        }.build()\n\n        \u002F\u002F JSON mapper transport\n        val transport = RestClientTransport(restClient, JacksonJsonpMapper())\n        return ElasticsearchClient(transport)\n    }\n}\n```\n\n### Sniffing (노드 자동 감지)\n\n```kotlin\n\u002F\u002F Sniffer로 클러스터 노드 자동 감지\nval sniffer = Sniffer.builder(restClient)\n    .setSniffIntervalMillis(60_000)        \u002F\u002F 1분 간격 스니핑\n    .setSniffAfterFailureDelayMillis(5_000) \u002F\u002F 실패 후 5초 후 재스니핑\n    .build()\n\n\u002F\u002F 애플리케이션 종료 시 반드시 close\n@PreDestroy\nfun cleanup() {\n    sniffer.close()\n    restClient.close()\n}\n```\n\n### Retry & Backoff\n\n```kotlin\n\u002F\u002F RestClient 레벨 retry는 내장 (max 3회 기본)\n\u002F\u002F 애플리케이션 레벨 retry는 직접 구현\nsuspend fun \u003CT> withRetry(\n    maxAttempts: Int = 3,\n    initialDelay: Long = 100,\n    maxDelay: Long = 5000,\n    block: suspend () -> T\n): T {\n    var lastException: Exception? = null\n    var delay = initialDelay\n\n    repeat(maxAttempts) { attempt ->\n        try {\n            return block()\n        } catch (e: ElasticsearchException) {\n            if (e.status() == 429) { \u002F\u002F Too Many Requests\n                lastException = e\n                delay(delay)\n                delay = (delay * 2).coerceAtMost(maxDelay)\n            } else throw e\n        } catch (e: IOException) {\n            lastException = e\n            delay(delay)\n            delay = (delay * 2).coerceAtMost(maxDelay)\n        }\n    }\n    throw lastException!!\n}\n```\n\n### Health Check\n\n```kotlin\n@Component\nclass ElasticsearchHealthIndicator(\n    private val client: ElasticsearchClient\n) : HealthIndicator {\n    override fun health(): Health {\n        return try {\n            val response = client.cluster().health()\n            when (response.status()) {\n                HealthStatus.Green -> Health.up()\n                    .withDetail(\"status\", \"green\")\n                    .withDetail(\"numberOfNodes\", response.numberOfNodes())\n                    .build()\n                HealthStatus.Yellow -> Health.up()\n                    .withDetail(\"status\", \"yellow\")\n                    .build()\n                HealthStatus.Red -> Health.down()\n                    .withDetail(\"status\", \"red\")\n                    .build()\n            }\n        } catch (e: Exception) {\n            Health.down(e).build()\n        }\n    }\n}\n```\n\n### Legacy: Java High Level REST Client\n\n```kotlin\n\u002F\u002F ES 7.x 이하 레거시 프로젝트용 (deprecated in 7.15+)\n\u002F\u002F 마이그레이션 계획 수립 필요\nval client = RestHighLevelClient(\n    RestClient.builder(HttpHost(\"localhost\", 9200, \"http\"))\n)\n\u002F\u002F 주의: 8.x에서 제거 예정. 신규 코드는 elasticsearch-java 사용\n```\n\n## 2. Search Implementation\n\n### Typesafe Query Builder API\n\n```kotlin\n\u002F\u002F elasticsearch-java v8의 typesafe builder\nfun searchProducts(keyword: String, category: String?, priceRange: IntRange?): List\u003CProduct> {\n    val response = client.search({ s ->\n        s.index(\"products\")\n            .query { q ->\n                q.bool { b ->\n                    \u002F\u002F must: full-text 검색\n                    b.must { m ->\n                        m.multiMatch { mm ->\n                            mm.query(keyword)\n                                .fields(\"title^3\", \"title.search^2\", \"description\")\n                                .type(TextQueryType.BestFields)\n                        }\n                    }\n                    \u002F\u002F filter: exact match (스코어 무관)\n                    category?.let { cat ->\n                        b.filter { f -> f.term { t -> t.field(\"category\").value(cat) } }\n                    }\n                    priceRange?.let { range ->\n                        b.filter { f ->\n                            f.range { r ->\n                                r.field(\"price\")\n                                    .gte(JsonData.of(range.first))\n                                    .lte(JsonData.of(range.last))\n                            }\n                        }\n                    }\n                    b\n                }\n            }\n            .source { src ->\n                src.filter { f -> f.includes(\"title\", \"price\", \"category\", \"thumbnail_url\") }\n            }\n            .size(20)\n    }, Product::class.java)\n\n    return response.hits().hits().mapNotNull { it.source() }\n}\n```\n\n### Raw JSON Query (복잡한 쿼리)\n\n```kotlin\n\u002F\u002F 매우 복잡한 쿼리는 JSON 직접 사용 가능\nfun searchWithRawJson(queryJson: String): SearchResponse\u003CJsonData> {\n    val reader = StringReader(queryJson)\n    val request = SearchRequest.of { s ->\n        s.index(\"products\").withJson(reader)\n    }\n    return client.search(request, JsonData::class.java)\n}\n```\n\n### Scroll vs search_after Pagination\n\n```kotlin\n\u002F\u002F search_after (권장: stateless, 병렬 가능)\nfun searchAfterPagination(keyword: String, searchAfter: List\u003CFieldValue>?): SearchPage {\n    val response = client.search({ s ->\n        s.index(\"products\")\n            .query { q -> q.match { m -> m.field(\"title\").query(keyword) } }\n            .sort { sort -> sort.field { f -> f.field(\"_score\").order(SortOrder.Desc) } }\n            .sort { sort -> sort.field { f -> f.field(\"_id\").order(SortOrder.Asc) } }\n            .size(20)\n            .apply {\n                searchAfter?.let { sa -> searchAfter(sa) }\n            }\n    }, Product::class.java)\n\n    val hits = response.hits().hits()\n    val lastSort = hits.lastOrNull()?.sort()\n\n    return SearchPage(\n        items = hits.mapNotNull { it.source() },\n        nextSearchAfter = lastSort,\n        total = response.hits().total()?.value() ?: 0\n    )\n}\n```\n\n### Multi-Search (msearch) for Parallel Queries\n\n```kotlin\n\u002F\u002F 여러 쿼리를 하나의 HTTP 요청으로 실행\nfun parallelSearch(keyword: String): AggregatedSearchResult {\n    val response = client.msearch({ ms ->\n        ms.searches(\n            \u002F\u002F 상품 검색\n            { rs -> rs\n                .header { h -> h.index(\"products\") }\n                .body { b -> b.query { q -> q.match { m -> m.field(\"title\").query(keyword) } }.size(10) }\n            },\n            \u002F\u002F 카테고리 집계\n            { rs -> rs\n                .header { h -> h.index(\"products\") }\n                .body { b ->\n                    b.size(0).aggregations(\"categories\") { a ->\n                        a.terms { t -> t.field(\"category\").size(10) }\n                    }\n                }\n            },\n            \u002F\u002F 브랜드 추천\n            { rs -> rs\n                .header { h -> h.index(\"brands\") }\n                .body { b -> b.query { q -> q.match { m -> m.field(\"name\").query(keyword) } }.size(5) }\n            }\n        )\n    }, JsonData::class.java)\n\n    \u002F\u002F 각 응답 개별 처리\n    val productHits = response.responses()[0].result().hits()\n    val categoryAggs = response.responses()[1].result().aggregations()\n    val brandHits = response.responses()[2].result().hits()\n\n    return AggregatedSearchResult(productHits, categoryAggs, brandHits)\n}\n```\n\n### Kotlin Coroutine Integration\n\n```kotlin\n\u002F\u002F ES 클라이언트는 동기 API이므로 suspend fun wrapper 필요\n@Service\nclass SearchService(\n    private val client: ElasticsearchClient,\n    private val searchDispatcher: CoroutineDispatcher = Dispatchers.IO\n) {\n    \u002F\u002F IO 디스패처에서 블로킹 호출 실행\n    suspend fun search(request: SearchRequest): SearchResponse\u003CProduct> =\n        withContext(searchDispatcher) {\n            client.search(request, Product::class.java)\n        }\n\n    \u002F\u002F 여러 인덱스 병렬 검색\n    suspend fun parallelSearch(keyword: String): CombinedResult = coroutineScope {\n        val products = async { searchProducts(keyword) }\n        val suggestions = async { searchSuggestions(keyword) }\n        val relatedKeywords = async { findRelatedKeywords(keyword) }\n\n        CombinedResult(\n            products = products.await(),\n            suggestions = suggestions.await(),\n            relatedKeywords = relatedKeywords.await()\n        )\n    }\n}\n```\n\n## 3. Bulk Indexing\n\n### BulkProcessor Pattern\n\n```kotlin\n\u002F\u002F elasticsearch-java v8 BulkIngester\n@Component\nclass ProductIndexer(\n    private val client: ElasticsearchClient\n) {\n    private val bulkIngester = BulkIngester.of { b ->\n        b.client(client)\n            .maxOperations(500)         \u002F\u002F 500건마다 flush\n            .flushInterval(5, TimeUnit.SECONDS) \u002F\u002F 또는 5초마다\n            .maxConcurrentRequests(2)   \u002F\u002F 동시 2개 요청\n            .listener(object : BulkListener\u003CAny> {\n                override fun beforeBulk(executionId: Long, request: BulkRequest, contexts: List\u003CAny>) {\n                    logger.info(\"Bulk #{}: {} operations\", executionId, request.operations().size)\n                }\n                override fun afterBulk(executionId: Long, request: BulkRequest, contexts: List\u003CAny>, response: BulkResponse) {\n                    if (response.errors()) {\n                        response.items().filter { it.error() != null }.forEach { item ->\n                            logger.error(\"Bulk item error: index={}, id={}, error={}\",\n                                item.index(), item.id(), item.error()?.reason())\n                        }\n                    }\n                }\n                override fun afterBulk(executionId: Long, request: BulkRequest, contexts: List\u003CAny>, failure: Throwable) {\n                    logger.error(\"Bulk #{} failed\", executionId, failure)\n                }\n            })\n    }\n\n    fun indexProduct(product: Product) {\n        bulkIngester.add { op ->\n            op.index { idx ->\n                idx.index(\"products\").id(product.id).document(product)\n            }\n        }\n    }\n\n    @PreDestroy\n    fun close() = bulkIngester.close()\n}\n```\n\n### Coroutine-Based Indexing Pipeline\n\n```kotlin\n\u002F\u002F Channel 기반 비동기 인덱싱 파이프라인\nclass CoroutineBulkIndexer(\n    private val client: ElasticsearchClient,\n    private val batchSize: Int = 500,\n    private val flushIntervalMs: Long = 5000\n) {\n    private val channel = Channel\u003CBulkOperation>(capacity = 10_000)\n\n    \u002F\u002F producer: 문서 투입\n    suspend fun add(operation: BulkOperation) {\n        channel.send(operation)\n    }\n\n    \u002F\u002F consumer: 배치 처리\n    fun start(scope: CoroutineScope) = scope.launch(Dispatchers.IO) {\n        val buffer = mutableListOf\u003CBulkOperation>()\n        var lastFlush = System.currentTimeMillis()\n\n        for (op in channel) {\n            buffer.add(op)\n            val elapsed = System.currentTimeMillis() - lastFlush\n\n            if (buffer.size >= batchSize || elapsed >= flushIntervalMs) {\n                flush(buffer.toList())\n                buffer.clear()\n                lastFlush = System.currentTimeMillis()\n            }\n        }\n        \u002F\u002F 채널 종료 시 남은 버퍼 flush\n        if (buffer.isNotEmpty()) flush(buffer)\n    }\n\n    private suspend fun flush(operations: List\u003CBulkOperation>) {\n        try {\n            val response = client.bulk { b -> b.operations(operations) }\n            if (response.errors()) {\n                val failures = response.items().filter { it.error() != null }\n                logger.error(\"Bulk indexing partial failure: {} \u002F {} failed\",\n                    failures.size, operations.size)\n                \u002F\u002F 실패 건 재시도 또는 DLQ 저장\n                handleFailures(failures, operations)\n            }\n        } catch (e: Exception) {\n            logger.error(\"Bulk request failed entirely\", e)\n            \u002F\u002F 전체 실패 시 재시도 큐로 전송\n        }\n    }\n}\n```\n\n### Struct-to-Document Serialization\n\n```kotlin\n\u002F\u002F Jackson 직렬화 설정\n@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy::class)\ndata class ProductDocument(\n    @JsonProperty(\"id\") val id: String,\n    @JsonProperty(\"title\") val title: String,\n    @JsonProperty(\"price\") val price: Int,\n    @JsonProperty(\"category\") val category: String,\n    @JsonProperty(\"tags\") val tags: List\u003CString>,\n    @JsonProperty(\"created_at\") val createdAt: Instant,\n    @JsonIgnore val internalMemo: String? = null \u002F\u002F ES에 인덱싱하지 않음\n) {\n    companion object {\n        fun from(product: Product): ProductDocument = ProductDocument(\n            id = product.id,\n            title = product.title,\n            price = product.price,\n            category = product.category.code,\n            tags = product.tags.map { it.name },\n            createdAt = product.createdAt\n        )\n    }\n}\n```\n\n## 4. Testing\n\n### @SpringBootTest with Testcontainers\n\n```kotlin\n@SpringBootTest\n@Testcontainers\nclass ProductSearchServiceTest {\n\n    companion object {\n        @Container\n        @JvmStatic\n        val elasticsearch = ElasticsearchContainer(\n            DockerImageName.parse(\"docker.elastic.co\u002Felasticsearch\u002Felasticsearch:8.12.0\")\n        ).apply {\n            withEnv(\"discovery.type\", \"single-node\")\n            withEnv(\"xpack.security.enabled\", \"false\")\n            withEnv(\"ES_JAVA_OPTS\", \"-Xms512m -Xmx512m\")\n        }\n\n        @DynamicPropertySource\n        @JvmStatic\n        fun overrideProperties(registry: DynamicPropertyRegistry) {\n            registry.add(\"elasticsearch.hosts\") { listOf(elasticsearch.httpHostAddress) }\n        }\n    }\n\n    @Autowired\n    lateinit var searchService: ProductSearchService\n\n    @Autowired\n    lateinit var client: ElasticsearchClient\n\n    @BeforeEach\n    fun setup() {\n        \u002F\u002F 테스트 인덱스 생성 및 fixture 투입\n        createTestIndex()\n        indexTestDocuments()\n        \u002F\u002F 인덱싱 후 refresh 필수 (테스트에서는 즉시 검색 가능하도록)\n        client.indices().refresh { r -> r.index(\"products\") }\n    }\n\n    @Test\n    fun `상품 검색 시 제목 매칭 결과 반환`() {\n        val results = searchService.searchProducts(\"무선 이어폰\", null, null)\n        assertThat(results).isNotEmpty\n        assertThat(results.first().title).contains(\"이어폰\")\n    }\n\n    @AfterEach\n    fun cleanup() {\n        client.indices().delete { d -> d.index(\"products\") }\n    }\n}\n```\n\n### MockK for Unit Tests\n\n```kotlin\nclass SearchServiceUnitTest {\n\n    private val client: ElasticsearchClient = mockk()\n    private val service = SearchService(client)\n\n    @Test\n    fun `검색 결과가 없을 때 빈 리스트 반환`() {\n        \u002F\u002F Given\n        val emptyResponse = mockk\u003CSearchResponse\u003CProduct>> {\n            every { hits() } returns mockk {\n                every { hits() } returns emptyList()\n                every { total() } returns mockk { every { value() } returns 0 }\n            }\n        }\n        every { client.search(any\u003CSearchRequest>(), Product::class.java) } returns emptyResponse\n\n        \u002F\u002F When\n        val result = service.searchProducts(\"존재하지않는키워드\")\n\n        \u002F\u002F Then\n        assertThat(result).isEmpty()\n        verify(exactly = 1) { client.search(any\u003CSearchRequest>(), Product::class.java) }\n    }\n}\n```\n\n### Search Test Fixtures\n\n```kotlin\nobject SearchTestFixtures {\n    fun productDocuments(): List\u003CProduct> = listOf(\n        Product(id = \"1\", title = \"삼성 무선 이어폰 버즈3\", price = 150000, category = \"electronics\"),\n        Product(id = \"2\", title = \"애플 에어팟 프로 2세대\", price = 320000, category = \"electronics\"),\n        Product(id = \"3\", title = \"소니 노이즈캔슬링 헤드폰\", price = 280000, category = \"electronics\"),\n        Product(id = \"4\", title = \"무선 충전기 고속\", price = 25000, category = \"accessories\"),\n    )\n\n    \u002F\u002F 매핑 JSON (테스트용 간소화 버전)\n    val productMapping = \"\"\"\n    {\n        \"mappings\": {\n            \"properties\": {\n                \"title\": { \"type\": \"text\", \"analyzer\": \"standard\" },\n                \"price\": { \"type\": \"integer\" },\n                \"category\": { \"type\": \"keyword\" }\n            }\n        }\n    }\n    \"\"\".trimIndent()\n}\n```\n\n### Benchmark Pattern\n\n```kotlin\n\u002F\u002F JMH를 활용한 검색 성능 벤치마크\n@State(Scope.Benchmark)\n@BenchmarkMode(Mode.AverageTime)\n@OutputTimeUnit(TimeUnit.MILLISECONDS)\nopen class SearchBenchmark {\n    private lateinit var client: ElasticsearchClient\n\n    @Setup\n    fun setup() { \u002F* ES 연결 및 테스트 데이터 준비 *\u002F }\n\n    @Benchmark\n    fun searchSingleMatch(bh: Blackhole) {\n        val response = client.search({ s ->\n            s.index(\"products\").query { q -> q.match { m -> m.field(\"title\").query(\"이어폰\") } }\n        }, Product::class.java)\n        bh.consume(response)\n    }\n\n    @Benchmark\n    fun searchBoolWithFilter(bh: Blackhole) {\n        val response = client.search({ s ->\n            s.index(\"products\").query { q ->\n                q.bool { b ->\n                    b.must { m -> m.match { mt -> mt.field(\"title\").query(\"이어폰\") } }\n                    b.filter { f -> f.term { t -> t.field(\"category\").value(\"electronics\") } }\n                    b\n                }\n            }\n        }, Product::class.java)\n        bh.consume(response)\n    }\n}\n```\n\n## 5. Common Mistakes\n\n| Mistake | 문제 | Fix | Severity |\n|---------|------|-----|----------|\n| Response 미닫기 | 커넥션 풀 고갈, 메모리 누수 | `use {}` 또는 `try-finally`로 close 보장 | **Critical** |\n| `isError()` 무시 | 부분 실패 감지 못함 | bulk response에서 `errors()` 확인 | **High** |\n| 문자열 연결로 쿼리 생성 | injection 위험, 유지보수 불가 | builder API 또는 parameterized query 사용 | **Critical** |\n| timeout context 미설정 | 느린 쿼리가 스레드 점유 | `requestTimeout`, coroutine `withTimeout` 적용 | **High** |\n| bulk flush 동기 대기 | 호출 스레드 블로킹 | coroutine 또는 비동기 listener 활용 | **Medium** |\n| `_source` 필터링 미사용 | 불필요한 필드까지 전송 | `source(includes)` 로 필요 필드만 조회 | **Medium** |\n| `from\u002Fsize` 깊은 페이징 | 10,000건 이상 시 성능 급락 | `search_after` 사용 | **High** |\n| 인덱싱 후 refresh 없이 검색 | 테스트에서 결과 누락 | `indices().refresh()` 호출 (테스트 시) | **Medium** |\n\n```kotlin\n\u002F\u002F BAD: response 미닫기\nval response = client.search(request, Product::class.java)\n\u002F\u002F 응답 처리 중 예외 시 리소스 누수\n\n\u002F\u002F GOOD: timeout과 함께 안전하게 처리\nsuspend fun safeSearch(request: SearchRequest): List\u003CProduct> =\n    withContext(Dispatchers.IO) {\n        withTimeout(10_000) { \u002F\u002F 10초 타임아웃\n            val response = client.search(request, Product::class.java)\n            response.hits().hits().mapNotNull { it.source() }\n        }\n    }\n```\n\n## 6. Python Subsection (elasticsearch-py)\n\n서브 기술 스택인 Python에서의 ES 클라이언트 패턴.\n\n### AsyncElasticsearch Setup\n\n```python\nfrom elasticsearch import AsyncElasticsearch\n\nes = AsyncElasticsearch(\n    hosts=[\"http:\u002F\u002Fes-host:9200\"],\n    basic_auth=(\"user\", \"password\"),\n    max_retries=3,\n    retry_on_timeout=True,\n    request_timeout=30,\n)\n\nasync def search_products(keyword: str) -> list[dict]:\n    response = await es.search(\n        index=\"products\",\n        body={\n            \"query\": {\"match\": {\"title\": keyword}},\n            \"size\": 20,\n            \"_source\": [\"title\", \"price\", \"category\"],\n        },\n    )\n    return [hit[\"_source\"] for hit in response[\"hits\"][\"hits\"]]\n\n# 애플리케이션 종료 시 반드시 close\nasync def shutdown():\n    await es.close()\n```\n\n### helpers.bulk & scan\n\n```python\nfrom elasticsearch.helpers import async_bulk, async_scan\n\n# Bulk 인덱싱\nasync def bulk_index(documents: list[dict]):\n    actions = [\n        {\n            \"_index\": \"products\",\n            \"_id\": doc[\"id\"],\n            \"_source\": doc,\n        }\n        for doc in documents\n    ]\n    success, errors = await async_bulk(es, actions, chunk_size=500, raise_on_error=False)\n    if errors:\n        logger.error(f\"Bulk indexing errors: {len(errors)} failures\")\n\n# Scan (전체 문서 순회, scroll 대체)\nasync def export_all_products():\n    async for doc in async_scan(\n        es,\n        index=\"products\",\n        query={\"query\": {\"match_all\": {}}},\n        scroll=\"5m\",\n        size=1000,\n    ):\n        yield doc[\"_source\"]\n```\n\n### Python 주의사항\n\n| Mistake | Fix |\n|---------|-----|\n| 동기 `Elasticsearch` 클라이언트를 async 앱에서 사용 | `AsyncElasticsearch` 사용 |\n| `helpers.bulk`에서 `raise_on_error=True` (기본값) | `False`로 변경 후 에러 별도 처리 |\n| `scan` helper에서 `scroll` 시간 너무 길게 설정 | `\"5m\"` 이하, 처리 속도에 맞게 |\n| `body` dict를 수동 구성 시 오타 | `elasticsearch-dsl` 라이브러리로 builder 패턴 |\n\n---\n\n**Remember**: ES 클라이언트는 thread-safe하지만, 요청당 리소스 관리는 필수입니다. 커넥션 풀 크기, timeout, retry 정책을 운영 환경에 맞게 반드시 튜닝하세요.\n","# Kotlin + Elasticsearch Client Patterns\n\nKotlin 기반 Elasticsearch 클라이언트 구현 패턴을 제공합니다. elasticsearch-java v8 (co.elastic.clients) 중심으로, coroutine 통합, 테스트 전략, 그리고 Python 서브스택 패턴까지 다룹니다.\n\n## When to Activate\n\n- Elasticsearch Java\u002FKotlin 클라이언트 설정 또는 업그레이드 시\n- 검색 API 구현 또는 쿼리 빌더 작성 시\n- Bulk indexing 파이프라인 구축 또는 성능 튜닝 시\n- ES 관련 테스트 코드 작성 또는 리팩토링 시\n- Kotlin coroutine과 ES 클라이언트 통합 시\n- Python elasticsearch-py 클라이언트 사용 시\n\n## 1. Client Setup\n\n### elasticsearch-java v8 Configuration\n\n```kotlin\n@Configuration\nclass ElasticsearchConfig(\n    @Value(\"\\${elasticsearch.hosts}\") private val hosts: List\u003CString>,\n    @Value(\"\\${elasticsearch.username}\") private val username: String,\n    @Value(\"\\${elasticsearch.password}\") private val password: String\n) {\n    @Bean\n    fun elasticsearchClient(): ElasticsearchClient {\n        \u002F\u002F RestClient (low-level HTTP transport)\n        val restClient = RestClient.builder(\n            *hosts.map { HttpHost.create(it) }.toTypedArray()\n        ).setHttpClientConfigCallback { httpBuilder ->\n            httpBuilder.setDefaultCredentialsProvider(\n                BasicCredentialsProvider().apply {\n                    setCredentials(\n                        AuthScope.ANY,\n                        UsernamePasswordCredentials(username, password)\n                    )\n                }\n            )\n            \u002F\u002F 커넥션 풀 설정\n            httpBuilder.setMaxConnTotal(100)\n            httpBuilder.setMaxConnPerRoute(20)\n        }.setRequestConfigCallback { requestBuilder ->\n            requestBuilder\n                .setConnectTimeout(5_000)\n                .setSocketTimeout(60_000)\n        }.build()\n\n        \u002F\u002F JSON mapper transport\n        val transport = RestClientTransport(restClient, JacksonJsonpMapper())\n        return ElasticsearchClient(transport)\n    }\n}\n```\n\n### Sniffing (노드 자동 감지)\n\n```kotlin\n\u002F\u002F Sniffer로 클러스터 노드 자동 감지\nval sniffer = Sniffer.builder(restClient)\n    .setSniffIntervalMillis(60_000)        \u002F\u002F 1분 간격 스니핑\n    .setSniffAfterFailureDelayMillis(5_000) \u002F\u002F 실패 후 5초 후 재스니핑\n    .build()\n\n\u002F\u002F 애플리케이션 종료 시 반드시 close\n@PreDestroy\nfun cleanup() {\n    sniffer.close()\n    restClient.close()\n}\n```\n\n### Retry & Backoff\n\n```kotlin\n\u002F\u002F RestClient 레벨 retry는 내장 (max 3회 기본)\n\u002F\u002F 애플리케이션 레벨 retry는 직접 구현\nsuspend fun \u003CT> withRetry(\n    maxAttempts: Int = 3,\n    initialDelay: Long = 100,\n    maxDelay: Long = 5000,\n    block: suspend () -> T\n): T {\n    var lastException: Exception? = null\n    var delay = initialDelay\n\n    repeat(maxAttempts) { attempt ->\n        try {\n            return block()\n        } catch (e: ElasticsearchException) {\n            if (e.status() == 429) { \u002F\u002F Too Many Requests\n                lastException = e\n                delay(delay)\n                delay = (delay * 2).coerceAtMost(maxDelay)\n            } else throw e\n        } catch (e: IOException) {\n            lastException = e\n            delay(delay)\n            delay = (delay * 2).coerceAtMost(maxDelay)\n        }\n    }\n    throw lastException!!\n}\n```\n\n### Health Check\n\n```kotlin\n@Component\nclass ElasticsearchHealthIndicator(\n    private val client: ElasticsearchClient\n) : HealthIndicator {\n    override fun health(): Health {\n        return try {\n            val response = client.cluster().health()\n            when (response.status()) {\n                HealthStatus.Green -> Health.up()\n                    .withDetail(\"status\", \"green\")\n                    .withDetail(\"numberOfNodes\", response.numberOfNodes())\n                    .build()\n                HealthStatus.Yellow -> Health.up()\n                    .withDetail(\"status\", \"yellow\")\n                    .build()\n                HealthStatus.Red -> Health.down()\n                    .withDetail(\"status\", \"red\")\n                    .build()\n            }\n        } catch (e: Exception) {\n            Health.down(e).build()\n        }\n    }\n}\n```\n\n### Legacy: Java High Level REST Client\n\n```kotlin\n\u002F\u002F ES 7.x 이하 레거시 프로젝트용 (deprecated in 7.15+)\n\u002F\u002F 마이그레이션 계획 수립 필요\nval client = RestHighLevelClient(\n    RestClient.builder(HttpHost(\"localhost\", 9200, \"http\"))\n)\n\u002F\u002F 주의: 8.x에서 제거 예정. 신규 코드는 elasticsearch-java 사용\n```\n\n## 2. Search Implementation\n\n### Typesafe Query Builder API\n\n```kotlin\n\u002F\u002F elasticsearch-java v8의 typesafe builder\nfun searchProducts(keyword: String, category: String?, priceRange: IntRange?): List\u003CProduct> {\n    val response = client.search({ s ->\n        s.index(\"products\")\n            .query { q ->\n                q.bool { b ->\n                    \u002F\u002F must: full-text 검색\n                    b.must { m ->\n                        m.multiMatch { mm ->\n                            mm.query(keyword)\n                                .fields(\"title^3\", \"title.search^2\", \"description\")\n                                .type(TextQueryType.BestFields)\n                        }\n                    }\n                    \u002F\u002F filter: exact match (스코어 무관)\n                    category?.let { cat ->\n                        b.filter { f -> f.term { t -> t.field(\"category\").value(cat) } }\n                    }\n                    priceRange?.let { range ->\n                        b.filter { f ->\n                            f.range { r ->\n                                r.field(\"price\")\n                                    .gte(JsonData.of(range.first))\n                                    .lte(JsonData.of(range.last))\n                            }\n                        }\n                    }\n                    b\n                }\n            }\n            .source { src ->\n                src.filter { f -> f.includes(\"title\", \"price\", \"category\", \"thumbnail_url\") }\n            }\n            .size(20)\n    }, Product::class.java)\n\n    return response.hits().hits().mapNotNull { it.source() }\n}\n```\n\n### Raw JSON Query (복잡한 쿼리)\n\n```kotlin\n\u002F\u002F 매우 복잡한 쿼리는 JSON 직접 사용 가능\nfun searchWithRawJson(queryJson: String): SearchResponse\u003CJsonData> {\n    val reader = StringReader(queryJson)\n    val request = SearchRequest.of { s ->\n        s.index(\"products\").withJson(reader)\n    }\n    return client.search(request, JsonData::class.java)\n}\n```\n\n### Scroll vs search_after Pagination\n\n```kotlin\n\u002F\u002F search_after (권장: stateless, 병렬 가능)\nfun searchAfterPagination(keyword: String, searchAfter: List\u003CFieldValue>?): SearchPage {\n    val response = client.search({ s ->\n        s.index(\"products\")\n            .query { q -> q.match { m -> m.field(\"title\").query(keyword) } }\n            .sort { sort -> sort.field { f -> f.field(\"_score\").order(SortOrder.Desc) } }\n            .sort { sort -> sort.field { f -> f.field(\"_id\").order(SortOrder.Asc) } }\n            .size(20)\n            .apply {\n                searchAfter?.let { sa -> searchAfter(sa) }\n            }\n    }, Product::class.java)\n\n    val hits = response.hits().hits()\n    val lastSort = hits.lastOrNull()?.sort()\n\n    return SearchPage(\n        items = hits.mapNotNull { it.source() },\n        nextSearchAfter = lastSort,\n        total = response.hits().total()?.value() ?: 0\n    )\n}\n```\n\n### Multi-Search (msearch) for Parallel Queries\n\n```kotlin\n\u002F\u002F 여러 쿼리를 하나의 HTTP 요청으로 실행\nfun parallelSearch(keyword: String): AggregatedSearchResult {\n    val response = client.msearch({ ms ->\n        ms.searches(\n            \u002F\u002F 상품 검색\n            { rs -> rs\n                .header { h -> h.index(\"products\") }\n                .body { b -> b.query { q -> q.match { m -> m.field(\"title\").query(keyword) } }.size(10) }\n            },\n            \u002F\u002F 카테고리 집계\n            { rs -> rs\n                .header { h -> h.index(\"products\") }\n                .body { b ->\n                    b.size(0).aggregations(\"categories\") { a ->\n                        a.terms { t -> t.field(\"category\").size(10) }\n                    }\n                }\n            },\n            \u002F\u002F 브랜드 추천\n            { rs -> rs\n                .header { h -> h.index(\"brands\") }\n                .body { b -> b.query { q -> q.match { m -> m.field(\"name\").query(keyword) } }.size(5) }\n            }\n        )\n    }, JsonData::class.java)\n\n    \u002F\u002F 각 응답 개별 처리\n    val productHits = response.responses()[0].result().hits()\n    val categoryAggs = response.responses()[1].result().aggregations()\n    val brandHits = response.responses()[2].result().hits()\n\n    return AggregatedSearchResult(productHits, categoryAggs, brandHits)\n}\n```\n\n### Kotlin Coroutine Integration\n\n```kotlin\n\u002F\u002F ES 클라이언트는 동기 API이므로 suspend fun wrapper 필요\n@Service\nclass SearchService(\n    private val client: ElasticsearchClient,\n    private val searchDispatcher: CoroutineDispatcher = Dispatchers.IO\n) {\n    \u002F\u002F IO 디스패처에서 블로킹 호출 실행\n    suspend fun search(request: SearchRequest): SearchResponse\u003CProduct> =\n        withContext(searchDispatcher) {\n            client.search(request, Product::class.java)\n        }\n\n    \u002F\u002F 여러 인덱스 병렬 검색\n    suspend fun parallelSearch(keyword: String): CombinedResult = coroutineScope {\n        val products = async { searchProducts(keyword) }\n        val suggestions = async { searchSuggestions(keyword) }\n        val relatedKeywords = async { findRelatedKeywords(keyword) }\n\n        CombinedResult(\n            products = products.await(),\n            suggestions = suggestions.await(),\n            relatedKeywords = relatedKeywords.await()\n        )\n    }\n}\n```\n\n## 3. Bulk Indexing\n\n### BulkProcessor Pattern\n\n```kotlin\n\u002F\u002F elasticsearch-java v8 BulkIngester\n@Component\nclass ProductIndexer(\n    private val client: ElasticsearchClient\n) {\n    private val bulkIngester = BulkIngester.of { b ->\n        b.client(client)\n            .maxOperations(500)         \u002F\u002F 500건마다 flush\n            .flushInterval(5, TimeUnit.SECONDS) \u002F\u002F 또는 5초마다\n            .maxConcurrentRequests(2)   \u002F\u002F 동시 2개 요청\n            .listener(object : BulkListener\u003CAny> {\n                override fun beforeBulk(executionId: Long, request: BulkRequest, contexts: List\u003CAny>) {\n                    logger.info(\"Bulk #{}: {} operations\", executionId, request.operations().size)\n                }\n                override fun afterBulk(executionId: Long, request: BulkRequest, contexts: List\u003CAny>, response: BulkResponse) {\n                    if (response.errors()) {\n                        response.items().filter { it.error() != null }.forEach { item ->\n                            logger.error(\"Bulk item error: index={}, id={}, error={}\",\n                                item.index(), item.id(), item.error()?.reason())\n                        }\n                    }\n                }\n                override fun afterBulk(executionId: Long, request: BulkRequest, contexts: List\u003CAny>, failure: Throwable) {\n                    logger.error(\"Bulk #{} failed\", executionId, failure)\n                }\n            })\n    }\n\n    fun indexProduct(product: Product) {\n        bulkIngester.add { op ->\n            op.index { idx ->\n                idx.index(\"products\").id(product.id).document(product)\n            }\n        }\n    }\n\n    @PreDestroy\n    fun close() = bulkIngester.close()\n}\n```\n\n### Coroutine-Based Indexing Pipeline\n\n```kotlin\n\u002F\u002F Channel 기반 비동기 인덱싱 파이프라인\nclass CoroutineBulkIndexer(\n    private val client: ElasticsearchClient,\n    private val batchSize: Int = 500,\n    private val flushIntervalMs: Long = 5000\n) {\n    private val channel = Channel\u003CBulkOperation>(capacity = 10_000)\n\n    \u002F\u002F producer: 문서 투입\n    suspend fun add(operation: BulkOperation) {\n        channel.send(operation)\n    }\n\n    \u002F\u002F consumer: 배치 처리\n    fun start(scope: CoroutineScope) = scope.launch(Dispatchers.IO) {\n        val buffer = mutableListOf\u003CBulkOperation>()\n        var lastFlush = System.currentTimeMillis()\n\n        for (op in channel) {\n            buffer.add(op)\n            val elapsed = System.currentTimeMillis() - lastFlush\n\n            if (buffer.size >= batchSize || elapsed >= flushIntervalMs) {\n                flush(buffer.toList())\n                buffer.clear()\n                lastFlush = System.currentTimeMillis()\n            }\n        }\n        \u002F\u002F 채널 종료 시 남은 버퍼 flush\n        if (buffer.isNotEmpty()) flush(buffer)\n    }\n\n    private suspend fun flush(operations: List\u003CBulkOperation>) {\n        try {\n            val response = client.bulk { b -> b.operations(operations) }\n            if (response.errors()) {\n                val failures = response.items().filter { it.error() != null }\n                logger.error(\"Bulk indexing partial failure: {} \u002F {} failed\",\n                    failures.size, operations.size)\n                \u002F\u002F 실패 건 재시도 또는 DLQ 저장\n                handleFailures(failures, operations)\n            }\n        } catch (e: Exception) {\n            logger.error(\"Bulk request failed entirely\", e)\n            \u002F\u002F 전체 실패 시 재시도 큐로 전송\n        }\n    }\n}\n```\n\n### Struct-to-Document Serialization\n\n```kotlin\n\u002F\u002F Jackson 직렬화 설정\n@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy::class)\ndata class ProductDocument(\n    @JsonProperty(\"id\") val id: String,\n    @JsonProperty(\"title\") val title: String,\n    @JsonProperty(\"price\") val price: Int,\n    @JsonProperty(\"category\") val category: String,\n    @JsonProperty(\"tags\") val tags: List\u003CString>,\n    @JsonProperty(\"created_at\") val createdAt: Instant,\n    @JsonIgnore val internalMemo: String? = null \u002F\u002F ES에 인덱싱하지 않음\n) {\n    companion object {\n        fun from(product: Product): ProductDocument = ProductDocument(\n            id = product.id,\n            title = product.title,\n            price = product.price,\n            category = product.category.code,\n            tags = product.tags.map { it.name },\n            createdAt = product.createdAt\n        )\n    }\n}\n```\n\n## 4. Testing\n\n### @SpringBootTest with Testcontainers\n\n```kotlin\n@SpringBootTest\n@Testcontainers\nclass ProductSearchServiceTest {\n\n    companion object {\n        @Container\n        @JvmStatic\n        val elasticsearch = ElasticsearchContainer(\n            DockerImageName.parse(\"docker.elastic.co\u002Felasticsearch\u002Felasticsearch:8.12.0\")\n        ).apply {\n            withEnv(\"discovery.type\", \"single-node\")\n            withEnv(\"xpack.security.enabled\", \"false\")\n            withEnv(\"ES_JAVA_OPTS\", \"-Xms512m -Xmx512m\")\n        }\n\n        @DynamicPropertySource\n        @JvmStatic\n        fun overrideProperties(registry: DynamicPropertyRegistry) {\n            registry.add(\"elasticsearch.hosts\") { listOf(elasticsearch.httpHostAddress) }\n        }\n    }\n\n    @Autowired\n    lateinit var searchService: ProductSearchService\n\n    @Autowired\n    lateinit var client: ElasticsearchClient\n\n    @BeforeEach\n    fun setup() {\n        \u002F\u002F 테스트 인덱스 생성 및 fixture 투입\n        createTestIndex()\n        indexTestDocuments()\n        \u002F\u002F 인덱싱 후 refresh 필수 (테스트에서는 즉시 검색 가능하도록)\n        client.indices().refresh { r -> r.index(\"products\") }\n    }\n\n    @Test\n    fun `상품 검색 시 제목 매칭 결과 반환`() {\n        val results = searchService.searchProducts(\"무선 이어폰\", null, null)\n        assertThat(results).isNotEmpty\n        assertThat(results.first().title).contains(\"이어폰\")\n    }\n\n    @AfterEach\n    fun cleanup() {\n        client.indices().delete { d -> d.index(\"products\") }\n    }\n}\n```\n\n### MockK for Unit Tests\n\n```kotlin\nclass SearchServiceUnitTest {\n\n    private val client: ElasticsearchClient = mockk()\n    private val service = SearchService(client)\n\n    @Test\n    fun `검색 결과가 없을 때 빈 리스트 반환`() {\n        \u002F\u002F Given\n        val emptyResponse = mockk\u003CSearchResponse\u003CProduct>> {\n            every { hits() } returns mockk {\n                every { hits() } returns emptyList()\n                every { total() } returns mockk { every { value() } returns 0 }\n            }\n        }\n        every { client.search(any\u003CSearchRequest>(), Product::class.java) } returns emptyResponse\n\n        \u002F\u002F When\n        val result = service.searchProducts(\"존재하지않는키워드\")\n\n        \u002F\u002F Then\n        assertThat(result).isEmpty()\n        verify(exactly = 1) { client.search(any\u003CSearchRequest>(), Product::class.java) }\n    }\n}\n```\n\n### Search Test Fixtures\n\n```kotlin\nobject SearchTestFixtures {\n    fun productDocuments(): List\u003CProduct> = listOf(\n        Product(id = \"1\", title = \"삼성 무선 이어폰 버즈3\", price = 150000, category = \"electronics\"),\n        Product(id = \"2\", title = \"애플 에어팟 프로 2세대\", price = 320000, category = \"electronics\"),\n        Product(id = \"3\", title = \"소니 노이즈캔슬링 헤드폰\", price = 280000, category = \"electronics\"),\n        Product(id = \"4\", title = \"무선 충전기 고속\", price = 25000, category = \"accessories\"),\n    )\n\n    \u002F\u002F 매핑 JSON (테스트용 간소화 버전)\n    val productMapping = \"\"\"\n    {\n        \"mappings\": {\n            \"properties\": {\n                \"title\": { \"type\": \"text\", \"analyzer\": \"standard\" },\n                \"price\": { \"type\": \"integer\" },\n                \"category\": { \"type\": \"keyword\" }\n            }\n        }\n    }\n    \"\"\".trimIndent()\n}\n```\n\n### Benchmark Pattern\n\n```kotlin\n\u002F\u002F JMH를 활용한 검색 성능 벤치마크\n@State(Scope.Benchmark)\n@BenchmarkMode(Mode.AverageTime)\n@OutputTimeUnit(TimeUnit.MILLISECONDS)\nopen class SearchBenchmark {\n    private lateinit var client: ElasticsearchClient\n\n    @Setup\n    fun setup() { \u002F* ES 연결 및 테스트 데이터 준비 *\u002F }\n\n    @Benchmark\n    fun searchSingleMatch(bh: Blackhole) {\n        val response = client.search({ s ->\n            s.index(\"products\").query { q -> q.match { m -> m.field(\"title\").query(\"이어폰\") } }\n        }, Product::class.java)\n        bh.consume(response)\n    }\n\n    @Benchmark\n    fun searchBoolWithFilter(bh: Blackhole) {\n        val response = client.search({ s ->\n            s.index(\"products\").query { q ->\n                q.bool { b ->\n                    b.must { m -> m.match { mt -> mt.field(\"title\").query(\"이어폰\") } }\n                    b.filter { f -> f.term { t -> t.field(\"category\").value(\"electronics\") } }\n                    b\n                }\n            }\n        }, Product::class.java)\n        bh.consume(response)\n    }\n}\n```\n\n## 5. Common Mistakes\n\n| Mistake | 문제 | Fix | Severity |\n|---------|------|-----|----------|\n| Response 미닫기 | 커넥션 풀 고갈, 메모리 누수 | `use {}` 또는 `try-finally`로 close 보장 | **Critical** |\n| `isError()` 무시 | 부분 실패 감지 못함 | bulk response에서 `errors()` 확인 | **High** |\n| 문자열 연결로 쿼리 생성 | injection 위험, 유지보수 불가 | builder API 또는 parameterized query 사용 | **Critical** |\n| timeout context 미설정 | 느린 쿼리가 스레드 점유 | `requestTimeout`, coroutine `withTimeout` 적용 | **High** |\n| bulk flush 동기 대기 | 호출 스레드 블로킹 | coroutine 또는 비동기 listener 활용 | **Medium** |\n| `_source` 필터링 미사용 | 불필요한 필드까지 전송 | `source(includes)` 로 필요 필드만 조회 | **Medium** |\n| `from\u002Fsize` 깊은 페이징 | 10,000건 이상 시 성능 급락 | `search_after` 사용 | **High** |\n| 인덱싱 후 refresh 없이 검색 | 테스트에서 결과 누락 | `indices().refresh()` 호출 (테스트 시) | **Medium** |\n\n```kotlin\n\u002F\u002F BAD: response 미닫기\nval response = client.search(request, Product::class.java)\n\u002F\u002F 응답 처리 중 예외 시 리소스 누수\n\n\u002F\u002F GOOD: timeout과 함께 안전하게 처리\nsuspend fun safeSearch(request: SearchRequest): List\u003CProduct> =\n    withContext(Dispatchers.IO) {\n        withTimeout(10_000) { \u002F\u002F 10초 타임아웃\n            val response = client.search(request, Product::class.java)\n            response.hits().hits().mapNotNull { it.source() }\n        }\n    }\n```\n\n## 6. Python Subsection (elasticsearch-py)\n\n서브 기술 스택인 Python에서의 ES 클라이언트 패턴.\n\n### AsyncElasticsearch Setup\n\n```python\nfrom elasticsearch import AsyncElasticsearch\n\nes = AsyncElasticsearch(\n    hosts=[\"http:\u002F\u002Fes-host:9200\"],\n    basic_auth=(\"user\", \"password\"),\n    max_retries=3,\n    retry_on_timeout=True,\n    request_timeout=30,\n)\n\nasync def search_products(keyword: str) -> list[dict]:\n    response = await es.search(\n        index=\"products\",\n        body={\n            \"query\": {\"match\": {\"title\": keyword}},\n            \"size\": 20,\n            \"_source\": [\"title\", \"price\", \"category\"],\n        },\n    )\n    return [hit[\"_source\"] for hit in response[\"hits\"][\"hits\"]]\n\n# 애플리케이션 종료 시 반드시 close\nasync def shutdown():\n    await es.close()\n```\n\n### helpers.bulk & scan\n\n```python\nfrom elasticsearch.helpers import async_bulk, async_scan\n\n# Bulk 인덱싱\nasync def bulk_index(documents: list[dict]):\n    actions = [\n        {\n            \"_index\": \"products\",\n            \"_id\": doc[\"id\"],\n            \"_source\": doc,\n        }\n        for doc in documents\n    ]\n    success, errors = await async_bulk(es, actions, chunk_size=500, raise_on_error=False)\n    if errors:\n        logger.error(f\"Bulk indexing errors: {len(errors)} failures\")\n\n# Scan (전체 문서 순회, scroll 대체)\nasync def export_all_products():\n    async for doc in async_scan(\n        es,\n        index=\"products\",\n        query={\"query\": {\"match_all\": {}}},\n        scroll=\"5m\",\n        size=1000,\n    ):\n        yield doc[\"_source\"]\n```\n\n### Python 주의사항\n\n| Mistake | Fix |\n|---------|-----|\n| 동기 `Elasticsearch` 클라이언트를 async 앱에서 사용 | `AsyncElasticsearch` 사용 |\n| `helpers.bulk`에서 `raise_on_error=True` (기본값) | `False`로 변경 후 에러 별도 처리 |\n| `scan` helper에서 `scroll` 시간 너무 길게 설정 | `\"5m\"` 이하, 처리 속도에 맞게 |\n| `body` dict를 수동 구성 시 오타 | `elasticsearch-dsl` 라이브러리로 builder 패턴 |\n\n---\n\n**Remember**: ES 클라이언트는 thread-safe하지만, 요청당 리소스 관리는 필수입니다. 커넥션 풀 크기, timeout, retry 정책을 운영 환경에 맞게 반드시 튜닝하세요.\n",{"name":5,"description":7},"main","e9f37e996e3d2b1b6ac9c879e9dfba1223b597c3","archive\u002Fcomponents\u002Fsearch\u002Fskills\u002Fkotlin-es-client-patterns",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 kotlin-es-client-patterns",{"tool":59,"command":60},"bunx","bunx skills add Dokkabei97\u002Fdokkabei-harness --skill kotlin-es-client-patterns",{"tool":62,"command":63},"pnpm","pnpm dlx skills add Dokkabei97\u002Fdokkabei-harness --skill kotlin-es-client-patterns","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FDokkabei97\u002Fdokkabei-harness\u002Fblob\u002Fmain\u002Farchive\u002Fcomponents\u002Fsearch\u002Fskills\u002Fkotlin-es-client-patterns\u002FSKILL.md",true,[],[68,93,118,140,160,181],{"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":74,"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",[],[75,76,77,78,79,80,81,82,83,84,27,85,86,87,88,89,90,91,92,37],"sync","claude md","sync claude md","MCP","commit","architecture","pr","update","ci","integrations","diff","only","minimal","project","make","reviews","pending","mr",{"skillNo":94,"name":95,"nameZh":6,"description":96,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":97,"categories":98,"keywords":99,"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",[],[100,101,102,103,104,105,106,107,108,109,110,111,112,113,88,114,115,116,117,37],"spec","spec driven","dev","spec driven dev","driven","review","workflow","change","tasks","code","plan","ask","never","human","feature","for","vague","features",{"skillNo":119,"name":120,"nameZh":6,"description":121,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":122,"categories":123,"keywords":124,"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",[],[125,126,127,128,129,130,131,110,132,133,27,134,135,114,136,137,33,138,139,37],"shipping","guide","shipping guide","launch","monitoring","lifecycle","feature flags","template","rollback","rollout","flags","thresholds","post","pre-launch","rollback plan",{"skillNo":141,"name":142,"nameZh":6,"description":143,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":144,"categories":145,"keywords":146,"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",[],[142,105,75,108,147,148,149,150,151,152,153,154,86,155,156,157,158,159,36,37],"run","harness","loop","evolve","write","edit","proposals","session","up","dry","learned","Session Retrospective","lessons",{"skillNo":161,"name":162,"nameZh":6,"description":163,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":164,"categories":165,"keywords":166,"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",[],[167,88,168,169,170,109,171,172,173,174,85,86,22,175,176,177,178,179,180,37],"Rules","project rules","core","generate","git","audit","stack","orm","drift","layout","runtime","-specialist","path","scoped",{"skillNo":182,"name":183,"nameZh":6,"description":184,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":185,"categories":186,"keywords":187,"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",[],[188,189,137,190,191,82,192,193,194,155,195,196,197,198,199,200,201,202,92,37],"merge","post merge","documentation","cleanup","batch","wiki","just","issue","tracker","close","closing","follow-up","true","plane","single"]