PGvector

本節將引導您設定 PGvector VectorStore,以儲存文件嵌入並執行相似性搜尋。

PGvector 是 PostgreSQL 的開源擴充功能,可讓您儲存和搜尋機器學習產生的嵌入。它提供不同的功能,讓使用者可以識別精確和近似的最近鄰居。它旨在與其他 PostgreSQL 功能(包括索引和查詢)無縫協作。

先決條件

首先,您需要存取已啟用 vectorhstoreuuid-ossp 擴充功能的 PostgreSQL 實例。

您可以透過Docker ComposeTestcontainers,將 PGvector 資料庫作為 Spring Boot 開發服務執行。或者,本機設定 Postgres/PGVector 附錄說明如何使用 Docker 容器在本機設定資料庫。

啟動時,如果 PgVectorStore 尚未安裝所需的資料庫擴充功能並建立必要的 vector_store 表格與索引,則會嘗試執行這些操作。

或者,您可以手動執行此操作,如下所示

CREATE EXTENSION IF NOT EXISTS vector;
CREATE EXTENSION IF NOT EXISTS hstore;
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

CREATE TABLE IF NOT EXISTS vector_store (
	id uuid DEFAULT uuid_generate_v4() PRIMARY KEY,
	content text,
	metadata json,
	embedding vector(1536) // 1536 is the default embedding dimension
);

CREATE INDEX ON vector_store USING HNSW (embedding vector_cosine_ops);
如果您使用不同的維度,請將 1536 替換為實際的嵌入維度。PGvector 對於 HNSW 索引最多支援 2000 個維度。

接下來,如果需要,請為 EmbeddingModel 提供 API 金鑰,以產生由 PgVectorStore 儲存的嵌入。

自動配置

然後將 PgVectorStore 啟動器相依性新增至您的專案

<dependency>
	<groupId>org.springframework.ai</groupId>
	<artifactId>spring-ai-pgvector-store-spring-boot-starter</artifactId>
</dependency>

或新增至您的 Gradle build.gradle 建置檔案。

dependencies {
    implementation 'org.springframework.ai:spring-ai-pgvector-store-spring-boot-starter'
}

向量儲存實作可以為您初始化所需的結構描述,但您必須選擇加入,方法是在適當的建構函式中指定 initializeSchema 布林值,或在 application.properties 檔案中設定 …​initialize-schema=true

這是一個重大變更!在 Spring AI 的早期版本中,此結構描述初始化是預設發生的。

向量儲存也需要 EmbeddingModel 實例來計算文件的嵌入。您可以選擇其中一個可用的 EmbeddingModel 實作

例如,若要使用 OpenAI EmbeddingModel,請將以下相依性新增至您的專案

<dependency>
	<groupId>org.springframework.ai</groupId>
	<artifactId>spring-ai-openai-spring-boot-starter</artifactId>
</dependency>

或新增至您的 Gradle build.gradle 建置檔案。

dependencies {
    implementation 'org.springframework.ai:spring-ai-openai-spring-boot-starter'
}
請參閱相依性管理章節,將 Spring AI BOM 新增至您的建置檔案。請參閱儲存庫章節,將 Milestone 和/或 Snapshot 儲存庫新增至您的建置檔案。

若要連線和配置 PgVectorStore,您需要提供您實例的存取詳細資訊。可以透過 Spring Boot 的 application.yml 提供簡單的配置。

spring:
  datasource:
    url: jdbc:postgresql://127.0.0.1:5432/postgres
    username: postgres
    password: postgres
  ai:
	vectorstore:
	  pgvector:
		index-type: HNSW
		distance-type: COSINE_DISTANCE
		dimensions: 1536
如果您透過 Docker ComposeTestcontainers 將 PGvector 作為 Spring Boot 開發服務執行,則不需要配置 URL、使用者名稱和密碼,因為它們是由 Spring Boot 自動配置的。
請查看配置參數列表,以了解預設值和配置選項。

現在您可以在您的應用程式中自動注入 PgVectorStore 並使用它

@Autowired VectorStore vectorStore;

// ...

List<Document> documents = List.of(
    new Document("Spring AI rocks!! Spring AI rocks!! Spring AI rocks!! Spring AI rocks!! Spring AI rocks!!", Map.of("meta1", "meta1")),
    new Document("The World is Big and Salvation Lurks Around the Corner"),
    new Document("You walk forward facing the past and you turn back toward the future.", Map.of("meta2", "meta2")));

// Add the documents to PGVector
vectorStore.add(documents);

