Skip to content

Commit

Permalink
integrate-with-llamaindex: refine descriptions
Browse files Browse the repository at this point in the history
  • Loading branch information
qiancai committed Sep 9, 2024
1 parent ae94864 commit f485b58
Showing 1 changed file with 80 additions and 80 deletions.
160 changes: 80 additions & 80 deletions vector-search-integrate-with-llamaindex.md
Original file line number Diff line number Diff line change
@@ -1,40 +1,45 @@
---
title: 在 LlamaIndex 中使用 TiDB 向量搜索
summary: 展示如何在 LlamaIndex 中使用 TiDB 向量搜索
summary: 了解如何在 LlamaIndex 中使用 TiDB 向量搜索
---

# 在 LlamaIndex 中使用 TiDB 向量搜索

本文档展示如何在 [LlamaIndex](https://www.llamaindex.ai) 中使用 [TiDB 向量搜索](/vector-search-overview.md)
本文档将展示如何在 [LlamaIndex](https://www.llamaindex.ai) 中使用 [TiDB 向量搜索](/vector-search-overview.md)

> **Note**
>
> - 您可以在 Jupyter Notebook 上查看完整的 [示例代码](https://github.com/run-llama/llama_index/blob/main/docs/docs/examples/vector_stores/TiDBVector.ipynb),或直接在 [Colab](https://colab.research.google.com/github/run-llama/llama_index/blob/main/docs/docs/examples/vector_stores/TiDBVector.ipynb) 在线环境中运行示例代码。
> 你可以在 Jupyter Notebook 上查看完整的[示例代码](https://github.com/run-llama/llama_index/blob/main/docs/docs/examples/vector_stores/TiDBVector.ipynb),或直接在 [Colab](https://colab.research.google.com/github/run-llama/llama_index/blob/main/docs/docs/examples/vector_stores/TiDBVector.ipynb) 在线环境中运行示例代码。
## 前置需求

- 推荐 [Python 3.8](https://www.python.org/downloads/) 及以上版本。
- [Jupyter Notebook](https://jupyter.org/install)
- [Git](https://git-scm.com/downloads)
- TiDB 集群,如果你还没有 TiDB 集群,可以按照以下方式创建:
- TiDB Serverless 集群。如果没有 TiDB Cloud 集群,请按照 [创建 TiDB Serverless集群](https://dev.mysql.com/doc/refman/8.4/en/mysql.html) 创建自己的 TiDB Cloud 集群。
- 本地部署的 TiDB 集群。如果没有集群,请按照 [使用 TiUP 部署 TiDB 集群](/production-deployment-using-tiup.md) 创建自己的 TiDB 集群。
为了能够顺利完成本文中的操作,你需要提前:

## 开始
- 在你的机器上安装 [Python 3.8](https://www.python.org/downloads/) 或更高版本
- 在你的机器上安装 [Jupyter Notebook](https://jupyter.org/install)
- 在你的机器上安装 [Git](https://git-scm.com/downloads)
- 准备一个 TiDB 集群

本节将逐步说明如何在 LlamaIndex 中使用 TiDB 向量搜索进行语义搜索。
如果你还没有 TiDB 集群,可以按照以下任一种方式创建:

### 步骤 1. 创建新的 Jupyter Notebook 文件
- 参考[部署本地测试 TiDB 集群](/quick-start-with-tidb.md#部署本地测试集群)[部署正式 TiDB 集群](/production-deployment-using-tiup.md),创建本地集群。
- 参考[创建 TiDB Serverless 集群](/develop/dev-guide-build-cluster-in-cloud.md#第-1-步创建-tidb-serverless-集群),创建 TiDB Cloud 集群。

在根目录下新建一个名为 `integrate_with_llamaindex.ipynb` 的 Jupyter Notebook 文件:
## 快速开始

本节将详细介绍如何将 TiDB 的向量搜索功能与 LlamaIndex 结合使用,以实现语义搜索。

### 第 1 步:新建 Jupyter Notebook 文件

在根目录下,新建一个名为 `integrate_with_llamaindex.ipynb` 的 Jupyter Notebook 文件:

```shell
touch integrate_with_llamaindex.ipynb
```

### 步骤 2. 安装所需依赖
### 第 2 步:安装所需的依赖

在项目目录下运行以下命令安装所需的软件包
在你的项目目录下,运行以下命令安装所需的软件包

```shell
pip install llama-index-vector-stores-tidbvector
Expand All @@ -51,36 +56,13 @@ from llama_index.core import VectorStoreIndex
from llama_index.vector_stores.tidbvector import TiDBVectorStore
```

### 步骤 3. 设置环境
### 第 3 步:配置环境变量

<SimpleTab>

<div label="TiDB Serverless 集群部署">

#### 步骤 3.1 获取 TiDB 群集的连接字符串

1.[**Cluster**](https://tidbcloud.com/console/clusters) 界面,单击目标群集的名称进入其概览页面。

2. 单击右上角的**Connect**。此时将显示连接对话框。

3. 确保连接对话框中的配置符合您的运行环境。

- **Connection Type** 设置为 `Public`.
- **Branch** 设置为 `main`.
- **Connect With** 设置为 `SQLAlchemy`.
- **Operating System** 与你的系统环境相匹配.

4. 点击 **PyMySQL** 标签,复制连接字符串。

> **Tip:**
>
> 如果尚未设置密码,请单击**Generate Password**生成一个随机密码。
#### 步骤 3.2 配置环境变量

要建立安全高效的数据库连接,请使用 TiDB 提供的标准连接方法。
<div label="本地部署 TiDB">

本文档使用 [OpenAI](https://platform.openai.com/docs/introduction) 作为嵌入模型生成向量嵌入。在此步骤中,你需要提供从步骤 3.1 中获取的连接字符串和 [OpenAI API 密钥](https://platform.openai.com/docs/quickstart/step-2-set-up-your-api-key)
本文档使用 [OpenAI](https://platform.openai.com/docs/introduction) 作为嵌入模型生成向量嵌入。在此步骤中,你需要提供集群的连接字符串和 [OpenAI API 密钥](https://platform.openai.com/docs/quickstart/step-2-set-up-your-api-key)

运行以下代码,配置环境变量。代码运行后,系统会提示输入连接字符串和 OpenAI API 密钥:

Expand All @@ -95,54 +77,72 @@ tidb_connection_string = getpass.getpass("TiDB Connection String:")
os.environ["OPENAI_API_KEY"] = getpass.getpass("OpenAI API Key:")
```

例如,macOS 上的连接字符串如下所示:

```dotenv
TIDB_DATABASE_URL="mysql+pymysql://<prefix>.root:<password>@gateway01.<region>.prod.aws.tidbcloud.com:4000/test?ssl_ca=/etc/ssl/cert.pem&ssl_verify_cert=true&ssl_verify_identity=true"
```

注意替换为你的 TiDB 实际对应的值。

</div>

<div label="本地部署 TiDB">
<div label="TiDB Serverless 集群部署">

#### 步骤 3.1 配置环境变量
对于 TiDB Serverless 集群,请按照以下步骤获取 TiDB 群集的连接字符串,然后配置环境变量:

要建立安全高效的数据库连接,请使用 TiDB 提供的标准连接方法
1. 在 TiDB Cloud 的 [**Clusters**](https://tidbcloud.com/console/clusters) 页面,单击你的 TiDB Serverless 集群名,进入集群的 **Overview** 页面

本文档使用 [OpenAI](https://platform.openai.com/docs/introduction) 作为嵌入模型生成向量嵌入。在此步骤中,你需要提供从步骤 3.1 中获取的连接字符串和 [OpenAI API 密钥](https://platform.openai.com/docs/quickstart/step-2-set-up-your-api-key)
2. 点击右上角的 **Connect** 按钮,将会弹出连接对话框

运行以下代码,配置环境变量。代码运行后,系统会提示输入连接字符串和 OpenAI API 密钥:
3. 确认对话框中的配置和你的运行环境一致。

```python
# Use getpass to securely prompt for environment variables in your terminal.
import getpass
import os
- **Connection Type**`Public`
- **Branch** 选择 `main`.
- **Connect With** 选择 `SQLAlchemy`.
- **Operating System** 为你的运行环境。

# Copy your connection string from the TiDB Cloud console.
# Connection string format: "mysql+pymysql://<USER>:<PASSWORD>@<HOST>:4000/<DB>?ssl_ca=/etc/ssl/cert.pem&ssl_verify_cert=true&ssl_verify_identity=true"
tidb_connection_string = getpass.getpass("TiDB Connection String:")
os.environ["OPENAI_API_KEY"] = getpass.getpass("OpenAI API Key:")
```
4. 点击 **PyMySQL** 选项卡,复制连接字符串。

例如,macOS 上的连接字符串如下所示:
> **Tip:**
>
> 如果你还没有设置密码,点击 **Generate Password** 生成一个随机密码。
```dotenv
TIDB_DATABASE_URL="mysql+pymysql://<prefix>.root:<password>@gateway01.<region>.prod.aws.tidbcloud.com:4000/test?ssl_ca=/etc/ssl/cert.pem&ssl_verify_cert=true&ssl_verify_identity=true"
```
注意替换为你的 TiDB 实际对应的值。
5. 配置环境变量。

本文档使用 [OpenAI](https://platform.openai.com/docs/introduction) 作为嵌入模型生成向量嵌入。在此步骤中,你需要提供从上一步中获取的连接字符串和 [OpenAI API 密钥](https://platform.openai.com/docs/quickstart/step-2-set-up-your-api-key)

运行以下代码,配置环境变量。代码运行后,系统会提示输入连接字符串和 OpenAI API 密钥:

```python
# Use getpass to securely prompt for environment variables in your terminal.
import getpass
import os

# Copy your connection string from the TiDB Cloud console.
# Connection string format: "mysql+pymysql://<USER>:<PASSWORD>@<HOST>:4000/<DB>?ssl_ca=/etc/ssl/cert.pem&ssl_verify_cert=true&ssl_verify_identity=true"
tidb_connection_string = getpass.getpass("TiDB Connection String:")
os.environ["OPENAI_API_KEY"] = getpass.getpass("OpenAI API Key:")
```

</div>

</SimpleTab>

### 步骤 4. 加载样本文件
### 第 4 步:加载样本文档

#### 步骤 4.1 下载样本文件
#### 4.1 下载样本文档

在项目目录中创建名为 `data/paul_graham/` 的目录,并从 [run-llama/llama_index](https://github.com/run-llama/llama_index) 代码库中下载示例文档 [`paul_graham_essay.txt`](https://github.com/run-llama/llama_index/blob/main/docs/docs/examples/data/paul_graham/paul_graham_essay.txt)
在你的项目目录中创建一个名为 `data/paul_graham/` 的目录,然后从 [run-llama/llama_index](https://github.com/run-llama/llama_index) 代码库中下载样本文档 [`paul_graham_essay.txt`](https://github.com/run-llama/llama_index/blob/main/docs/docs/examples/data/paul_graham/paul_graham_essay.txt)

```shell
!mkdir -p 'data/paul_graham/'
!wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/docs/examples/data/paul_graham/paul_graham_essay.txt' -O 'data/paul_graham/paul_graham_essay.txt'
```

#### 步骤 4.2 加载文件
#### 4.2 加载文档

使用 `SimpleDirectoryReader``data/paul_graham/paul_graham_essay.txt` 中加载示例文档
使用 `SimpleDirectoryReader``data/paul_graham/paul_graham_essay.txt` 中加载示例文档

```python
documents = SimpleDirectoryReader("./data/paul_graham").load_data()
Expand All @@ -152,11 +152,11 @@ for index, document in enumerate(documents):
document.metadata = {"book": "paul_graham"}
```

### 步骤 5. 向量的生成和存储
### 第 5 步:生成并存储文档向量

#### 步骤 5.1 初始化 TiDB 向量存储
#### 5.1 初始化 TiDB 向量存储

以下代码在 TiDB 中创建了一个名为 `paul_graham_test` 的表,该表针对向量搜索进行了优化。
以下代码将在 TiDB 中创建一个 `paul_graham_test` ,该表针对向量搜索进行了优化。

```python
tidbvec = TiDBVectorStore(
Expand All @@ -170,9 +170,9 @@ tidbvec = TiDBVectorStore(

执行成功后,你可以直接查看和访问 TiDB 数据库中的 `paul_graham_test` 表。

#### 步骤 5.2 生成并存储向量
#### 5.2 生成并存储向量嵌入

下面的代码会解析文档、生成向量嵌入并将其存储到 TiDB 向量存储中。
以下代码将解析文档以生成向量嵌入,并将向量嵌入存储到 TiDB 向量存储中。

```python
storage_context = StorageContext.from_defaults(vector_store=tidbvec)
Expand All @@ -188,9 +188,9 @@ Parsing nodes: 100%|██████████| 1/1 [00:00<00:00, 8.76it/s]
Generating embeddings: 100%|██████████| 21/21 [00:02<00:00, 8.22it/s]
```

### 步骤 6. 执行向量搜索
### 第 6 步:执行向量搜索

下面将基于 TiDB 向量存储创建一个查询引擎,并执行语义相似性搜索。
以下代码将基于 TiDB 向量存储创建一个查询引擎,并执行语义相似性搜索。

```python
query_engine = index.as_query_engine()
Expand All @@ -210,13 +210,13 @@ publishing essays online, developing spam filters, painting, hosting dinner part
a building for office use.
```

### 步骤 7. 使用元数据过滤器搜索
### 第 7 步:使用元数据过滤器进行搜索

为了优化搜索,你可以使用元数据筛选器来获取符合所设置筛选条件的特定近邻结果
为了优化搜索,你可以使用元数据过滤器来筛选出符合特定条件的近邻结果

#### 使用 `book != “paul_graham”` 过滤器查询

以下示例查询了去除 `book` 元数据字段为 `paul_graham` 后的结果
以下示例的查询将排除掉 `book` 元数据字段为 `paul_graham` 的结果

```python
from llama_index.core.vector_stores.types import (
Expand All @@ -236,15 +236,15 @@ response = query_engine.query("What did the author learn?")
print(textwrap.fill(str(response), 100))
```

预期输出如下
预期输出如下

```plain
Empty Response
```

#### Query with `book == "paul_graham"` filter

以下示例查询了 `book` 元数据字段为 `paul_graham` 的结果:
以下示例的查询将筛选出 `book` 元数据字段为 `paul_graham` 的结果:

```python
from llama_index.core.vector_stores.types import (
Expand Down Expand Up @@ -274,15 +274,15 @@ Later on, the author attended art school in both the US and Italy, where they ob
substantial teaching in the painting department.
```

### 步骤 8. 删除文件
### 第 8 步:删除文档

从索引中删除第一个文件
从索引中删除第一个文档

```python
tidbvec.delete(documents[0].doc_id)
```

检查文件是否已被删除
检查文档是否已被删除

```python
query_engine = index.as_query_engine()
Expand Down

0 comments on commit f485b58

Please sign in to comment.