{
  "title": "Pinecone과 LLM을 활용한 전자상거래 하이브리드 검색",
  "excerpt": "전통적인 정보 검색 방법과 언어 모델(LLM) 및 관리형 벡터 데이터베이스인 Pinecone과 같은 머신러닝 모델을 결합하여 전자상거래 애플리케이션을 위한 강력한 하이브리드 검색 시스템을 구축하는 방법을 알아보세요. 검색 관련성 향상, 개인화, 롱테일 쿼리 처리, 간소화된 인프라 관리 등 전자상거래를 위한 하이브리드 검색의 이점을 살펴봅니다.",
  "content_html": "<p>관련 제품을 검색하고 찾는 것은 전자상거래 웹사이트의 핵심 구성 요소입니다. 빠르고 정확한 검색 결과를 제공하는 것은 높은 사용자 만족도와 사용자 불만 사이의 차이를 만들 수 있습니다. 최근 자연어 이해 및 벡터 검색 기술의 발전으로 향상된 검색 시스템이 더욱 접근 가능하고 효율적이 되어 더 나은 사용자 경험과 향상된 전환율로 이어지고 있습니다.</p>\n\n<p>이 블로그 게시물에서는 고성능 벡터 검색 엔진인 Pinecone과 도메인별로 미세 조정된 언어 모델을 사용하여 전자상거래를 위한 하이브리드 검색 시스템을 구현하는 방법을 살펴봅니다. 이 게시물을 마치면 하이브리드 검색에 대한 강력한 이해뿐만 아니라 이를 구현하기 위한 실용적인 단계별 가이드를 얻게 될 것입니다.</p>\n\n<h2>하이브리드 검색이란 무엇인가요?</h2>\n\n<img src=\"/assets/images/pinecone_hybrid_index.jpg\" alt=\"Pinecone Hybrid Index\" class=\"post-img\" width=\"2360\" height=\"921\" />\n<span class=\"post-img-caption\">간단한 Pinecone 하이브리드 인덱스의 상위 수준 보기</span>\n\n<p>구현에 들어가기 전에 하이브리드 검색이 무엇을 의미하는지 빠르게 이해해 봅시다. 하이브리드 검색은 전통적인 검색(희소 벡터 검색)과 벡터 검색(밀집 벡터 검색)의 장점을 결합하여 광범위한 도메인에서 더 나은 검색 성능을 달성하는 접근 방식입니다.</p>\n\n<p>밀집 벡터 검색은 텍스트 데이터에서 고품질 벡터 임베딩을 추출하고 유사성 검색을 수행하여 관련 문서를 찾습니다. 그러나 도메인별 데이터셋에서 미세 조정되지 않은 경우 도메인 외 데이터에서 어려움을 겪는 경우가 많습니다.</p>\n\n<p>반면에 전통적인 검색은 용어 빈도-역문서 빈도(TF-IDF) 또는 BM25와 같은 희소 벡터 표현을 사용하며 도메인별 미세 조정이 필요하지 않습니다. 새로운 도메인을 처리할 수 있지만 단어 간의 의미론적 관계를 이해하지 못하고 밀집 검색의 지능이 부족하여 성능이 제한됩니다.</p>\n\n<p>하이브리드 검색은 두 접근 방식을 단일 시스템에 결합하여 밀집 벡터 검색의 성능 잠재력과 전통적인 검색의 제로샷 적응성을 활용함으로써 두 접근 방식의 약점을 완화하려고 시도합니다.</p>\n\n<p>이제 하이브리드 검색에 대한 기본적인 이해를 했으니 구현에 대해 자세히 살펴보겠습니다.</p>\n\n<h2>하이브리드 검색 시스템 구축</h2>\n\n<p>하이브리드 검색 시스템을 구현하기 위한 다음 단계를 다룰 것입니다:</p>\n\n<ol>\n<li>도메인별 언어 모델 활용</li>\n<li>희소 및 밀집 벡터 생성</li>\n<li>Pinecone 설정</li>\n<li>하이브리드 검색 파이프라인 구현</li>\n<li>쿼리 실행 및 매개변수 조정</li>\n</ol>\n\n<h3>1. 도메인별 언어 모델 활용</h3>\n\n<p>최근 몇 년 동안 OpenAI의 GPT 및 Cohere와 같은 대규모 사전 훈련된 언어 모델은 자연어 이해 및 생성을 포함한 다양한 작업에서 점점 더 인기를 얻고 있습니다. 이러한 모델은 도메인별 데이터에서 미세 조정되어 성능을 향상시키고 전자상거래 제품 검색과 같은 특정 작업에 적응할 수 있습니다.</p>\n\n<p>우리의 예에서는 제품 및 쿼리에 대한 밀집 벡터 임베딩을 생성하기 위해 미세 조정된 도메인별 언어 모델을 사용할 것입니다. 그러나 다른 모델을 선택하거나 특정 도메인을 기반으로 자체 사용자 정의 임베딩을 만들 수도 있습니다.</p>\n\n<pre><code class=\"language-python\">import torch\nfrom transformers import AutoTokenizer, AutoModel\n\n# Load a pre-trained domain-specific language model\nmodel_name = \"your-domain-specific-model\"\ntokenizer = AutoTokenizer.from_pretrained(model_name)\nmodel = AutoModel.from_pretrained(model_name)\n\n# Generate dense vector embeddings for a product description\ntext = \"Nike Air Max sports shoes for men\"\ninputs = tokenizer(text, return_tensors=\"pt\")\nwith torch.no_grad():\n    outputs = model(**inputs)\n    dense_embedding = outputs.last_hidden_state.mean(dim=1).numpy()\n</code></pre>\n\n<h3>2. 희소 및 밀집 벡터 생성</h3>\n\n<p>하이브리드 검색에는 전자상거래 데이터에 대한 희소 및 밀집 벡터 표현이 모두 필요합니다. 이제 이러한 벡터를 생성하는 방법을 설명하겠습니다.</p>\n\n<h4>희소 벡터</h4>\n\n<p>TF-IDF 또는 BM25와 같은 희소 벡터 표현은 토큰화, 불용어 제거 및 어간 추출과 같은 표준 텍스트 처리 기술을 사용하여 생성할 수 있습니다. 희소 벡터를 생성하는 예는 어휘 행렬을 사용하여 달성할 수 있습니다.</p>\n\n<pre><code class=\"language-python\"># This function generates sparse vector representations of a list of product descriptions\ndef generate_sparse_vectors(text):\n    '''Generates sparse vector representations for a list of product descriptions\n\n    Args:\n        text (list): A list of product descriptions\n\n    Returns:\n        sparse_vector (dict): A dictionary of indices and values\n    '''\n    sparse_vector = bm25.encode_queries(text)\n    return sparse_vector\n\nfrom pinecone_text.sparse import BM25Encoder\n\n# Create the BM25 encoder and fit the data\nbm25 = BM25Encoder()\nbm25.fit(new_df.full_data)\n\n# Create the sparse vectors\nsparse_vectors = []\nfor product_description in product_descriptions:\n    sparse_vectors.append(generate_sparse_vectors(text=product_description))\n</code></pre>\n\n<h4>밀집 벡터</h4>\n\n<p>밀집 벡터 표현은 사전 훈련되거나 사용자 정의 도메인별 언어 모델을 사용하여 생성할 수 있습니다. 이전 예에서는 제품 설명에 대한 밀집 벡터 임베딩을 생성하기 위해 도메인별 언어 모델을 사용했습니다.</p>\n\n<pre><code class=\"language-python\">def generate_dense_vector(text):\n    '''Generates dense vector embeddings for a list of product descriptions\n\n    Args:\n        text (list): A list of product descriptions\n\n    Returns:\n        dense_embedding (np.array): A numpy array of dense vector embeddings\n    '''\n    # Tokenize the text and convert to PyTorch tensors\n    inputs = tokenizer(text, return_tensors=\"pt\")\n    # Generate the embeddings with the pre-trained model\n    with torch.no_grad():\n        outputs = model(**inputs)\n        dense_vector = outputs.last_hidden_state.mean(dim=1).numpy()\n    return dense_vector\n\n# Generate dense vector embeddings for a list of product descriptions\ndense_vectors = []\nfor product_description in product_descriptions:\n    dense_vectors.append(generate_dense_vector(text=product_description))\n</code></pre>\n\n<h3>3. Pinecone 설정</h3>\n\n<p>Pinecone은 하이브리드 검색을 지원하는 고성능 벡터 검색 엔진입니다. 희소 및 밀집 벡터 모두에 대한 단일 인덱스 생성을 가능하게 하고 다양한 데이터 모달리티에 걸쳐 검색 쿼리를 원활하게 처리합니다.</p>\n\n<p>Pinecone을 사용하려면 계정에 가입하고 Pinecone 클라이언트를 설치하고 API 키와 환경을 설정해야 합니다.</p>\n\n<pre><code class=\"language-python\"># Create a Pinecone hybrid search index\nimport pinecone\n\npinecone.init(\n    api_key=\"YOUR_API_KEY\",  # app.pinecone.io\n    environment=\"YOUR_ENV\"  # find next to api key in console\n)\n\n# Create a Pinecone hybrid search index\nindex_name = \"ecommerce-hybrid-search\"\npinecone.create_index(\n    index_name = index_name,\n    dimension = MODEL_DIMENSION,  # dimensionality of dense model\n    metric = \"dotproduct\"\n)\n# connect to the index\nindex = pinecone.Index(index_name=index_name)\n# view index stats\nindex.describe_index_stats()\n</code></pre>\n\n<h3>4. 하이브리드 검색 파이프라인 구현</h3>\n\n<p>희소 및 밀집 벡터가 생성되고 Pinecone이 설정되면 이제 하이브리드 검색 파이프라인을 구축할 수 있습니다. 이 파이프라인에는 다음 단계가 포함됩니다:</p>\n\n<ol>\n<li>Pinecone 인덱스에 제품 데이터 추가</li>\n<li>희소 및 밀집 벡터를 모두 사용하여 결과 검색</li>\n</ol>\n\n<pre><code class=\"language-python\">def add_product_data_to_index(product_ids, sparse_vectors, dense_vectors, metadata=None):\n    \"\"\"Upserts product data to the Pinecone index.\n\n    Args:\n        product_ids (`list` of `str`): Product IDs.\n        sparse_vectors (`list` of `list` of `float`): Sparse vectors.\n        dense_vectors (`list` of `list` of `float`): Dense vectors.\n        metadata (`list` of `list` of `str`): Optional metadata.\n\n    Returns:\n        None\n    \"\"\"\n    batch_size = 32\n\n    # Loop through the product IDs in batches.\n    for i in range(0, len(product_ids), batch_size):\n        i_end = min(i + batch_size, len(product_ids))\n        ids = product_ids[i:i_end]\n        sparse_batch = sparse_vectors[i:i_end]\n        dense_batch = dense_vectors[i:i_end]\n        meta_batch = metadata[i:i_end] if metadata else []\n\n        vectors = []\n        for _id, sparse, dense, meta in zip(ids, sparse_batch, dense_batch, meta_batch):\n            vectors.append({\n                'id': _id,\n                'sparse_values': sparse,\n                'values': dense,\n                'metadata': meta\n            })\n\n        # Upsert the vectors into the Pinecone index.\n        index.upsert(vectors=vectors)\n\nadd_product_data_to_index(product_ids, sparse_vectors, dense_vectors)\n</code></pre>\n\n<p>이제 데이터가 인덱싱되었으므로 하이브리드 검색 쿼리를 수행할 수 있습니다.</p>\n\n<h3>5. 쿼리 실행 및 매개변수 조정</h3>\n\n<img src=\"/assets/images/pinecone_hybrid_query.jpg\" alt=\"Pinecone Hybrid Query\" class=\"post-img\" width=\"2360\" height=\"892\" />\n<span class=\"post-img-caption\">간단한 Pinecone 하이브리드 쿼리의 상위 수준 보기</span>\n\n<p>하이브리드 검색 쿼리를 만들기 위해 쿼리, 상위 결과 수 및 밀집 및 희소 벡터 검색 점수 간의 가중치를 제어하는 알파 매개변수를 받는 함수를 만들 것입니다.</p>\n\n<pre><code class=\"language-python\">def hybrid_scale(dense, sparse, alpha: float):\n    \"\"\"Hybrid vector scaling using a convex combination\n\n    alpha * dense + (1 - alpha) * sparse\n\n    Args:\n        dense: Array of floats representing\n        sparse: a dict of `indices` and `values`\n        alpha: float between 0 and 1 where 0 == sparse only\n               and 1 == dense only\n    \"\"\"\n    if alpha &lt; 0 or alpha &gt; 1:\n        raise ValueError(\"Alpha must be between 0 and 1\")\n    # scale sparse and dense vectors to create hybrid search vecs\n    hsparse = {\n        'indices': sparse['indices'],\n        'values':  [v * (1 - alpha) for v in sparse['values']]\n    }\n    hdense = [v * alpha for v in dense]\n    return hdense, hsparse\n\ndef search_products(query, top_k=10, alpha=0.5):\n    # Generate sparse query vector\n    sparse_query_vector = generate_sparse_vector(query)\n\n    # Generate dense query vector\n    dense_query_vector = generate_dense_vector(query)\n\n    # Calculate hybrid query vector\n    dense_query_vector, sparse_query_vector = hybrid_scale(dense_query_vector, sparse_query_vector, alpha)\n\n    # Search products using Pinecone\n    results = index.query(\n        vector=dense_query_vector,\n        sparse_vector=sparse_query_vector,\n        top_k=top_k\n    )\n\n    return results\n</code></pre>\n\n<p>그런 다음 이 함수를 사용하여 전자상거래 데이터셋에서 관련 제품을 검색할 수 있습니다.</p>\n\n<pre><code class=\"language-python\">query = \"running shoes for women\"\nresults = search_products(query, top_k=5)\n\nfor result in results:\n    print(result['id'], result['metadata']['product_name'], result['score'])\n</code></pre>\n\n<p>알파 매개변수에 대해 다양한 값을 실험하면 특정 도메인에 대한 희소 및 밀집 벡터 검색 간의 최적 균형을 찾는 데 도움이 됩니다.</p>\n\n<h2>결론</h2>\n\n<p>이 블로그 게시물에서는 Pinecone과 도메인별 언어 모델을 사용하여 전자상거래를 위한 하이브리드 검색 시스템을 구축하는 방법을 시연했습니다. 하이브리드 검색을 통해 전통적인 검색과 벡터 검색의 장점을 결합하여 다양한 도메인에서 검색 성능과 적응성을 향상시킬 수 있습니다.</p>\n\n<p>이 게시물에서 제공하는 단계와 코드 스니펫을 따라 전자상거래 웹사이트의 특정 요구 사항에 맞춘 자체 하이브리드 검색 시스템을 구현할 수 있습니다. 지금 Pinecone을 탐색하고 전자상거래 검색 경험을 개선하세요!</p>\n\n<h2>참고 자료</h2>\n\n<ul>\n<li><a href=\"https://colab.research.google.com/github/pinecone-io/examples/blob/master/search/hybrid-search/ecommerce-search/ecommerce-search.ipynb\">Ecommerce Search using Hybrid Search Techniques in Pinecone (Google Colab Notebook)</a>: Pinecone의 하이브리드 검색 기술을 사용한 전자상거래 검색 구현을 보여주는 실용적인 가이드입니다.</li>\n<li><a href=\"https://docs.pinecone.io/docs/ecommerce-search\">Pinecone Ecommerce Search Documentation</a>: 전자상거래 검색 시스템 구축을 위한 공식 Pinecone 문서입니다.</li>\n<li><a href=\"https://colab.research.google.com/github/pinecone-io/examples/blob/master/pinecone/sparse/bm25/bm25-vector-generation.ipynb\">BM25 Vector Generation using Pinecone (Google Colab Notebook)</a>: Pinecone을 사용하여 BM25 희소 벡터를 생성하는 가이드입니다.</li>\n<li><a href=\"https://github.com/pinecone-io/pinecone-text\">Pinecone Text Repository on GitHub</a>: Pinecone을 사용한 텍스트 처리 및 벡터 생성 리소스 모음입니다.</li>\n<li><a href=\"https://www.pinecone.io/learn/hybrid-search-intro/\">Introduction to Hybrid Search on Pinecone's Website</a>: Pinecone의 기능 맥락에서 하이브리드 검색, 그 이점 및 사용 사례에 대한 개요입니다.</li>\n</ul>",
  "source_hash": "sha256:c8b3789c888127b9f8404365e651e80624c4177f346d2aef54a3b185e2cd138b",
  "model": "claude-sonnet-4-5-20250929",
  "generated_at": "2026-01-15T20:04:26.554789+00:00"
}