> ## Documentation Index
> Fetch the complete documentation index at: https://cndoc-langchain.site/llms.txt
> Use this file to discover all available pages before exploring further.

# StarRocks 集成

> 使用 LangChain Python 与 StarRocks 向量存储集成。

> [StarRocks](https://www.starrocks.io/) 是一个高性能分析型数据库。
> `StarRocks` 是一个面向全分析场景的下一代亚秒级 MPP 数据库，包括多维分析、实时分析和即席查询。

> 通常 `StarRocks` 被归类为 OLAP，并且在 [ClickBench — 一个分析型数据库基准测试](https://benchmark.clickhouse.com/) 中表现出色。由于它拥有超快的向量化执行引擎，它也可以被用作快速的向量数据库。

这里我们将展示如何使用 StarRocks 向量存储。

## 设置

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
pip install -qU  pymysql langchain-community
```

在开始时设置 `update_vectordb = False`。如果没有文档更新，那么我们不需要重建文档的嵌入向量

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_classic.chains import RetrievalQA
from langchain_community.document_loaders import (
    DirectoryLoader,
    UnstructuredMarkdownLoader,
)
from langchain_community.vectorstores import StarRocks
from langchain_community.vectorstores.starrocks import StarRocksSettings
from langchain_openai import OpenAI, OpenAIEmbeddings
from langchain_text_splitters import TokenTextSplitter

update_vectordb = False
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
/Users/dirlt/utils/py3env/lib/python3.9/site-packages/requests/__init__.py:102: RequestsDependencyWarning: urllib3 (1.26.7) or chardet (5.1.0)/charset_normalizer (2.0.9) doesn't match a supported version!
  warnings.warn("urllib3 ({}) or chardet ({})/charset_normalizer ({}) doesn't match a supported "
```

## 加载文档并将其分割为令牌

加载 `docs` 目录下的所有 markdown 文件

对于 StarRocks 文档，你可以从 [github.com/StarRocks/starrocks](https://github.com/StarRocks/starrocks) 克隆仓库，其中有一个 `docs` 目录。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
loader = DirectoryLoader(
    "./docs", glob="**/*.md", loader_cls=UnstructuredMarkdownLoader
)
documents = loader.load()
```

将文档分割为令牌，并设置 `update_vectordb = True`，因为有新的文档/令牌。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
# 加载文本分割器并将文档分割成文本片段
text_splitter = TokenTextSplitter(chunk_size=400, chunk_overlap=50)
split_docs = text_splitter.split_documents(documents)

# 告诉向量数据库更新文本嵌入
update_vectordb = True
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
split_docs[-20]
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
Document(page_content='使用 Docker 编译 StarRocks\n\n本主题描述如何使用 Docker 编译 StarRocks。\n\n概述\n\nStarRocks 为 Ubuntu 22.04 和 CentOS 7.9 提供了开发环境镜像。使用该镜像，你可以启动一个 Docker 容器并在容器内编译 StarRocks。\n\nStarRocks 版本和开发环境镜像\n\nStarRocks 的不同分支对应于 StarRocks Docker Hub 上提供的不同开发环境镜像。\n\n对于 Ubuntu 22.04：\n\n| 分支名称 | 镜像名称              |\n  | --------------- | ----------------------------------- |\n  | main            | starrocks/dev-env-ubuntu:latest     |\n  | branch-3.0      | starrocks/dev-env-ubuntu:3.0-latest |\n  | branch-2.5      | starrocks/dev-env-ubuntu:2.5-latest |\n\n对于 CentOS 7.9：\n\n| 分支名称 | 镜像名称                       |\n  | --------------- | ------------------------------------ |\n  | main            | starrocks/dev-env-centos7:latest     |\n  | branch-3.0      | starrocks/dev-env-centos7:3.0-latest |\n  | branch-2.5      | starrocks/dev-env-centos7:2.5-latest |\n\n先决条件\n\n在编译 StarRocks 之前，请确保满足以下要求：\n\n硬件\n\n', metadata={'source': 'docs/developers/build-starrocks/Build_in_docker.md'})
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
print("# docs  = %d, # splits = %d" % (len(documents), len(split_docs)))
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
# docs  = 657, # splits = 2802
```

## 创建向量数据库实例

### 使用 StarRocks 作为向量数据库

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
def gen_starrocks(update_vectordb, embeddings, settings):
    if update_vectordb:
        docsearch = StarRocks.from_documents(split_docs, embeddings, config=settings)
    else:
        docsearch = StarRocks(embeddings, settings)
    return docsearch
```

## 将令牌转换为嵌入向量并放入向量数据库

这里我们使用 StarRocks 作为向量数据库，你可以通过 `StarRocksSettings` 配置 StarRocks 实例。

配置 StarRocks 实例与配置 MySQL 实例非常相似。你需要指定：

1. 主机/端口
2. 用户名（默认：'root'）
3. 密码（默认：''）
4. 数据库（默认：'default'）
5. 表（默认：'langchain'）

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
embeddings = OpenAIEmbeddings()

# 配置 starrocks 设置（主机/端口/用户名/密码/数据库）
settings = StarRocksSettings()
settings.port = 41003
settings.host = "127.0.0.1"
settings.username = "root"
settings.password = ""
settings.database = "zya"
docsearch = gen_starrocks(update_vectordb, embeddings, settings)

print(docsearch)

update_vectordb = False
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
Inserting data...: 100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 2802/2802 [02:26<00:00, 19.11it/s]
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
zya.langchain @ 127.0.0.1:41003

username: root

Table Schema:
----------------------------------------------------------------------------
|name                    |type                    |key                     |
----------------------------------------------------------------------------
|id                      |varchar(65533)          |true                    |
|document                |varchar(65533)          |false                   |
|embedding               |array<float>            |false                   |
|metadata                |varchar(65533)          |false                   |
----------------------------------------------------------------------------
```

## 构建问答系统并提问

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
llm = OpenAI()
qa = RetrievalQA.from_chain_type(
        llm=llm, chain_type="stuff", retriever=docsearch.as_retriever()
)
query = "is profile enabled by default? if not, how to enable profile?"
resp = qa.run(query)
print(resp)
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
 No, profile is not enabled by default. To enable profile, set the variable `enable_profile` to `true` using the command `set enable_profile = true;`
```

***

<div className="source-links">
  <Callout icon="terminal-2">
    [将这些文档](/use-these-docs)通过 MCP 连接到 Claude、VSCode 等，以获取实时答案。
  </Callout>

  <Callout icon="edit">
    [在 GitHub 上编辑此页面](https://github.com/langchain-ai/docs/edit/main/src/oss/python/integrations/vectorstores/starrocks.mdx) 或 [提交问题](https://github.com/langchain-ai/docs/issues/new/choose)。
  </Callout>
</div>
