Skip to main content
Open In Colab在 GitHub 上打开

Postgres 嵌入

Postgres Embedding 是一种开源的向量相似性搜索Postgres使用Hierarchical Navigable Small Worlds (HNSW)进行近似最近邻搜索。

它支持:

  • 使用 HNSW 进行精确和近似最近邻搜索
  • L2 距离

此笔记本介绍如何使用 Postgres 矢量数据库 (PGEmbedding).

PGEmbedding 集成会为您创建 pg_embedding 扩展,但您需要运行以下 Postgres 查询来添加它:

CREATE EXTENSION embedding;
# Pip install necessary package
%pip install --upgrade --quiet langchain-openai langchain-community
%pip install --upgrade --quiet psycopg2-binary
%pip install --upgrade --quiet tiktoken

将 OpenAI API 密钥添加到要使用的环境变量中OpenAIEmbeddings.

import getpass
import os

if "OPENAI_API_KEY" not in os.environ:
os.environ["OPENAI_API_KEY"] = getpass.getpass("OpenAI API Key:")
OpenAI API Key:········
## Loading Environment Variables
from typing import List, Tuple
from langchain_community.document_loaders import TextLoader
from langchain_community.vectorstores import PGEmbedding
from langchain_core.documents import Document
from langchain_openai import OpenAIEmbeddings
from langchain_text_splitters import CharacterTextSplitter
if "DATABASE_URL" not in os.environ:
os.environ["DATABASE_URL"] = getpass.getpass("Database Url:")
Database Url:········
loader = TextLoader("state_of_the_union.txt")
documents = loader.load()
text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
docs = text_splitter.split_documents(documents)

embeddings = OpenAIEmbeddings()
connection_string = os.environ.get("DATABASE_URL")
collection_name = "state_of_the_union"
db = PGEmbedding.from_documents(
embedding=embeddings,
documents=docs,
collection_name=collection_name,
connection_string=connection_string,
)

query = "What did the president say about Ketanji Brown Jackson"
docs_with_score: List[Tuple[Document, float]] = db.similarity_search_with_score(query)
for doc, score in docs_with_score:
print("-" * 80)
print("Score: ", score)
print(doc.page_content)
print("-" * 80)

在 Postgres 中使用 vectorstore

在 PG 中上传 vectorstore

db = PGEmbedding.from_documents(
embedding=embeddings,
documents=docs,
collection_name=collection_name,
connection_string=connection_string,
pre_delete_collection=False,
)

创建 HNSW 索引

默认情况下,扩展执行顺序扫描搜索,召回率为 100%。您可以考虑为近似最近邻 (ANN) 搜索创建 HNSW 索引以加快速度similarity_search_with_score执行时间。要在向量列上创建 HNSW 索引,请使用create_hnsw_index功能:

PGEmbedding.create_hnsw_index(
max_elements=10000, dims=1536, m=8, ef_construction=16, ef_search=16
)

上述函数等效于运行以下 SQL 查询:

CREATE INDEX ON vectors USING hnsw(vec) WITH (maxelements=10000, dims=1536, m=3, efconstruction=16, efsearch=16);

上述声明中使用的 HNSW 指数选项包括:

  • maxelements:定义索引的最大元素数。这是一个必需的参数。上面显示的示例的值为 3。实际示例将具有非常大的值,例如 1000000。“元素”是指数据集中的数据点(向量),在 HNSW 图中表示为节点。通常,您会将此选项设置为能够容纳数据集中行数的值。

  • dims:定义矢量数据中的维度数。这是一个必需的参数。在上面的示例中使用了一个较小的值。例如,如果要存储使用 OpenAI 的 text-embedding-ada-002 模型(支持 1536 个维度)生成的数据,则可以定义值 1536。

  • m:定义在图形构建期间为每个节点创建的双向链接(也称为“边”)的最大数量。 支持以下其他索引选项:

  • efConstruction:定义索引构造期间考虑的最近邻数。默认值为 32。

  • efsearch:定义索引搜索期间考虑的最近邻数。默认值为 32。 有关如何配置这些选项以影响 HNSW 算法的信息,请参阅优化 HNSW 算法

在 PG 中检索 vectorstore

store = PGEmbedding(
connection_string=connection_string,
embedding_function=embeddings,
collection_name=collection_name,
)

retriever = store.as_retriever()
retriever
VectorStoreRetriever(vectorstore=<langchain_community.vectorstores.pghnsw.HNSWVectoreStore object at 0x121d3c8b0>, search_type='similarity', search_kwargs={})
db1 = PGEmbedding.from_existing_index(
embedding=embeddings,
collection_name=collection_name,
pre_delete_collection=False,
connection_string=connection_string,
)

query = "What did the president say about Ketanji Brown Jackson"
docs_with_score: List[Tuple[Document, float]] = db1.similarity_search_with_score(query)
for doc, score in docs_with_score:
print("-" * 80)
print("Score: ", score)
print(doc.page_content)
print("-" * 80)