{
  "title": "使用 Pinecone 和 LLM 构建电商混合搜索系统",
  "excerpt": "了解如何结合传统信息检索方法与机器学习模型（如大语言模型 LLM）以及托管向量数据库 Pinecone，为电商应用构建强大的混合搜索系统。探索混合搜索在电商领域的优势，包括提升搜索相关性、实现个性化、处理长尾查询以及简化基础设施管理。",
  "content_html": "<p>搜索并找到相关产品是电商网站的关键组成部分。提供快速且准确的搜索结果，决定了用户是高度满意还是倍感沮丧。随着自然语言理解和向量搜索技术的最新进展，增强型搜索系统变得更加易于实现且高效，从而带来更出色的用户体验和更高的转化率。</p>\n\n<p>在本文中，我们将探讨如何使用高性能向量搜索引擎 Pinecone 以及经过微调的领域专用语言模型，为电商实现混合搜索系统。阅读完本文后，你不仅能深入理解混合搜索，还能获得一份可落地的分步实施指南。</p>\n\n<h2>什么是混合搜索？</h2>\n\n<p><img src=\"/assets/images/pinecone_hybrid_index.jpg\" class=\"post-img\" width=\"2360\" height=\"921\" alt=\"Pinecone 混合索引\"></p>\n<p><span class=\"post-img-caption\">简单 Pinecone 混合索引的高层视图</span></p>\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<p><img src=\"/assets/images/pinecone_hybrid_query.jpg\" class=\"post-img\" width=\"2360\" height=\"892\" alt=\"Pinecone 混合查询\"></p>\n<p><span class=\"post-img-caption\">简单 Pinecone 混合查询的高层视图</span></p>\n\n<p>为了实现混合搜索查询，我们将创建一个函数，该函数接收查询内容、返回结果数量，以及一个 alpha 参数，用于控制稠密向量搜索与稀疏向量搜索得分之间的权重。</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 < 0 or alpha > 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>尝试不同的 alpha 参数值，将帮助你为特定领域找到稀疏向量搜索与稠密向量搜索之间的最佳平衡点。</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:e66aaa4db1667d84e791217c8e94d2c0fb0ed99f7181b65b37a84e72ae3181ef",
  "model": "moonshotai/kimi-k2.6",
  "generated_at": "2026-08-07T05:24:18.998544+00:00"
}