Skip to main content
Open In ColabOpen on GitHub

openGauss 向量数据库

本笔记本介绍了如何开始使用 openGauss 向量数据库。openGauss 是一个高性能的关系型数据库,具有原生的向量存储与检索能力。该集成在 LangChain 应用中实现了符合 ACID 的向量操作,将传统 SQL 功能与现代人工智能驱动的相似性搜索相结合。 向量数据库。

设置

启动 openGauss 容器

docker run --name opengauss \
-d \
-e GS_PASSWORD='MyStrongPass@123' \
-p 8888:5432 \
opengauss/opengauss-server:latest

安装 langchain-opengauss

pip install langchain-opengauss

系统要求

  • openGauss ≥ 7.0.0
  • Python ≥ 3.8
  • psycopg2-binary

Credentials

使用您的openGauss凭据

初始化

pip install -qU langchain-openai
import getpass
import os

if not os.environ.get("OPENAI_API_KEY"):
os.environ["OPENAI_API_KEY"] = getpass.getpass("Enter API key for OpenAI: ")

from langchain_openai import OpenAIEmbeddings

embeddings = OpenAIEmbeddings(model="text-embedding-3-large")
from langchain_opengauss import OpenGauss, OpenGaussSettings

# Configure with schema validation
config = OpenGaussSettings(
table_name="test_langchain",
embedding_dimension=384,
index_type="HNSW",
distance_strategy="COSINE",
)
vector_store = OpenGauss(embedding=embeddings, config=config)

管理向量存储

添加项到向量存储

from langchain_core.documents import Document

document_1 = Document(page_content="foo", metadata={"source": "https://example.com"})

document_2 = Document(page_content="bar", metadata={"source": "https://example.com"})

document_3 = Document(page_content="baz", metadata={"source": "https://example.com"})

documents = [document_1, document_2, document_3]

vector_store.add_documents(documents=documents, ids=["1", "2", "3"])
API 参考:文档

更新向量存储中的项

updated_document = Document(
page_content="qux", metadata={"source": "https://another-example.com"}
)

# If the id is already exist, will update the document
vector_store.add_documents(document_id="1", document=updated_document)

删除向量存储中的项

vector_store.delete(ids=["3"])

查询向量存储

一旦您的向量存储已经创建并添加了相关文档,您很可能在运行链或代理的过程中希望对其进行查询。

查询直接

简单进行相似性搜索可以按照以下方式进行:

  • TODO: 编辑然后运行代码单元以生成输出
results = vector_store.similarity_search(
query="thud", k=1, filter={"source": "https://another-example.com"}
)
for doc in results:
print(f"* {doc.page_content} [{doc.metadata}]")

如果您想要执行相似性搜索并接收相应的评分,可以运行:

results = vector_store.similarity_search_with_score(
query="thud", k=1, filter={"source": "https://example.com"}
)
for doc, score in results:
print(f"* [SIM={score:3f}] {doc.page_content} [{doc.metadata}]")

查询通过转换为检索器

您也可以将向量存储转换为检索器,以便在链条中更方便地使用。

  • TODO: 编辑然后运行代码单元以生成输出
retriever = vector_store.as_retriever(search_type="mmr", search_kwargs={"k": 1})
retriever.invoke("thud")

使用检索增强生成

对于如何使用此向量存储进行检索增强生成(RAG)的指南,请参见以下部分:

配置

连接设置

参数默认描述
hostlocalhostDatabase server address
port8888Database connection port
usergaussdbDatabase username
password-Complex password string
databasepostgresDefault database name
min_connections1Connection pool minimum size
max_connections5Connection pool maximum size
table_namelangchain_docsName of the table for storing vector data and metadata
index_typeIndexType.HNSWVector index algorithm type. Options: HNSW or IVFFLAT\nDefault is HNSW.
vector_typeVectorType.vectorType of vector representation to use. Default is Vector.
distance_strategyDistanceStrategy.COSINEVector similarity metric to use for retrieval. Options: euclidean (L2 distance), cosine (angular distance, ideal for text embeddings), manhattan (L1 distance for sparse data), negative_inner_product (dot product for normalized vectors).\n Default is cosine.
embedding_dimension1536Dimensionality of the vector embeddings.

支持的组合

向量类型维度索引类型支持的距离策略
vector≤2000HNSW/IVFFLATCOSINE/EUCLIDEAN/MANHATTAN/INNER_PROD

性能优化

索引调优指南

HNSW 参数:

  • m: 16-100 (召回率与记忆之间的平衡)
  • ef_construction: 64-1000 (必须 > 2*m)

IVFFLAT 推荐:

import math

lists = min(
int(math.sqrt(total_rows)) if total_rows > 1e6 else int(total_rows / 1000),
2000, # openGauss maximum
)

连接池

OpenGaussSettings(min_connections=3, max_connections=20)

局限性

  • bitsparsevec 向量类型目前处于开发阶段
  • 最大向量维度:对于 vector 类型,上限为 2000

API 参考

关于所有__ModuleName__VectorStore特性和配置的详细文档,请访问API参考文档:https://python.langchain.com/api_reference/en/latest/vectorstores/opengauss.OpenGuass.html