Class PgVectorStore
- All Implemented Interfaces:
VDBStoreBase,AutoCloseable
This class provides an interface for storing and searching vectors using PostgreSQL with the pgvector extension. It implements the VDBStoreBase interface to provide a unified API for vector storage operations.
In PostgreSQL with pgvector, we use a table to store the vectors and metadata, including the document ID, chunk ID, content, and custom payload as JSONB.
This implementation uses the pgvector JDBC driver (com.pgvector:pgvector). To use this class, add the following dependencies:
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.7.4</version>
</dependency>
<dependency>
<groupId>com.pgvector</groupId>
<artifactId>pgvector</artifactId>
<version>0.1.6</version>
</dependency>
Prerequisites:
- PostgreSQL 11+ with pgvector extension installed
- Run: CREATE EXTENSION IF NOT EXISTS vector;
Example usage:
// Using builder with full configuration (recommended)
try (PgVectorStore store = PgVectorStore.builder()
.jdbcUrl("jdbc:postgresql://localhost:5432/mydb")
.username("postgres")
.password("password")
.schema("my_schema") // optional, defaults to "public"
.tableName("embeddings")
.dimensions(1024)
.distanceType(PgVectorStore.DistanceType.COSINE)
.build()) {
store.add(documents).block();
List<Document> results = store.search(searchDto).block();
}
// Using static factory method (simpler, uses defaults)
try (PgVectorStore store = PgVectorStore.create(
"jdbc:postgresql://localhost:5432/mydb",
"postgres", "password", "embeddings", 1024)) {
store.add(documents).block();
List<Document> results = store.search(searchDto).block();
}
Note: The JDBC URL should follow PostgreSQL format:
- jdbc:postgresql://host:port/database
- jdbc:postgresql://localhost:5432/vectordb
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic classBuilder for creating PgVectorStore instances with fluent configuration.static enumDistance types supported by pgvector. -
Method Summary
Modifier and TypeMethodDescriptionreactor.core.publisher.Mono<Void>Adds multiple documents to the store.static PgVectorStore.Builderbuilder()Creates a new builder for constructing PgVectorStore instances.voidclose()Closes the PostgreSQL connection and releases all resources.static PgVectorStoreCreates a new PgVectorStore with minimal configuration.reactor.core.publisher.Mono<Boolean>Deletes a document from the store (optional).Gets the underlying JDBC connection for advanced operations.intGets the vector dimensions.Gets the distance type used for similarity search.Gets the JDBC URL.Gets the schema name.Gets the table name.booleanisClosed()Checks if this store has been closed.reactor.core.publisher.Mono<List<io.agentscope.core.rag.model.Document>>search(SearchDocumentDto searchDocumentDto) Searches for similar documents.
-
Method Details
-
create
public static PgVectorStore create(String jdbcUrl, String username, String password, String tableName, int dimensions) throws VectorStoreException Creates a new PgVectorStore with minimal configuration.- Parameters:
jdbcUrl- the PostgreSQL JDBC URL (e.g., "jdbc:postgresql://localhost:5432/mydb")username- the database usernamepassword- the database passwordtableName- the name of the table to usedimensions- the dimension of vectors that will be stored- Returns:
- a new PgVectorStore instance
- Throws:
VectorStoreException- if initialization fails
-
add
Description copied from interface:VDBStoreBaseAdds multiple documents to the store.All documents must have embedding vectors set. The store will persist both the vectors and the document metadata/payloads.
This method supports batch operations for efficiency. Implementations should handle batch insertion optimally.
- Specified by:
addin interfaceVDBStoreBase- Parameters:
documents- the list of documents to store (all must have embeddings set)- Returns:
- a Mono that completes when all documents are stored
-
search
public reactor.core.publisher.Mono<List<io.agentscope.core.rag.model.Document>> search(SearchDocumentDto searchDocumentDto) Description copied from interface:VDBStoreBaseSearches for similar documents.This method performs vector similarity search and returns the most similar documents. Results include the document metadata and similarity scores. Optionally, embeddings may also be included in the results (implementation-dependent).
- Specified by:
searchin interfaceVDBStoreBase- Parameters:
searchDocumentDto- the search document DTO- Returns:
- a Mono that emits a list of Document objects with scores set, sorted by similarity (descending)
-
delete
Description copied from interface:VDBStoreBaseDeletes a document from the store (optional).Default implementation throws UnsupportedOperationException. Vector stores that support deletion should override this method.
- Specified by:
deletein interfaceVDBStoreBase- Parameters:
docId- the document ID (UUID string) to delete- Returns:
- a Mono that emits true if the deletion was successful, false otherwise
-
getConnection
Gets the underlying JDBC connection for advanced operations.This method provides access to the connection for users who need to perform operations beyond the standard VDBStoreBase interface, such as:
- Custom index configuration
- Advanced filtering
- Table management
- Batch operations
- Returns:
- the Connection instance
- Throws:
VectorStoreException- if the store has been closed
-
getJdbcUrl
Gets the JDBC URL.- Returns:
- the JDBC URL
-
getSchema
Gets the schema name.- Returns:
- the schema name
-
getTableName
Gets the table name.- Returns:
- the table name
-
getDimensions
public int getDimensions()Gets the vector dimensions.- Returns:
- the dimensions
-
getDistanceType
Gets the distance type used for similarity search.- Returns:
- the distance type
-
close
public void close()Closes the PostgreSQL connection and releases all resources.This method closes the JDBC connection, releasing all database resources. This method is idempotent and can be called multiple times safely.
After closing, all operations on this store will fail with a VectorStoreException. It's recommended to use try-with-resources for automatic resource management:
try (PgVectorStore store = PgVectorStore.builder() .jdbcUrl("jdbc:postgresql://localhost:5432/mydb") .tableName("embeddings") .dimensions(1024) .build()) { store.add(documents).block(); // Store is automatically closed here }- Specified by:
closein interfaceAutoCloseable
-
isClosed
public boolean isClosed()Checks if this store has been closed.- Returns:
- true if the store has been closed, false otherwise
-
builder
Creates a new builder for constructing PgVectorStore instances.- Returns:
- a new builder instance
-