langchain4j-vector-stores-configuration
giuseppe-trisciuoglio/developer-kit
Configure LangChain4J vector stores for RAG applications with PostgreSQL, Pinecone, MongoDB, Milvus, and Neo4j.
What is langchain4j-vector-stores-configuration?
Provides configuration patterns and best practices for setting up vector stores in LangChain4J RAG applications. Use when building semantic search, integrating vector databases, implementing embedding storage with metadata filtering, setting up hybrid search, or optimizing vector database performance for production workloads.
- Configure embedding stores with builder-based setup for PostgreSQL/pgvector, Pinecone, MongoDB, Milvus, and Neo4j
- Implement document ingestion with automatic splitting and embedding generation
- Set up metadata filtering and hybrid search capabilities
- Configure connection pooling and production-grade performance optimization
- Implement health checks and monitoring for vector store connectivity
- Support multiple vector stores for different use cases with Spring qualifiers
How to install langchain4j-vector-stores-configuration
npx skills add https://github.com/giuseppe-trisciuoglio/developer-kit --skill langchain4j-vector-stores-configuration- LangChain4J library installed
- Java 11 or higher
- Vector database instance (PostgreSQL with pgvector, Pinecone, MongoDB Atlas, Milvus, or Neo4j)
- Embedding model API access (e.g., OpenAI API key)
How to use langchain4j-vector-stores-configuration
- 1.Choose your vector store implementation based on your infrastructure (PostgreSQL, Pinecone, MongoDB, Milvus, or Neo4j)
- 2.Configure the EmbeddingStore bean with connection parameters and embedding dimensions
- 3.Set up document ingestion using EmbeddingStoreIngestor with appropriate document splitter settings
- 4.Configure metadata field mappings if using metadata filtering capabilities
- 5.Implement health checks to monitor vector store connectivity before production deployment
- 6.Test with sample data and queries to validate embedding dimensions and retrieval accuracy
Use cases
- Building semantic search functionality in RAG applications
- Integrating vector databases into existing Java applications
- Setting up document ingestion pipelines with automatic embedding generation
- Implementing metadata-based filtering on vector search results
- Configuring production vector stores with connection pooling and monitoring
- Java developers building RAG applications
- Backend engineers integrating vector databases into production systems
- AI/ML engineers optimizing semantic search performance
- Teams migrating between vector database providers
langchain4j-vector-stores-configuration FAQ
Use 1536 for OpenAI embeddings (text-embedding-3-small and text-embedding-3-large). Match the dimension configuration in your vector store to your embedding model's output dimension.
PostgreSQL + pgvector for existing PostgreSQL environments, Pinecone for managed services, MongoDB Atlas for existing MongoDB applications, and Milvus/Zilliz for high-performance large-scale deployments.
Use IndexMapping to define metadata field names, then use EmbeddingSearchRequest with filter() method using metadataKey() predicates to filter results by category, date, author, or other fields.
Yes, configure multiple EmbeddingStore beans with @Qualifier annotations to use different stores for different use cases (e.g., documents vs. chat history).
Use HikariCP connection pooling with appropriate pool size, enable indexing with useIndex(true), implement health checks, and monitor connectivity before full data ingestion.
Full instructions (SKILL.md)
Source of truth, from giuseppe-trisciuoglio/developer-kit.
name: langchain4j-vector-stores-configuration description: Provides configuration patterns for LangChain4J vector stores in RAG applications. Use when building semantic search, integrating vector databases (PostgreSQL/pgvector, Pinecone, MongoDB, Milvus, Neo4j), implementing embedding storage/retrieval, setting up hybrid search, or optimizing vector database performance for production AI applications. allowed-tools: Read, Write, Edit, Bash, Glob, Grep
LangChain4J Vector Stores Configuration
Configure vector stores for Retrieval-Augmented Generation applications with LangChain4J.
Overview
LangChain4J provides a unified abstraction for vector stores (PostgreSQL/pgvector, Pinecone, MongoDB Atlas, Milvus, Neo4j) with builder-based configuration, metadata filtering, and hybrid search support.
When to Use
- Configuring vector stores for semantic search and RAG applications
- Setting up embedding storage with metadata filtering and hybrid search
- Optimizing vector database performance for production AI workloads
Instructions
Set Up Basic Vector Store
Configure an embedding store for vector operations:
@Bean
public EmbeddingStore<TextSegment> embeddingStore() {
return PgVectorEmbeddingStore.builder()
.host("localhost")
.port(5432)
.database("vectordb")
.user("username")
.password("password")
.table("embeddings")
.dimension(1536) // OpenAI embedding dimension
.createTable(true)
.useIndex(true)
.build();
}
Validation Workflow
Follow this workflow to ensure correct vector store setup:
- Configure: Build the embedding store with required dimensions and connection parameters
- Test connection: Verify store connectivity with a health check before ingesting data
- Validate dimensions: Confirm embedding model dimensions match store configuration
- Ingest test data: Add a small batch of test documents to verify ingestion works
- Run test query: Execute a sample semantic search to confirm retrieval accuracy
- Proceed to production: Only after all steps pass, proceed with full data ingestion
Configure Multiple Vector Stores
Use different stores for different use cases:
@Configuration
public class MultiVectorStoreConfiguration {
@Bean
@Qualifier("documentsStore")
public EmbeddingStore<TextSegment> documentsEmbeddingStore() {
return PgVectorEmbeddingStore.builder()
.table("document_embeddings")
.dimension(1536)
.build();
}
@Bean
@Qualifier("chatHistoryStore")
public EmbeddingStore<TextSegment> chatHistoryEmbeddingStore() {
return MongoDbEmbeddingStore.builder()
.collectionName("chat_embeddings")
.build();
}
}
Implement Document Ingestion
Use EmbeddingStoreIngestor for automated document processing:
@Bean
public EmbeddingStoreIngestor embeddingStoreIngestor(
EmbeddingStore<TextSegment> embeddingStore,
EmbeddingModel embeddingModel) {
return EmbeddingStoreIngestor.builder()
.documentSplitter(DocumentSplitters.recursive(
300, // maxSegmentSizeInTokens
20, // maxOverlapSizeInTokens
new OpenAiTokenizer(GPT_3_5_TURBO)
))
.embeddingModel(embeddingModel)
.embeddingStore(embeddingStore)
.build();
}
Set Up Metadata Filtering
Configure metadata-based filtering capabilities:
// MongoDB with metadata field mapping
IndexMapping indexMapping = IndexMapping.builder()
.dimension(1536)
.metadataFieldNames(Set.of("category", "source", "created_date", "author"))
.build();
// Search with metadata filters
EmbeddingSearchRequest request = EmbeddingSearchRequest.builder()
.queryEmbedding(queryEmbedding)
.maxResults(10)
.filter(and(
metadataKey("category").isEqualTo("technical_docs"),
metadataKey("created_date").isGreaterThan(LocalDate.now().minusMonths(6))
))
.build();
Configure Production Settings
Implement connection pooling and monitoring:
@Bean
public EmbeddingStore<TextSegment> optimizedPgVectorStore() {
HikariConfig hikariConfig = new HikariConfig();
hikariConfig.setJdbcUrl("jdbc:postgresql://localhost:5432/vectordb");
hikariConfig.setUsername("username");
hikariConfig.setPassword("password");
hikariConfig.setMaximumPoolSize(20);
hikariConfig.setMinimumIdle(5);
hikariConfig.setConnectionTimeout(30000);
DataSource dataSource = new HikariDataSource(hikariConfig);
return PgVectorEmbeddingStore.builder()
.dataSource(dataSource)
.table("embeddings")
.dimension(1536)
.useIndex(true)
.build();
}
Implement Health Checks
Monitor vector store connectivity:
@Component
public class VectorStoreHealthIndicator implements HealthIndicator {
private final EmbeddingStore<TextSegment> embeddingStore;
@Override
public Health health() {
try {
embeddingStore.search(EmbeddingSearchRequest.builder()
.queryEmbedding(new Embedding(Collections.nCopies(1536, 0.0f)))
.maxResults(1)
.build());
return Health.up()
.withDetail("store", embeddingStore.getClass().getSimpleName())
.build();
} catch (Exception e) {
return Health.down()
.withDetail("error", e.getMessage())
.build();
}
}
}
Examples
Basic RAG Application Setup
@Configuration
public class SimpleRagConfig {
@Bean
public EmbeddingStore<TextSegment> embeddingStore() {
return PgVectorEmbeddingStore.builder()
.host("localhost")
.database("rag_db")
.table("documents")
.dimension(1536)
.build();
}
@Bean
public ChatLanguageModel chatModel() {
return OpenAiChatModel.withApiKey(System.getenv("OPENAI_API_KEY"));
}
}
Semantic Search Service
@Service
public class SemanticSearchService {
private final EmbeddingStore<TextSegment> store;
private final EmbeddingModel embeddingModel;
public List<String> search(String query, int maxResults) {
Embedding queryEmbedding = embeddingModel.embed(query).content();
EmbeddingSearchRequest request = EmbeddingSearchRequest.builder()
.queryEmbedding(queryEmbedding)
.maxResults(maxResults)
.minScore(0.75)
.build();
return store.search(request).matches().stream()
.map(match -> match.embedded().text())
.toList();
}
}
Production Setup with Monitoring
@Configuration
public class ProductionVectorStoreConfig {
@Bean
public EmbeddingStore<TextSegment> vectorStore(
@Value("${vector.store.host}") String host,
MeterRegistry meterRegistry) {
EmbeddingStore<TextSegment> store = PgVectorEmbeddingStore.builder()
.host(host)
.database("production_vectors")
.useIndex(true)
.indexListSize(200)
.build();
return new MonitoredEmbeddingStore<>(store, meterRegistry);
}
}
Best Practices
Choose the Right Vector Store
For Development:
- Use
InMemoryEmbeddingStorefor local development and testing - Fast setup, no external dependencies
- Data lost on application restart
For Production:
- PostgreSQL + pgvector: Excellent for existing PostgreSQL environments
- Pinecone: Managed service, good for rapid prototyping
- MongoDB Atlas: Good integration with existing MongoDB applications
- Milvus/Zilliz: High performance for large-scale deployments
Configure Appropriate Index Types
Choose index types based on performance requirements:
// For high recall requirements
.indexType(IndexType.FLAT) // Exact search, slower but accurate
// For balanced performance
.indexType(IndexType.IVF_FLAT) // Good balance of speed and accuracy
// For high-speed approximate search
.indexType(IndexType.HNSW) // Fastest, slightly less accurate
Optimize Vector Dimensions
Match embedding dimensions to your model:
// OpenAI text-embedding-3-small
.dimension(1536)
// OpenAI text-embedding-3-large
.dimension(3072)
// Sentence Transformers
.dimension(384) // all-MiniLM-L6-v2
.dimension(768) // all-mpnet-base-v2
Implement Batch Operations
Use batch operations for better performance:
@Service
public class BatchEmbeddingService {
private static final int BATCH_SIZE = 100;
public void addDocumentsBatch(List<Document> documents) {
for (List<Document> batch : Lists.partition(documents, BATCH_SIZE)) {
List<TextSegment> segments = batch.stream()
.map(doc -> TextSegment.from(doc.text(), doc.metadata()))
.collect(Collectors.toList());
List<Embedding> embeddings = embeddingModel.embedAll(segments)
.content();
embeddingStore.addAll(embeddings, segments);
}
}
}
Secure Configuration
Protect sensitive configuration:
// Use environment variables
@Value("${vector.store.api.key:#{null}}")
private String apiKey;
// Validate configuration
@PostConstruct
public void validateConfiguration() {
if (StringUtils.isBlank(apiKey)) {
throw new IllegalStateException("Vector store API key must be configured");
}
}
References
For comprehensive documentation and advanced configurations, see:
- API Reference - Complete API documentation
- Examples - Production-ready examples
Constraints and Warnings
- Vector dimensions must match the embedding model; mismatched dimensions will cause errors.
- Large vector collections require proper indexing configuration for acceptable search performance.
- Embedding generation can be expensive; implement batching and caching strategies.
- Different vector stores have different distance metric support; verify compatibility.
- Connection pooling is critical for production deployments to prevent connection exhaustion.
- Metadata filtering capabilities vary between vector store implementations.
- Vector stores consume significant memory; monitor resource usage in production.
- Migration between vector store providers may require re-embedding all documents.
- Batch operations are more efficient than single-document operations.
- Always validate configuration during application startup to fail fast.
Related skills
More from giuseppe-trisciuoglio/developer-kit and the wider catalog.

learn
Autonomously analyze your codebase to discover patterns and auto-generate Claude Code project rules.

memory-md-management
Audit, assess, and improve project memory files like CLAUDE.md for optimal agent context.

nestjs
NestJS framework patterns with Drizzle ORM for building scalable REST/GraphQL APIs and microservices.

nestjs-best-practices
Enforce modular NestJS architecture, DI scoping, validation, error handling, and Drizzle ORM patterns.

nestjs-code-review
Comprehensive code review for NestJS applications covering controllers, services, modules, guards, and DI patterns.

nestjs-drizzle-crud-generator
Generate complete NestJS CRUD modules with Drizzle ORM, Zod validation, and tests.