
Byted Bytehouse Hybrid Search
- 31 installs
- 411 repo stars
- Updated August 4, 2026
- bytedance/agentkit-samples
Runs hybrid full-text plus vector search on ByteHouse and reranks results with the RRF algorithm for more precise retrieval.
About
Combines full-text and vector search over ByteHouse and applies RRF reranking. A developer uses it to build higher-precision retrieval over ByteHouse-stored data.
- Full-text plus vector retrieval with RRF rerank
- Uses Volcengine Ark embeddings for vectorization
Byted Bytehouse Hybrid Search by the numbers
- 31 all-time installs (skills.sh)
- Ranked #500 of 911 Databases skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/bytedance/agentkit-samples --skill byted-bytehouse-hybrid-searchAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 31 |
|---|---|
| repo stars | ★ 411 |
| Last updated | August 4, 2026 |
| Repository | bytedance/agentkit-samples ↗ |
What it does
Runs hybrid full-text plus vector search on ByteHouse and reranks results with the RRF algorithm for more precise retrieval.
Files
ByteHouse 混合检索 Skill
🚀 快速开始
环境准备
pip install clickhouse-connect volcengine-python-sdk[ark] numpy scipy配置说明
配置保存在 ~/.bytehouse_config.json ,如果该文件存在且非空,则直接使用文件中的配置。如果不存在,则让用户提供ByteHouse连接信息( 把这个文档也发给客户,文档里面介绍了如何获取主机地址和密码:https://www.volcengine.com/docs/6517/1121919?lang=zh )。用户提供信息后,保存到json文件,避免重复向用户请求连接信息。当用户切换ByteHouse集群时,一并修改该文件。
{
"BYTEHOUSE_HOST": "<ByteHouse-host>",
"BYTEHOUSE_PORT": "8123",
"BYTEHOUSE_USER": "bytehouse",
"BYTEHOUSE_PASSWORD": "<ByteHouse-password>",
"BYTEHOUSE_SECURE": true,
"BYTEHOUSE_VERIFY": true,
"BH_ARK_API_KEY": "<火山引擎方舟API密钥>",
"BH_ARK_BASE_URL": "https://ark.cn-beijing.volces.com/api/v3",
"BH_EMBEDDING_MODEL": "doubao-embedding-vision-251215"
}其中BYTEHOUSE_HOST(主机地址)和BYTEHOUSE_PASSWORD(密码)必须由用户提供。BH_ARK_API_KEY为可选配置,仅在embedding时使用,用户初次使用时可忽略。其余配置固定。
执行 scripts/export_config.sh 把配置信息导入环境变量中
source scripts/export_config.sh---
📚 核心能力
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` - 使用示例
- `scripts/export_config.sh` - 把配置文件中的信息导入环境变量
快速使用
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":"v4"}') GRANULARITY 1,
-- 向量索引(HNSW算法,余弦相似度)
INDEX embedding_idx embedding TYPE HNSW_SQ('DIM={vec_dimensions}', 'metric=COSINE', 'M=32', 'EF_CONSTRUCTION=256') GRANULARITY 1
)
ENGINE = CnchMergeTree()
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 MultimodalEmbedding
from hybrid_search_client import ByteHouseHybridSearch
__all__ = ["MultimodalEmbedding", "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.
"""
多模态向量化模块
基于豆包多模态向量化模型实现文本、图片、视频的向量化
"""
import os
import json
import numpy as np
from volcenginesdkarkruntime import Ark
from typing import List, Union, Dict
class MultimodalEmbedding:
"""多模态向量化客户端"""
def __init__(self):
# 先尝试从环境变量读取配置
api_key = os.environ.get("BH_ARK_API_KEY")
base_url = os.environ.get("BH_ARK_BASE_URL")
# 如果环境变量没有配置,尝试从OpenClaw配置文件读取
if not api_key or not base_url:
config_path = os.path.expanduser("~/.openclaw/openclaw.json")
if os.path.exists(config_path):
try:
with open(config_path, "r", encoding="utf-8") as f:
config = json.load(f)
ark_config = config.get("models", {}).get("providers", {}).get("ark", {})
if not api_key:
api_key = ark_config.get("apiKey")
if not base_url:
base_url = ark_config.get("baseUrl")
except Exception as e:
print(f"读取OpenClaw配置文件失败: {str(e)}")
# 检查必要配置是否存在
if not api_key:
raise ValueError("未找到ARK API Key,请配置BH_ARK_API_KEY环境变量或在openclaw.json中配置models.providers.ark.apiKey")
if not base_url:
raise ValueError("未找到ARK Base URL,请配置BH_ARK_BASE_URL环境变量或在openclaw.json中配置models.providers.ark.baseUrl")
self.client = Ark(
api_key=api_key,
base_url=base_url
)
self.model = os.environ.get("BH_EMBEDDING_MODEL", "doubao-embedding-vision-251215")
self.dimensions = int(os.environ.get("EMBEDDING_DIMENSIONS", 2048))
def encode(self,
input_data: Union[str, List[Dict]],
modality: str = "text",
instruction: str = None) -> List[float]:
"""
多模态向量化接口
Args:
input_data: 输入数据
- 文本:直接传入字符串
- 图片/视频:传入 {"type": "image_url"/"video_url", "url": "xxx"} 格式
modality: 数据类型,可选 text/image/video
instruction: 自定义指令,用于提升特定场景检索精度
Returns:
向量列表
"""
try:
if isinstance(input_data, str):
input_item = {"type": "text", "text": input_data}
else:
input_item = input_data
# 输入格式校验
if modality in ["image", "video"] and not isinstance(input_item, dict):
raise ValueError(f"{modality}类型输入必须为包含url的字典格式")
# 构造请求参数
request_params = {
"model": self.model,
"encoding_format": "float",
"input": [input_item],
"dimensions": self.dimensions
}
# 添加自定义指令(251215及以上版本支持)
if instruction and "251215" in self.model:
request_params["instructions"] = instruction
# 调用 API
resp = self.client.multimodal_embeddings.create(**request_params)
if hasattr(resp, 'data'):
embedding = resp.data.embedding
vec = np.array(embedding).flatten().tolist()
return vec
else:
raise ValueError("API响应格式错误,未找到embedding字段")
except Exception as e:
error_msg = str(e).lower()
if "api key" in error_msg or "unauthorized" in error_msg or "permission" in error_msg:
raise PermissionError(f"向量化失败:API密钥无效或权限不足。错误详情:{e}")
elif "connection" in error_msg or "timeout" in error_msg or "network" in error_msg:
raise ConnectionError(f"向量化失败:网络连接异常。错误详情:{e}")
elif "invalid" in error_msg or "parameter" in error_msg or "format" in error_msg:
raise ValueError(f"向量化失败:输入参数或格式错误。错误详情:{e}")
else:
raise Exception(f"向量化失败:{e}")
def encode_text(self, text: str, instruction: str = None) -> List[float]:
"""文本向量化"""
return self.encode(text, "text", instruction)
def encode_image(self, image_url: str, instruction: str = None) -> List[float]:
"""图片URL向量化"""
input_item = {"type": "image_url", "image_url": {"url": image_url}}
return self.encode(input_item, "image", instruction)
def encode_video(self, video_url: str, instruction: str = None) -> List[float]:
"""视频URL向量化"""
input_item = {"type": "video_url", "video_url": {"url": video_url}}
return self.encode(input_item, "video", instruction)
def main():
"""命令行入口"""
print("Hello, World!")
multimodal_embedding = MultimodalEmbedding()
print(multimodal_embedding.encode_text("你好"))
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 混合检索使用示例
"""
from hybrid_search_client import ByteHouseHybridSearch
def main():
# 初始化客户端
search = ByteHouseHybridSearch(host="",
user="",
password="",
database="",
connection_type="")
table_name = "demo_hybrid_index"
print("=== 清理旧表 ===")
search.client.command(f"DROP TABLE IF EXISTS {table_name}")
# 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()
#!/bin/bash
load_config() {
# 检查 jq 是否安装
if ! command -v jq &> /dev/null; then
echo "Error: jq is not installed. Please install jq first (e.g. brew install jq or sudo apt install jq)."
return 1
fi
# 解析 json,将每个 key-value 转成 export KEY="VALUE" 的格式
local exports
exports=$(jq -r 'to_entries | .[] | "export \(.key)=\(.value | @sh)"' ~/.bytehouse_config.json)
# 执行生成的 export 命令
eval "$exports"
echo "Configuration loaded from ~/.bytehouse_config.json"
}
load_config# 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 MultimodalEmbedding
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", "bytehouse")
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,
verify=False,
connect_timeout=30,
send_receive_timeout=60
)
# 初始化向量化客户端
self.dimensions = int(os.environ.get("EMBEDDING_DIMENSIONS", 2048))
self.embedding_client = MultimodalEmbedding()
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.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\":\"v4\"}}') GRANULARITY 1,
INDEX embedding_idx embedding TYPE HNSW_SQ('DIM={vec_dimensions}', 'metric=COSINE', 'M=32', 'EF_CONSTRUCTION=256') GRANULARITY 1
)
ENGINE = CnchMergeTree()
ORDER BY doc_id
SETTINGS
index_granularity = 1024,
enable_vector_index_preload = 1
"""
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.encode_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字段
"""
# 构建插入数据
data = []
for doc in documents:
# 逐个生成向量
full_text = f"标题:{doc['title']} 内容:{doc['content']}"
emb = self.embedding_client.encode_text(full_text)
# 验证向量维度正确性
if len(emb) != self.dimensions:
raise ValueError(f"向量维度错误:期望{self.dimensions}维,实际{len(emb)}维")
data.append([
doc['doc_id'],
doc['title'],
doc['content'],
emb
])
for row in data:
self.client.command(f"INSERT INTO {table_name} (doc_id, title, content, embedding) VALUES (%s, %s, %s, %s)", parameters=row)
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字段
"""
query_escaped = self.transform_string(query)
search_sql = f"""
SELECT
doc_id,
title,
content,
_text_search_score as bm25_score
FROM {table_name}
WHERE textSearch(content, '{query_escaped}')
ORDER BY bm25_score DESC
LIMIT {top_k}
"""
print(f"执行全文检索查询:{search_sql}")
results = self.client.query(search_sql).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.encode_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}
"""
print(f"执行向量检索查询:{search_sql}")
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()
def transform_string(self, s: str) -> str:
# Remove all single quotes
s = s.replace("'", "")
s = s.replace(" ", "")
# Split each character with |
return "|".join(s)