跳到主要内容

PGVector

LangChain4j は PGVector とシームレスに統合され、開発者は ベクトル埋め込みを PostgreSQL に直接保存・照会できます。この連携はセマンティック検索、 RAG などのアプリケーションに最適です。

Maven依存関係​


<dependency>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-pgvector</artifactId>
<version>1.23.0-beta33</version>
</dependency>

Gradle依存関係​

implementation 'dev.langchain4j:langchain4j-pgvector:1.23.0-beta33'

APIs​

  • PgVectorEmbeddingStore

Parameter Summary​

Plain Java PropertyDescriptionDefault ValueRequired/Optional
datasourceThe DataSource object used for database connections. Available only in the PgVectorEmbeddingStore.datasourceBuilder() builder variant. If not provided, host, port, user, password, and database must be provided individually in the PgVectorEmbeddingStore.builder() builder variant.NoneRequired if host, port, user, password, and database are not provided individually.
hostHostname of the PostgreSQL server. Required if DataSource is not provided.NoneRequired if DataSource is not provided
portPort number of the PostgreSQL server. Required if DataSource is not provided.NoneRequired if DataSource is not provided
userUsername for database authentication. Required if DataSource is not provided.NoneRequired if DataSource is not provided
passwordPassword for database authentication. Required if DataSource is not provided.NoneRequired if DataSource is not provided
databaseName of the database to connect to. Required if DataSource is not provided.NoneRequired if DataSource is not provided
tableThe name of the database table used for storing embeddings.NoneRequired
dimensionThe dimensionality of the embedding vectors. This should match the embedding model being used. Use embeddingModel.dimension() to dynamically set it.NoneRequired
useIndexAn IVFFlat index divides vectors into lists, and then searches a subset of those lists closest to the query vector. It has faster build times and uses less memory than HNSW but has lower query performance (in terms of speed-recall tradeoff). Should use IVFFlat index.falseOptional
indexListSizeThe number of lists for the IVFFlat index.NoneWhen Required: If useIndex is true, indexListSize must be provided and must be greater than zero. Otherwise, the program will throw an exception during table initialization. When Optional: If useIndex is false, this property is ignored and doesn’t need to be set.
createTableSpecifies whether to automatically create the embeddings table.trueOptional
dropTableFirstSpecifies whether to drop the table before recreating it (useful for tests).falseOptional
searchModeSearch mode to use. Options:
  • VECTOR: Standard vector similarity search using cosine distance.
  • HYBRID: Combines vector search with full-text keyword search using Reciprocal Rank Fusion (RRF).
VECTOROptional
rrfKThe constant k used in the RRF (Reciprocal Rank Fusion) algorithm: Score = 1/(k + rank_vector) + 1/(k + rank_keyword). Lower values (20-40) emphasize top results more; higher values (80-100) create more balanced rankings. Only relevant when searchMode is set to HYBRID.60Optional. Only used in HYBRID search mode.
textSearchConfigPostgreSQL text search configuration name used for keyword search (e.g., simple, english, german). Only applies when searchMode is HYBRID.simpleOptional. Only used in HYBRID search mode.
metadataStorageConfigConfiguration object for handling metadata associated with embeddings. Supports three storage modes:
  • COLUMN_PER_KEY: For static metadata when you know the metadata keys in advance.
  • COMBINED_JSON: For dynamic metadata when you don't know the metadata keys in advance. Stores data as JSON. (Default)
  • COMBINED_JSONB: Similar to JSON, but stored in binary format for optimized querying on large datasets.
COMBINED_JSONOptional. If not set, a default configuration is used with COMBINED_JSON.

Examples​

To demonstrate the capabilities of PGVector, you can use a Dockerized PostgreSQL setup. It leverages Testcontainers to run PostgreSQL with PGVector.

Quick Start with Docker​

To quickly set up a PostgreSQL instance with the PGVector extension, you can use the following Docker command:

docker run --rm --name langchain4j-postgres-test-container -p 5432:5432 -e POSTGRES_USER=my_user -e POSTGRES_PASSWORD=my_password pgvector/pgvector

