
Byted Bytehouse Hybrid Search
- 2 installs
- 408 repo stars
- Updated August 3, 2026
- volcengine/agentkit-samples
Run hybrid search in ByteHouse combining BM25 full-text and HNSW vector retrieval, reranked with RRF, using Doubao embeddings for text vectorization.
About
Implements ByteHouse hybrid retrieval combining BM25 full-text and HNSW vector search reranked via RRF, with automatic Doubao-based text vectorization on insert. A developer uses it to build more accurate keyword-plus-semantic search over ByteHouse data.
- Dual index: BM25 full-text inverted index and HNSW vector index
- hybrid_search() reranks both recall paths with the RRF algorithm
Byted Bytehouse Hybrid Search by the numbers
- 2 all-time installs (skills.sh)
- Ranked #741 of 911 Databases skills by installs in the Skillselion catalog
- Data as of Aug 4, 2026 (Skillselion catalog sync)
npx skills add https://github.com/volcengine/agentkit-samples --skill byted-bytehouse-hybrid-searchAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 2 |
|---|---|
| repo stars | ★ 408 |
| Last updated | August 3, 2026 |
| Repository | volcengine/agentkit-samples ↗ |
What it does
Run hybrid search in ByteHouse combining BM25 full-text and HNSW vector retrieval, reranked with RRF, using Doubao embeddings for text vectorization.
Files
ByteHouse 混合检索 Skill
🚀 快速开始
环境准备
pip install clickhouse-connect volcengine-python-sdk[ark] numpy scipy环境变量配置
优先从环境变量读取配置,禁止硬编码明文敏感信息:
# ByteHouse 配置
export BYTEHOUSE_HOST="<你的ByteHouse连接地址>"
export BYTEHOUSE_PORT="<ByteHouse端口>"
export BYTEHOUSE_USER="<ByteHouse用户名>"
export BYTEHOUSE_PASSWORD="<ByteHouse密码>"
export BYTEHOUSE_DATABASE="<默认数据库,可选,默认default>"
export BYTEHOUSE_SECURE="<是否启用加密,可选,默认true>"
# 火山引擎方舟 API 配置
export ARK_API_KEY="<火山引擎方舟API密钥>"
export ARK_BASE_URL="https://ark.cn-beijing.volces.com/api/v3"
export EMBEDDING_MODEL="doubao-embedding-vision-251215" # 文本向量化模型
export EMBEDDING_DIMENSIONS="1536" # 向量维度,可选,默认1536如果环境变量未配置,会自动提示用户输入。
---
📚 核心能力
1. 文本向量化
基于豆包文本向量化模型生成文本向量,支持任意长度中文文本。
2. 双索引构建
| 索引类型 | 说明 | 适用场景 |
|---|---|---|
| 全文倒排索引 | 基于BM25算法的全文检索,支持关键词匹配 | 精准关键词召回 |
| 向量索引 | 基于HNSW的向量相似度检索,支持语义匹配 | 语义相似召回 |
3. 核心功能
| 功能 | 方法 | 说明 |
|---|---|---|
| 全文检索 | fulltext_search() | 基于BM25的全文检索,返回BM25分数 |
| 向量检索 | vector_search() | 基于余弦相似度的向量检索,返回相似度分数 |
| 混合检索+RRF重排 | hybrid_search() | 双路召回后使用RRF算法重排,返回最终结果 |
| 自动生成向量 | insert_document()/batch_insert_documents() | 插入文档时自动生成向量并存储,无需手动处理 |
| 单个文档向量更新 | update_document_embedding() | 为单个文档重新生成并更新向量 |
| 批量补全缺失向量 | batch_update_missing_embeddings() | 自动扫描表中所有缺少向量的文档,批量生成并补全向量 |
4. RRF重排算法
Reciprocal Rank Fusion 算法,综合全文检索和向量检索的排名结果,公式:
score = Σ 1 / (k + rank)默认k=60,可自定义调整。
---
📖 代码实现
完整示例代码实现位于 scripts/ 目录:
- `scripts/embedding.py` - 文本向量化模块
- `scripts/hybrid_search_client.py` - ByteHouse 混合检索客户端
- `scripts/examples.py` - 使用示例
快速使用
from scripts import ByteHouseHybridSearch
# 初始化客户端
search = ByteHouseHybridSearch(connection_type="http")
# 创建混合检索表(自动构建全文索引和向量索引)
search.create_hybrid_table("my_hybrid_index")
# 插入文档(自动生成向量 + 存储原始文本)
search.insert_document("my_hybrid_index", doc_id=1,
title="ByteHouse 混合检索",
content="ByteHouse 支持全文检索和向量检索,可实现混合检索能力")
# 混合检索(自动执行全文+向量检索,RRF重排返回结果)
results = search.hybrid_search("my_hybrid_index", query="ByteHouse检索能力", top_k=10)---
⚙️ 最佳实践
建表配置
CREATE TABLE {table_name} (
`doc_id` UInt64,
`title` String,
`content` String,
`embedding` Array(Float32),
-- 全文倒排索引(version=2支持BM25分数)
INDEX content_idx content TYPE inverted('standard', '{"version":"v2"}') GRANULARITY 1,
-- 向量索引(HNSW算法,余弦相似度)
INDEX embedding_idx embedding TYPE HNSW_SQ('DIM={vec_dimensions}', 'metric=COSINE', 'M=32', 'EF_CONSTRUCTION=256') GRANULARITY 1
)
ENGINE = MergeTree()
ORDER BY doc_id
SETTINGS
index_granularity = 1024,
enable_vector_index_preload = 1RRF参数调整
- 当全文检索结果更重要时,可降低
rrf_k值(推荐30-60) - 当向量检索结果更重要时,可提高
rrf_k值(推荐60-100)
🔗 参考文档
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
# Copyright (c) 2025 Beijing Volcano Engine Technology Co., Ltd. and/or its affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from .embedding import TextEmbedding
from .hybrid_search_client import ByteHouseHybridSearch
__all__ = ["TextEmbedding", "ByteHouseHybridSearch"]
# Copyright (c) 2025 Beijing Volcano Engine Technology Co., Ltd. and/or its affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
文本向量化模块,基于火山引擎方舟API
"""
import os
import openai
from typing import List, Optional
class TextEmbedding:
def __init__(self,
api_key: Optional[str] = None,
base_url: Optional[str] = None,
model: Optional[str] = None,
dimensions: Optional[int] = None):
"""
初始化文本向量化客户端
:param api_key: 方舟API密钥,默认从环境变量ARK_API_KEY读取
:param base_url: 方舟API地址,默认从环境变量ARK_BASE_URL读取
:param model: 向量化模型,默认从环境变量EMBEDDING_MODEL读取
:param dimensions: 向量维度,默认从环境变量EMBEDDING_DIMENSIONS读取,默认1536
"""
self.api_key = api_key or os.getenv("ARK_API_KEY")
self.base_url = base_url or os.getenv("ARK_BASE_URL", "https://ark.cn-beijing.volces.com/api/v3")
self.model = model or os.getenv("EMBEDDING_MODEL", "doubao-embedding-text-240715")
self.dimensions = dimensions or int(os.getenv("EMBEDDING_DIMENSIONS", "2560"))
if not self.api_key:
raise ValueError("请配置ARK_API_KEY环境变量或传入api_key参数")
self.client = openai.OpenAI(
api_key=self.api_key,
base_url=self.base_url
)
def embed_text(self, text: str) -> List[float]:
"""
生成单个文本的向量
:param text: 输入文本
:return: 向量列表
"""
params = {
"input": text,
"model": self.model
}
# 仅当dimensions存在时传递参数,部分模型不支持自定义维度
if self.dimensions:
params["dimensions"] = self.dimensions
response = self.client.embeddings.create(**params)
return response.data[0].embedding
def batch_embed_texts(self, texts: List[str]) -> List[List[float]]:
"""
批量生成文本向量
:param texts: 输入文本列表
:return: 向量列表
"""
params = {
"input": texts,
"model": self.model
}
# 仅当dimensions存在时传递参数,部分模型不支持自定义维度
if self.dimensions:
params["dimensions"] = self.dimensions
response = self.client.embeddings.create(**params)
return [item.embedding for item in response.data]
# Copyright (c) 2025 Beijing Volcano Engine Technology Co., Ltd. and/or its affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
ByteHouse 混合检索使用示例
"""
from hybrid_search_client import ByteHouseHybridSearch
def main():
# 初始化客户端
search = ByteHouseHybridSearch(connection_type="http")
table_name = "demo_hybrid_index"
# 1. 创建混合检索表
print("=== 创建混合检索表 ===")
search.create_hybrid_table(table_name, if_not_exists=True)
# 2. 插入测试数据
print("\n=== 插入测试数据 ===")
documents = [
{
"doc_id": 1,
"title": "ByteHouse 全文检索",
"content": "ByteHouse 企业版支持全文检索能力,基于倒排索引实现,支持BM25相似度计算,可快速检索文本内容。"
},
{
"doc_id": 2,
"title": "ByteHouse 向量检索",
"content": "ByteHouse 支持向量检索功能,基于HNSW索引实现,支持余弦相似度、L2距离等多种相似度计算方式。"
},
{
"doc_id": 3,
"title": "混合检索最佳实践",
"content": "结合全文检索和向量检索的优势,使用RRF重排算法可以实现更精准的检索效果,兼顾关键词匹配和语义匹配。"
},
{
"doc_id": 4,
"title": "RRF重排算法",
"content": "RRF(Reciprocal Rank Fusion)是一种常用的多路召回融合算法,通过对不同召回源的排名进行加权融合,得到最终的排序结果。"
},
{
"doc_id": 5,
"title": "ClickHouse 二级索引",
"content": "ClickHouse 支持二级索引功能,包括跳数索引、全文倒排索引、向量索引等,可大幅提升查询性能。"
}
]
search.batch_insert_documents(table_name, documents)
print("测试数据插入完成")
# 3. 全文检索示例
print("\n=== 全文检索示例,查询:'ByteHouse 检索' ===")
fulltext_results = search.fulltext_search(table_name, query="ByteHouse 检索", top_k=3)
for i, res in enumerate(fulltext_results):
print(f"排名 {i+1}: [doc_id={res['doc_id']}] {res['title']},BM25分数:{res['bm25_score']:.4f}")
print(f"内容摘要:{res['content'][:50]}...\n")
# 4. 向量检索示例
print("\n=== 向量检索示例,查询:'怎么实现更好的检索效果' ===")
vector_results = search.vector_search(table_name, query="怎么实现更好的检索效果", top_k=3)
for i, res in enumerate(vector_results):
print(f"排名 {i+1}: [doc_id={res['doc_id']}] {res['title']},向量相似度:{res['vector_score']:.4f}")
print(f"内容摘要:{res['content'][:50]}...\n")
# 5. 混合检索+RRF重排示例
print("\n=== 混合检索+RRF重排示例,查询:'ByteHouse 检索效果优化' ===")
hybrid_results = search.hybrid_search(table_name, query="ByteHouse 检索效果优化", top_k=3)
for i, res in enumerate(hybrid_results):
print(f"排名 {i+1}: [doc_id={res['doc_id']}] {res['title']},RRF分数:{res['rrf_score']:.4f}")
if 'bm25_score' in res:
print(f"BM25分数:{res['bm25_score']:.4f}")
if 'vector_score' in res:
print(f"向量相似度:{res['vector_score']:.4f}")
print(f"内容摘要:{res['content'][:80]}...\n")
# 关闭连接
search.close()
if __name__ == "__main__":
main()
# Copyright (c) 2025 Beijing Volcano Engine Technology Co., Ltd. and/or its affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
ByteHouse 混合检索客户端
支持全文检索、向量检索、RRF重排
"""
import os
import clickhouse_connect
from typing import List, Dict, Optional, Any
from .embedding import TextEmbedding
class ByteHouseHybridSearch:
def __init__(self,
host: Optional[str] = None,
port: Optional[int] = None,
user: Optional[str] = None,
password: Optional[str] = None,
database: Optional[str] = None,
secure: Optional[bool] = None,
connection_type: str = "http"):
"""
初始化ByteHouse客户端
:param host: ByteHouse地址,默认从环境变量BYTEHOUSE_HOST读取
:param port: ByteHouse端口,默认从环境变量BYTEHOUSE_PORT读取
:param user: 用户名,默认从环境变量BYTEHOUSE_USER读取
:param password: 密码,默认从环境变量BYTEHOUSE_PASSWORD读取
:param database: 默认数据库,默认从环境变量BYTEHOUSE_DATABASE读取,默认default
:param secure: 是否启用加密,默认从环境变量BYTEHOUSE_SECURE读取,默认True
:param connection_type: 连接类型,http或native,默认http
"""
self.host = host or os.getenv("BYTEHOUSE_HOST")
self.port = port or int(os.getenv("BYTEHOUSE_PORT", "8123"))
self.user = user or os.getenv("BYTEHOUSE_USER", "default")
self.password = password or os.getenv("BYTEHOUSE_PASSWORD")
self.database = database or os.getenv("BYTEHOUSE_DATABASE", "default")
self.secure = secure if secure is not None else (os.getenv("BYTEHOUSE_SECURE", "true").lower() == "true")
if not self.host or not self.password:
raise ValueError("请配置BYTEHOUSE_HOST和BYTEHOUSE_PASSWORD环境变量")
# 初始化ByteHouse连接
self.client = clickhouse_connect.get_client(
host=self.host,
port=self.port,
username=self.user,
password=self.password,
database=self.database,
secure=self.secure,
connect_timeout=30,
send_receive_timeout=60
)
# 初始化向量化客户端
self.embedding_client = TextEmbedding()
def create_hybrid_table(self, table_name: str, if_not_exists: bool = True) -> None:
"""
创建混合检索表,自动构建全文倒排索引和向量索引
:param table_name: 表名
:param if_not_exists: 是否存在就跳过,默认True
"""
exists_clause = "IF NOT EXISTS" if if_not_exists else ""
vec_dimensions = self.embedding_client.dimensions
# 兼容旧版本ByteHouse,先创建基础表,索引可后续手动添加
create_sql = f"""
CREATE TABLE {exists_clause} {table_name} (
`doc_id` UInt64,
`title` String,
`content` String,
`embedding` Array(Float32),
`create_time` DateTime DEFAULT now(),
INDEX content_idx content TYPE inverted('standard', '{{\"version\":\"v2\"}}') GRANULARITY 1,
INDEX embedding_idx embedding TYPE HNSW_SQ('DIM={vec_dimensions}', 'metric=COSINE', 'M=32', 'EF_CONSTRUCTION=256') GRANULARITY 1
)
ENGINE = MergeTree()
ORDER BY doc_id
SETTINGS
index_granularity = 1024
"""
self.client.command(create_sql)
print(f"混合检索表 {table_name} 创建成功,向量维度:{vec_dimensions}")
def insert_document(self, table_name: str, doc_id: int, title: str, content: str) -> None:
"""
插入单个文档
:param table_name: 表名
:param doc_id: 文档ID
:param title: 文档标题
:param content: 文档内容
"""
# 拼接标题和内容生成向量
full_text = f"标题:{title} 内容:{content}"
embedding = self.embedding_client.embed_text(full_text)
insert_sql = f"""
INSERT INTO {table_name} (doc_id, title, content, embedding)
VALUES (%s, %s, %s, %s)
"""
self.client.command(insert_sql, parameters=[doc_id, title, content, embedding])
def batch_insert_documents(self, table_name: str, documents: List[Dict[str, Any]]) -> None:
"""
批量插入文档
:param table_name: 表名
:param documents: 文档列表,每个元素包含doc_id, title, content字段
"""
# 批量生成向量
full_texts = [f"标题:{doc['title']} 内容:{doc['content']}" for doc in documents]
embeddings = self.embedding_client.batch_embed_texts(full_texts)
# 验证向量维度正确性
for emb in embeddings:
if len(emb) != self.embedding_client.dimensions:
raise ValueError(f"向量维度错误:期望{self.embedding_client.dimensions}维,实际{len(emb)}维")
# 构建插入数据
data = []
for i, doc in enumerate(documents):
data.append([
doc['doc_id'],
doc['title'],
doc['content'],
embeddings[i]
])
self.client.insert(
table=table_name,
data=data,
column_names=['doc_id', 'title', 'content', 'embedding']
)
print(f"成功插入 {len(documents)} 条文档,向量已自动生成并写入")
def fulltext_search(self, table_name: str, query: str, top_k: int = 20) -> List[Dict[str, Any]]:
"""
全文检索,基于BM25算法
:param table_name: 表名
:param query: 查询关键词
:param top_k: 返回结果数量,默认20
:return: 检索结果,包含doc_id, title, content, bm25_score字段
"""
search_sql = f"""
SELECT
doc_id,
title,
content,
_text_search_score as bm25_score
FROM {table_name}
WHERE textSearch(content, %s)
ORDER BY bm25_score DESC
LIMIT {top_k}
"""
results = self.client.query(search_sql, parameters=[query]).result_rows
return [
{
"doc_id": row[0],
"title": row[1],
"content": row[2],
"bm25_score": float(row[3])
}
for row in results
]
def vector_search(self, table_name: str, query: str, top_k: int = 20) -> List[Dict[str, Any]]:
"""
向量检索,基于余弦相似度
:param table_name: 表名
:param query: 查询文本
:param top_k: 返回结果数量,默认20
:return: 检索结果,包含doc_id, title, content, vector_score字段
"""
# 生成查询向量
query_embedding = self.embedding_client.embed_text(query)
search_sql = f"""
SELECT
doc_id,
title,
content,
cosineDistance(embedding, %s) as vector_score
FROM {table_name}
ORDER BY vector_score ASC
LIMIT {top_k}
"""
results = self.client.query(search_sql, parameters=[query_embedding]).result_rows
return [
{
"doc_id": row[0],
"title": row[1],
"content": row[2],
"vector_score": float(row[3])
}
for row in results
]
def rrf_rerank(self,
fulltext_results: List[Dict[str, Any]],
vector_results: List[Dict[str, Any]],
top_k: int = 10,
rrf_k: int = 60) -> List[Dict[str, Any]]:
"""
RRF重排算法,融合全文检索和向量检索结果
:param fulltext_results: 全文检索结果
:param vector_results: 向量检索结果
:param top_k: 返回重排后的结果数量,默认10
:param rrf_k: RRF算法k参数,默认60
:return: 重排后的结果,包含rrf_score字段
"""
# 构建文档分数字典
doc_scores: Dict[int, Dict[str, Any]] = {}
# 处理全文检索结果
for rank, result in enumerate(fulltext_results):
doc_id = result["doc_id"]
if doc_id not in doc_scores:
doc_scores[doc_id] = result.copy()
doc_scores[doc_id]["rrf_score"] = 0.0
# 累加RRF分数
doc_scores[doc_id]["rrf_score"] += 1.0 / (rrf_k + rank + 1)
# 处理向量检索结果
for rank, result in enumerate(vector_results):
doc_id = result["doc_id"]
if doc_id not in doc_scores:
doc_scores[doc_id] = result.copy()
doc_scores[doc_id]["rrf_score"] = 0.0
# 累加RRF分数
doc_scores[doc_id]["rrf_score"] += 1.0 / (rrf_k + rank + 1)
# 按RRF分数排序
sorted_docs = sorted(doc_scores.values(), key=lambda x: x["rrf_score"], reverse=True)
# 返回top_k结果
return sorted_docs[:top_k]
def hybrid_search(self,
table_name: str,
query: str,
top_k: int = 10,
recall_k: int = 20,
rrf_k: int = 60) -> List[Dict[str, Any]]:
"""
混合检索:全文+向量双路召回 + RRF重排
:param table_name: 表名
:param query: 查询文本
:param top_k: 返回最终结果数量,默认10
:param recall_k: 每路召回数量,默认20
:param rrf_k: RRF算法k参数,默认60
:return: 最终检索结果
"""
# 两路召回
fulltext_results = self.fulltext_search(table_name, query, top_k=recall_k)
vector_results = self.vector_search(table_name, query, top_k=recall_k)
# RRF重排
reranked_results = self.rrf_rerank(fulltext_results, vector_results, top_k=top_k, rrf_k=rrf_k)
return reranked_results
def close(self) -> None:
"""关闭连接"""
self.client.close()