关于 langchain4j-vector-stores-configuration
面向 Java 应用开发者的 LangChain4J 向量存储配置技能,涵盖多种存储实现、元数据过滤及生产环境连接与监控设置,适用于语义搜索和 RAG 应用。
主要功能
- 01多种向量存储配置
- 02元数据过滤与混合搜索
- 03文档切分与批量写入
- 04连接池和健康检查
适用场景
- 01配置 RAG 应用的嵌入存储
- 02按元数据筛选语义搜索结果
- 03为生产环境设置连接池与监控
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ giuseppe-trisciuoglio/ developer-kit --skill langchain4j-vector-stores-configuration安装后在 Claude Code 中输入/langchain4j-vector-stores-configuration确认已加载。
附带文件references/api-reference.mdreferences/examples.md
详细介绍
LangChain4J 向量存储配置
使用 LangChain4J 为检索增强生成应用配置向量存储。
概述
LangChain4J 为向量存储(PostgreSQL/pgvector、Pinecone、MongoDB Atlas、Milvus、Neo4j)提供统一的抽象,支持基于构建器的配置、元数据过滤和混合搜索。
适用场景
- 为语义搜索和 RAG 应用配置向量存储
- 设置支持元数据过滤和混合搜索的嵌入存储
- 优化向量数据库性能,以满足生产环境中的 AI 工作负载
说明
设置基本向量存储
配置用于向量操作的嵌入存储:
@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();
}
验证工作流
按照以下工作流确保向量存储设置正确:
- 配置:使用所需的维度和连接参数构建嵌入存储
- 测试连接:在摄取数据前,通过运行状况检查验证存储连接性
- 验证维度:确认嵌入模型维度与存储配置匹配
- 摄取测试数据:添加少量测试文档,验证摄取是否正常
- 运行测试查询:执行示例语义搜索,确认检索准确性
- 投入生产:仅在所有步骤均通过后,才开始全面摄取数据
配置多个向量存储
针对不同用例使用不同的存储:
@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();
}
}
实现文档摄取
使用 EmbeddingStoreIngestor 自动处理文档:
@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();
}
设置元数据过滤
配置基于元数据的过滤功能:
// 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();
配置生产环境设置
实现连接池和监控:
@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();
}
实现运行状况检查
监控向量存储的连接状态:
@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();
}
}
}
示例
基本 RAG 应用设置
@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"));
}
}
语义搜索服务
@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();
}
}
配置监控的生产环境设置
@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);
}
}
最佳实践
选择合适的向量存储
用于开发:
- 使用
InMemoryEmbeddingStore进行本地开发和测试 - 设置快速,无需外部依赖
- 应用重启后数据会丢失
用于生产:
- PostgreSQL + pgvector:非常适合已有 PostgreSQL 环境
- Pinecone:托管服务,适合快速原型开发
- MongoDB Atlas:与现有 MongoDB 应用集成良好
- Milvus/Zilliz:适用于大规模部署,性能出色
配置合适的索引类型
根据性能要求选择索引类型:
// 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
优化向量维度
使嵌入维度与模型匹配:
// 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
实现批量操作
使用批量操作以获得更好的性能:
@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);
}
}
}
安全配置
保护敏感配置:
// 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");
}
}
参考资料
如需完整文档和高级配置,请参阅:
限制和警告
- 向量维度必须与嵌入模型匹配;维度不匹配会导致错误。
- 大型向量集合需要正确配置索引,才能达到可接受的搜索性能。
- 生成嵌入可能成本较高;请采用批处理和缓存策略。
- 不同向量存储支持的距离度量各不相同;请确认兼容性。
- 连接池对生产部署至关重要,可避免连接耗尽。
- 不同向量存储实现支持的元数据过滤功能各不相同。
- 向量存储会消耗大量内存;请在生产环境中监控资源使用情况。
- 在不同向量存储提供商之间迁移,可能需要重新为所有文档生成嵌入。
- 批量操作比单文档操作更高效。
- 始终在应用启动时验证配置,以便快速失败。
评论
支持 Markdown