Explanation of the Command:​

  • docker run: Runs a new container.
  • --rm: Automatically removes the container after it stops, ensuring no residual data.
  • --name langchain4j-postgres-test-container: Names the container langchain4j-postgres-test-container for easy identification.
  • -p 5432:5432: Maps port 5432 on your local machine to port 5432 in the container.
  • -e POSTGRES_USER=my_user: Sets the PostgreSQL username to my_user.
  • -e POSTGRES_PASSWORD=my_password: Sets the PostgreSQL password to my_password.
  • pgvector/pgvector: Specifies the Docker image to use, pre-configured with the PGVector extension.

Here are two code examples showing how to create a PgVectorEmbeddingStore. The first uses only the required parameters, while the second configures all available parameters.

  1. Only Required Parameters
EmbeddingStore<TextSegment> embeddingStore = PgVectorEmbeddingStore.builder()
.host("localhost") // Required: Host of the PostgreSQL instance
.port(5432) // Required: Port of the PostgreSQL instance
.database("postgres") // Required: Database name
.user("my_user") // Required: Database user
.password("my_password") // Required: Database password
.table("my_embeddings") // Required: Table name to store embeddings
.dimension(embeddingModel.dimension()) // Required: Dimension of embeddings
.build();
  1. 全パラメータ設定

このバリアントでは、useIndex、indexListSize、 createTable、dropTableFirst、metadataStorageConfig など、よく使う任意パラメータも含めます。必要に応じて値を調整してください:

EmbeddingStore<TextSegment> embeddingStore = PgVectorEmbeddingStore.builder()
// Required parameters
.host("localhost")
.port(5432)
.database("postgres")
.user("my_user")
.password("my_password")
.table("my_embeddings")
.dimension(embeddingModel.dimension())

// Optional parameters
.useIndex(true) // Enable IVFFlat index
.indexListSize(100) // Number of lists for IVFFlat index
.createTable(true) // Automatically create the table if it doesn’t exist
.dropTableFirst(false) // Don’t drop the table first (set to true if you want a fresh start)
.metadataStorageConfig(MetadataStorageConfig.combinedJsonb()) // Store metadata as a combined JSONB column

.build();

Use the first example if you just want the minimal configuration to get started quickly. The second example shows how you can leverage all available builder parameters for more control and customization.

Complete RAG Example with PGVector​

This section demonstrates how to build a complete Retrieval-Augmented Generation (RAG) system using PostgreSQL with the PGVector extension for semantic search.

Overview​

A RAG system consists of two main stages:

  1. Indexing Stage (Offline): Load documents, split into chunks, generate embeddings, and store in pgvector
  2. Retrieval Stage (Online): Embed user query, search similar chunks, inject context into LLM prompt

Prerequisites​

Ensure you have a PostgreSQL instance with PGVector running (see Docker setup above).

1. Document Ingestion (Indexing Stage)​

This example shows how to load documents, split them into chunks, and store embeddings in pgvector:

import dev.langchain4j.data.document.Document;
import dev.langchain4j.data.document.DocumentParser;
import dev.langchain4j.data.document.DocumentSplitter;
import dev.langchain4j.data.document.parser.apache.pdfbox.ApachePdfBoxDocumentParser;
import dev.langchain4j.data.document.splitter.DocumentSplitters;
import dev.langchain4j.data.embedding.Embedding;
import dev.langchain4j.data.segment.TextSegment;
import dev.langchain4j.model.embedding.EmbeddingModel;
import dev.langchain4j.model.embedding.onnx.allminilml6v2.AllMiniLmL6V2EmbeddingModel;
import dev.langchain4j.store.embedding.EmbeddingStore;
import dev.langchain4j.store.embedding.EmbeddingStoreIngestor;

import static dev.langchain4j.data.document.loader.FileSystemDocumentLoader.loadDocument;

// Load document (PDF, TXT, etc.)
Document document = loadDocument("/path/to/document.pdf", new ApachePdfBoxDocumentParser());

// Split document into smaller chunks
// 300 tokens per chunk, 50 tokens overlap for context continuity
DocumentSplitter splitter = DocumentSplitters.recursive(300, 50);

// Create embedding model (384 dimensions for AllMiniLmL6V2)
EmbeddingModel embeddingModel = new AllMiniLmL6V2EmbeddingModel();

// Create pgvector embedding store
EmbeddingStore<TextSegment> embeddingStore = PgVectorEmbeddingStore.builder()
.host("localhost")
.port(5432)
.database("postgres")
.user("my_user")
.password("my_password")
.table("document_embeddings")
.dimension(embeddingModel.dimension()) // 384 for AllMiniLmL6V2
.build();