// Retrieve documents similar to a query
List<Document> results = this.vectorStore.similaritySearch(SearchRequest.query("Spring").withTopK(5));

配置屬性

您可以在 Spring Boot 配置中使用以下屬性來自訂 PGVector 向量儲存。

屬性 描述 預設值

spring.ai.vectorstore.pgvector.index-type

最近鄰居搜尋索引類型。選項包括 NONE - 精確最近鄰居搜尋、IVFFlat - 索引將向量劃分為列表,然後搜尋最接近查詢向量的那些列表的子集。它比 HNSW 具有更快的建置時間和更少的記憶體使用量,但查詢效能較低(就速度-召回率權衡而言)。HNSW - 建立多層圖。它比 IVFFlat 具有更慢的建置時間和更多的記憶體使用量,但具有更好的查詢效能(就速度-召回率權衡而言)。與 IVFFlat 不同,沒有訓練步驟,因此可以在表格中沒有任何資料的情況下建立索引。

HNSW

spring.ai.vectorstore.pgvector.distance-type

搜尋距離類型。預設為 COSINE_DISTANCE。但是,如果向量已標準化為長度 1,則可以使用 EUCLIDEAN_DISTANCENEGATIVE_INNER_PRODUCT 以獲得最佳效能。

COSINE_DISTANCE

spring.ai.vectorstore.pgvector.dimensions

嵌入維度。如果未明確指定,則 PgVectorStore 將從提供的 EmbeddingModel 檢索維度。維度設定為表格建立時的嵌入欄位。如果您變更維度,則也必須重新建立 vector_store 表格。

-

spring.ai.vectorstore.pgvector.remove-existing-vector-store-table

在啟動時刪除現有的 vector_store 表格。

false

spring.ai.vectorstore.pgvector.initialize-schema

是否初始化所需的結構描述

false

spring.ai.vectorstore.pgvector.schema-name

向量儲存結構描述名稱

public

spring.ai.vectorstore.pgvector.table-name

向量儲存表格名稱

vector_store

spring.ai.vectorstore.pgvector.schema-validation

啟用結構描述和表格名稱驗證,以確保它們是有效且現有的物件。

false

如果您配置自訂結構描述和/或表格名稱,請考慮啟用結構描述驗證,方法是設定 spring.ai.vectorstore.pgvector.schema-validation=true。這可確保名稱的正確性,並降低 SQL 注入攻擊的風險。

元數據篩選

您可以將通用的、可移植的 元數據篩選器 與 PgVector 儲存一起使用。

例如,您可以使用文字表達式語言

vectorStore.similaritySearch(
    SearchRequest.defaults()
    .withQuery("The World")
    .withTopK(TOP_K)
    .withSimilarityThreshold(SIMILARITY_THRESHOLD)
    .withFilterExpression("author in ['john', 'jill'] && article_type == 'blog'"));

或以程式設計方式使用 Filter.Expression DSL

FilterExpressionBuilder b = new FilterExpressionBuilder();

vectorStore.similaritySearch(SearchRequest.defaults()
    .withQuery("The World")
    .withTopK(TOP_K)
    .withSimilarityThreshold(SIMILARITY_THRESHOLD)
    .withFilterExpression(b.and(
        b.in("author","john", "jill"),
        b.eq("article_type", "blog")).build()));
這些篩選表達式會轉換為等效的 PgVector 篩選器。

手動配置

您可以手動配置 PgVectorStore,而不是使用 Spring Boot 自動配置。為此,您需要將 PostgreSQL 連線和 JdbcTemplate 自動配置相依性新增至您的專案

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

<dependency>
	<groupId>org.postgresql</groupId>
	<artifactId>postgresql</artifactId>
	<scope>runtime</scope>
</dependency>

<dependency>
	<groupId>org.springframework.ai</groupId>
	<artifactId>spring-ai-pgvector-store</artifactId>
</dependency>
請參閱相依性管理章節,將 Spring AI BOM 新增至您的建置檔案。

若要在您的應用程式中配置 PgVector,您可以使用以下設定

@Bean
public VectorStore vectorStore(JdbcTemplate jdbcTemplate, EmbeddingModel embeddingModel) {
	return new PgVectorStore(jdbcTemplate, embeddingModel);
}

在本機執行 Postgres 和 PGVector 資料庫

docker run -it --rm --name postgres -p 5432:5432 -e POSTGRES_USER=postgres -e POSTGRES_PASSWORD=postgres pgvector/pgvector

您可以像這樣連線到此伺服器

psql -U postgres -h localhost -p 5432