// Ingest: split document, generate embeddings, and store in pgvector
EmbeddingStoreIngestor.builder()
.documentSplitter(splitter)
.embeddingModel(embeddingModel)
.embeddingStore(embeddingStore)
.build()
.ingest(document);

System.out.println("Document ingested successfully!");

2. クエリ(検索段階)​

ユーザーの質問で RAG システムに問い合わせる例です:

import dev.langchain4j.data.embedding.Embedding;
import dev.langchain4j.data.message.AiMessage;
import dev.langchain4j.model.chat.ChatModel;
import dev.langchain4j.model.openai.OpenAiChatModel;
import dev.langchain4j.store.embedding.EmbeddingMatch;
import dev.langchain4j.store.embedding.EmbeddingSearchRequest;
import dev.langchain4j.store.embedding.EmbeddingSearchResult;

import java.util.List;
import java.util.stream.Collectors;

// User's question
String question = "What is the refund policy?";

// Generate embedding for the question
Embedding questionEmbedding = embeddingModel.embed(question).content();

// Search for the most similar text segments (top 3 results)
List<EmbeddingMatch<TextSegment>> relevantSegments = embeddingStore.findRelevant(
questionEmbedding,
3 // Retrieve top 3 most similar chunks
);

// Build context from retrieved segments
String context = relevantSegments.stream()
.map(match -> match.embedded().text())
.collect(Collectors.joining("\n\n"));

// Create prompt with retrieved context
String promptWithContext = String.format("""
Answer the question based on the following context.
If the context doesn't contain relevant information, say "I don't have enough information to answer."

Context:
%s

Question: %s

Answer:
""", context, question);

// Send to LLM with context
ChatModel chatModel = OpenAiChatModel.builder()
.apiKey(System.getenv("OPENAI_API_KEY"))
.modelName("gpt-6.1-sol")
.build();

String answer = chatModel.chat(promptWithContext);
System.out.println("Answer: " + answer);

本番環境での考慮事項​

実運用に基づき、本番デプロイで重要な考慮事項を挙げます:

1. コネクションプーリング​

本番環境では、個別の接続パラメータではなく、コネクションプーリング付きの DataSource を使ってください:

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

HikariConfig config = new HikariConfig();
config.setJdbcUrl("jdbc:postgresql://localhost:5432/postgres");
config.setUsername("my_user");
config.setPassword("my_password");
config.setMaximumPoolSize(10);

HikariDataSource dataSource = new HikariDataSource(config);

EmbeddingStore<TextSegment> embeddingStore = PgVectorEmbeddingStore.datasourceBuilder()
.datasource(dataSource)
.table("document_embeddings")
.dimension(384)
.build();

2. インデックス最適化​

大規模データセット(埋め込み 10 万件超)では、クエリ性能向上のため IVFFlat インデックスを有効にしてください:

EmbeddingStore<TextSegment> embeddingStore = PgVectorEmbeddingStore.builder()
// ... other config ...
.useIndex(true)
.indexListSize(100) // Adjust based on dataset size
.build();

注意: 大規模データセットではインデックス作成に時間がかかることがあります。クエリ速度とインデックス構築時間のバランスを取ってください。

3. メタデータ保存​

大規模データセットでより良いクエリ性能を得るには、メタデータ保存に JSONB を使ってください:

import dev.langchain4j.store.embedding.pgvector.MetadataStorageConfig;

EmbeddingStore<TextSegment> embeddingStore = PgVectorEmbeddingStore.builder()
// ... other config ...
.metadataStorageConfig(MetadataStorageConfig.combinedJsonb())
.build();

4. チャンクサイズの調整​

ユースケースに応じて異なるチャンクサイズを試してください:

  • 小さめのチャンク(200–300 トークン): 精度が高く、より具体的な回答
  • 大きめのチャンク(500–800 トークン): より多くのコンテキストだが、関連性が下がる可能性

5. エラー処理​

データベース接続失敗は常に適切に処理してください:

try {
embeddingStore.add(embedding, textSegment);
} catch (Exception e) {
logger.error("Failed to store embedding", e);
// Implement retry logic or fallback behavior
}

ハイブリッド検索(ベクトル + キーワード)​

PGVector は、ベクトル類似度検索と PostgreSQL の全文キーワード検索を組み合わせた ハイブリッド検索 をサポートします。セマンティック理解と正確なキーワード一致の両方を活かすため、ベクトルのみの検索より良い結果になることが多いです。

ハイブリッド検索を使うべき場合​

  • セマンティック類似度と正確なキーワード一致の両方が必要なとき
  • ドメイン固有の用語、製品名、専門用語を含むクエリ向け
  • RAG アプリケーションでの検索精度向上のため

設定​

searchMode パラメータを設定してハイブリッド検索を有効にします:

import dev.langchain4j.store.embedding.pgvector.SearchMode;

EmbeddingStore<TextSegment> embeddingStore = PgVectorEmbeddingStore.builder()
.host("localhost")
.port(5432)
.database("postgres")
.user("my_user")
.password("my_password")
.table("document_embeddings")
.dimension(embeddingModel.dimension())
.searchMode(SearchMode.HYBRID) // Enable hybrid search (default: SearchMode.VECTOR)
.textSearchConfig("english") // Optional: PostgreSQL text search config (default: "simple")
.rrfK(60) // Optional: RRF algorithm parameter (default: 60)
.build();

使い方​

ハイブリッド検索を使うときは、埋め込みとクエリテキストの 両方 を渡す必要があります:

import dev.langchain4j.store.embedding.EmbeddingSearchRequest;

String question = "How to configure PostgreSQL vector search?";

// Generate embedding for the query
Embedding questionEmbedding = embeddingModel.embed(question).content();

// Search with both embedding and text (required for HYBRID mode)
EmbeddingSearchRequest request = EmbeddingSearchRequest.builder()
.queryEmbedding(questionEmbedding) // For vector similarity search
.query(question) // For keyword search (REQUIRED in HYBRID mode)
.maxResults(3)
.build();

List<EmbeddingMatch<TextSegment>> results = embeddingStore.search(request);

仕組み​

ハイブリッド検索は Reciprocal Rank Fusion(RRF) で結果を結合します:

  1. ベクトル検索: コサイン類似度でセマンティックに似たテキストを探す
  2. キーワード検索: PostgreSQL の tsvector でキーワードが一致するテキストを探す
  3. RRF 融合: 次の式でランキングを結合:
RRF_Score = 1/(k + rank_vector) + 1/(k + rank_keyword)

ここで:

  • k は定数(rrfK() で設定可能、デフォルト: 60)
  • rank_vector はベクトル検索での順位(1 = 最良の一致)
  • rank_keyword はキーワード検索での順位(1 = 最良の一致)

スコア計算の例(テストで使われる k = 80):

ドキュメントがベクトル検索・キーワード検索の両方で 1 位の場合:

Score = 1/(80+1) + 1/(80+1)
= 1/81 + 1/81
≈ 0.0247

スコア範囲の注意

  • 両検索で 1 位のときの最大スコアは 2/(k+1)(例: k=60 → 約 0.0328、k=80 → 約 0.0247)。
  • 順位が下がるにつれスコアは 0 に近づき、1.0 には達しません。
  • RRF スコアは順位ベースであり、ベクトルのみ検索のコサイン類似度(0.0–1.0)と直接比較できません。

ベクトルのみ検索との主な違い​

観点ベクトル検索ハイブリッド検索
クエリ入力queryEmbedding のみqueryEmbedding および query テキストの両方
スコア種別コサイン類似度(0.0–1.0)RRF 順位ベーススコア(最大 ≈ 2/(k+1);k=60 で約 0.033)
得意な用途セマンティック類似度、言い換え正確なキーワード + セマンティック意味

RRF パラメータの調整​

rrfK パラメータを調整してランキング感度を制御します:

.rrfK(40)   // More weight to top-ranked results (higher scores for top matches)
.rrfK(80) // More balanced between top and lower-ranked results
  • 小さい k(20–40): 上位結果をより強調
  • 大きい k(80–100): よりバランスの取れたランキング分布
  • デフォルト(60): 多くのユースケースで良いバランス

Spring Boot 統合​

pgvector を Spring Boot マイクロサービスに統合した本番向けの完全な例については、 pgvector RAG Spring Boot example を参照してください。

この例では次を示します:

  • PgVectorEmbeddingStore の Spring Boot 自動構成

  • ドキュメント取り込みとクエリ用の REST API エンドポイント

  • 適切なコネクションプーリングとエラー処理

  • ローカル開発用の Docker Compose セットアップ

  • その他の例