Explore 解决 Save Share Download ▾ ReportPrivate research annotation Sign in to add a private research label or note.
AssistantCopy response
AssistantCopy response
AssistantCopy response
要创建一个分支并提交 PR,可以按照以下步骤操作:
1. 创建新分支
假设分支名为 feature/mongodb-enn-hybrid-search:
bash Copy code
# 拉取最新的主分支代码
git checkout main
git pull origin main
# 创建新分支
git checkout -b feature/mongodb-enn-hybrid-search
2. 修改和新增代码
按照之前提供的文件修改方案,完成以下操作:
AssistantCopy response
AssistantCopy response
Copy first prompt Copy first response
Other models, same or similar prompt Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Details
Provider openai
Model provenance As recorded by source dataset
Turns 5 (10 messages)
Language Not recorded
Added to archive Nov 26, 2026
ID 01m8bcy6fneqh5jwt9sbwg7t9bSource & license Imported from RepoChat Arena (4K preferences) (source ). Imported records earn no Research Points.
Upstream record: repochat_battles.json:2060:a
lmarena-ai/repochat-arena-preference-4k, revision 72adb77b23e41d2a0e5e5a5783c3cec3dfe14dd5
License: CC-BY-4.0 (prompts); model outputs under provider terms
Cite this conversation “解决.” Conversation with gpt-4o-2024-11-20, from the RepoChat Arena (4K preferences) dataset. The Chat Archive, 2026. https://thechatarchive.com/c/01m8bcy6fneqh5jwt9sbwg7t9b
要在 langchain4j-mongodb-atlas 中支持 MongoDB Atlas 的 ENN(Exact Nearest Neighbor)搜索 和 Hybrid Search(混合搜索) ,可以参考 ElasticsearchEmbeddingStore 和 ElasticsearchConfiguration 的设计模式,按照以下步骤进行实现:
解决方案设计
创建 MongoDbConfiguration 接口
该接口用于为 MongoDB 的不同搜索模式(ANN、ENN、Hybrid)提供统一的配置接口。
定义通用的配置方法,比如获取索引名称、数据库名称、连接配置等。
[Redacted Copy code
package dev.langchain4j.store.embedding.mongodb;
public interface MongoDbConfiguration {
String getDatabaseName();
String getCollectionName();
String getIndexName();
boolean isCreateIndexEnabled();
}
为每种搜索模式创建具体的实现类
MongoDbConfigurationANN : 当前的实现方式基本上是 ANN(Approximate Nearest Neighbor)搜索,可以将现有逻辑迁移到这个类中。
MongoDbConfigurationENN : 新增 ENN 搜索的支持。
MongoDbConfigurationHybrid : 新增混合搜索的支持(需要额外的全文搜索索引)。
[Redacted Copy code
package dev.langchain4j.store.embedding.mongodb;
public class MongoDbConfigurationANN implements MongoDbConfiguration {
private final String databaseName;
private final String collectionName;
private final String indexName;
private final boolean createIndex;
public MongoDbConfigurationANN(String databaseName, String collectionName, String indexName, boolean createIndex) {
this.databaseName = databaseName;
this.collectionName = collectionName;
this.indexName = indexName;
this.createIndex = createIndex;
}
@[Redacted Person]
public String getDatabaseName() {
return databaseName;
}
@[Redacted Person]
public String getCollectionName() {
return collectionName;
}
@[Redacted Person]
public String getIndexName() {
return indexName;
}
@[Redacted Person]
public boolean isCreateIndexEnabled() {
return createIndex;
}
}
public class MongoDbConfigurationENN implements MongoDbConfiguration {
private final String databaseName;
private final String collectionName;
private final String indexName;
private final boolean createIndex;
public MongoDbConfigurationENN(String databaseName, String collectionName, String indexName, boolean createIndex) {
this.databaseName = databaseName;
this.collectionName = collectionName;
this.indexName = indexName;
this.createIndex = createIndex;
}
@[Redacted Person]
public String getDatabaseName() {
return databaseName;
}
@[Redacted Person]
public String getCollectionName() {
return collectionName;
}
@[Redacted Person]
public String getIndexName() {
return indexName;
}
@[Redacted Person]
public boolean isCreateIndexEnabled() {
return createIndex;
}
}
public class MongoDbConfigurationHybrid implements MongoDbConfiguration {
private final String databaseName;
private final String collectionName;
private final String vectorIndexName;
private final String textIndexName; // 用于全文搜索
private final boolean createIndex;
public MongoDbConfigurationHybrid(String databaseName, String collectionName, String vectorIndexName, String textIndexName, boolean createIndex) {
this.databaseName = databaseName;
this.collectionName = collectionName;
this.vectorIndexName = vectorIndexName;
this.textIndexName = textIndexName;
this.createIndex = createIndex;
}
@[Redacted Person]
public String getDatabaseName() {
return databaseName;
}
@[Redacted Person]
public String getCollectionName() {
return collectionName;
}
@[Redacted Person]
public String getIndexName() {
return vectorIndexName; // 默认返回向量索引
}
public String getTextIndexName() {
return textIndexName;
}
@[Redacted Person]
public boolean isCreateIndexEnabled() {
return createIndex;
}
}
修改 MongoDbEmbeddingStore
接受 MongoDbConfiguration 接口作为参数,根据配置动态支持不同的搜索模式。
在 search 方法中,根据配置类型来选择适当的搜索策略。
示例代码 :
[Redacted Copy code
package dev.langchain4j.store.embedding.mongodb;
import com.mongodb.client.MongoClient;
import com.mongodb.client.model.Filters;
import dev.langchain4j.data.embedding.Embedding;
import dev.langchain4j.data.segment.TextSegment;
import dev.langchain4j.store.embedding.EmbeddingMatch;
import dev.langchain4j.store.embedding.EmbeddingSearchRequest;
import dev.langchain4j.store.embedding.EmbeddingSearchResult;
import dev.langchain4j.store.embedding.EmbeddingStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
public class MongoDbEmbeddingStore implements EmbeddingStore<TextSegment> {
private static final Logger log = LoggerFactory.getLogger(MongoDbEmbeddingStore.class);
private final MongoClient mongoClient;
private final MongoDbConfiguration configuration;
public MongoDbEmbeddingStore(MongoClient mongoClient, MongoDbConfiguration configuration) {
this.mongoClient = mongoClient;
this.configuration = configuration;
}
@[Redacted Person]
public EmbeddingSearchResult<TextSegment> search(EmbeddingSearchRequest request) {
if (configuration instanceof MongoDbConfigurationENN) {
return searchUsingENN(request);
} else if (configuration instanceof MongoDbConfigurationHybrid) {
return searchUsingHybrid(request);
} else {
return searchUsingANN(request);
}
}
private EmbeddingSearchResult<TextSegment> searchUsingANN(EmbeddingSearchRequest request) {
log.info("Performing ANN search...");
// 当前的 ANN 搜索逻辑
return new EmbeddingSearchResult<>(new ArrayList<>());
}
private EmbeddingSearchResult<TextSegment> searchUsingENN(EmbeddingSearchRequest request) {
log.info("Performing ENN search...");
// ENN 搜索逻辑:使用 MongoDB 的精确向量搜索
return new EmbeddingSearchResult<>(new ArrayList<>());
}
private EmbeddingSearchResult<TextSegment> searchUsingHybrid(EmbeddingSearchRequest request) {
log.info("Performing Hybrid search...");
// 混合搜索逻辑:结合向量搜索和全文搜索
return new EmbeddingSearchResult<>(new ArrayList<>());
}
}
支持 Hybrid 搜索的逻辑
Hybrid 搜索需要两个索引:
向量搜索索引 :用于语义搜索。
全文搜索索引 :用于传统的文本搜索。
使用 MongoDB 的 Reciprocal Rank Fusion (RRF) 技术,将两个搜索结果合并。
示例流程:
使用向量索引执行向量搜索。
使用文本索引执行全文搜索。
合并两个结果集合并并排序。
测试
为每种搜索模式编写单独的集成测试:
MongoDbEmbeddingStoreENNIT
MongoDbEmbeddingStoreHybridIT
测试不同配置下的搜索行为是否符合预期。
可能的改动
破坏性变更 :Hybrid 搜索需要两个索引(向量索引和文本索引),这可能会对现有用户产生影响。如果用户仅配置了一个索引,可能会导致异常。
解决方案 :为 Hybrid 搜索提供合理的默认行为(如仅启用向量搜索)。
总结
通过引入 MongoDbConfiguration 接口和为 ENN、Hybrid 搜索模式分别创建配置实现,可以在不破坏现有 ANN 搜索功能的基础上,扩展对 MongoDB Atlas 高级搜索功能的支持。这种设计方案具有良好的扩展性,方便未来支持更多的搜索模式或功能。
Show full message · 244 lines 根据需求和解决方案,以下是需要修改或新增的文件列表以及具体的修改内容:
1. 新增文件
MongoDbConfiguration.java
定义不同搜索模式的统一配置接口。
路径 : src/main/java/dev/langchain4j/store/embedding/mongodb/MongoDbConfiguration.java
MongoDbConfigurationANN.java
实现 MongoDbConfiguration 接口,支持 ANN(Approximate Nearest Neighbor)搜索(当前实现方式)。
路径 : src/main/java/dev/langchain4j/store/embedding/mongodb/MongoDbConfigurationANN.java
MongoDbConfigurationENN.java
实现 MongoDbConfiguration 接口,支持 ENN(Exact Nearest Neighbor)搜索。
路径 : src/main/java/dev/langchain4j/store/embedding/mongodb/MongoDbConfigurationENN.java
MongoDbConfigurationHybrid.java
实现 MongoDbConfiguration 接口,支持 Hybrid 搜索(混合搜索)。
路径 : src/main/java/dev/langchain4j/store/embedding/mongodb/MongoDbConfigurationHybrid.java
2. 修改文件
MongoDbEmbeddingStore.java
路径 : src/main/java/dev/langchain4j/store/embedding/mongodb/MongoDbEmbeddingStore.java
修改内容 :
将 MongoDbEmbeddingStore 修改为支持动态配置,接受 MongoDbConfiguration。
添加对 ENN 和 Hybrid 搜索的支持:
新增 searchUsingENN 方法:实现 MongoDB ENN 搜索逻辑。
新增 searchUsingHybrid 方法:实现 MongoDB Hybrid 搜索逻辑,结合向量搜索和全文搜索。
在 search 方法中根据配置类型调用相应的搜索逻辑。
pom.xml
路径 : langchain4j-mongodb-atlas/pom.xml
修改内容 :
如果使用 MongoDB 的 ENN 或 Hybrid 搜索功能,需要确保 MongoDB 驱动版本支持这些特性(推荐 mongodb-driver-sync 版本 >= 5.2.0)。
xml Copy code
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>[Redacted Person]-driver-sync</artifactId>
<version>5.2.0</version>
</dependency>
MongoDbEmbeddingStoreIT.java
路径 : src/test/java/dev/langchain4j/store/embedding/mongodb/MongoDbEmbeddingStoreIT.java
修改内容 :
添加 ENN 和 Hybrid 搜索的测试用例。
使用 MongoDbConfigurationENN 和 MongoDbConfigurationHybrid 初始化 MongoDbEmbeddingStore 并验证行为。
3. 新增测试文件
MongoDbEmbeddingStoreENNIT.java
路径 : src/test/java/dev/langchain4j/store/embedding/mongodb/MongoDbEmbeddingStoreENNIT.java
内容 :
验证 ENN 搜索的功能是否正常。
测试精确向量搜索的结果是否符合预期。
MongoDbEmbeddingStoreHybridIT.java
路径 : src/test/java/dev/langchain4j/store/embedding/mongodb/MongoDbEmbeddingStoreHybridIT.java
内容 :
验证 Hybrid 搜索的功能是否正常。
测试向量搜索和全文搜索的结果是否正确融合。
4. 修改或扩展工具类
MappingUtils.java
路径 : src/main/java/dev/langchain4j/store/embedding/mongodb/MappingUtils.java
修改内容 :
添加对 Hybrid 搜索中文本索引的支持,扩展 fromIndexMapping 方法以支持全文搜索字段。
更新 toMongoDbDocument 方法,确保可以存储与 Hybrid 搜索相关的元数据或文本字段。
MongoDbTestFixture.java
路径 : src/test/java/dev/langchain4j/store/embedding/mongodb/MongoDbTestFixture.java
修改内容 :
为 ENN 和 Hybrid 搜索添加初始化逻辑,支持创建对应的索引。
新增创建全文搜索索引的方法(Hybrid 搜索需要两个索引:向量索引和文本索引)。
文件修改总结
文件路径 修改类型 说明 src/main/java/dev/langchain4j/store/embedding/mongodb/MongoDbConfiguration.java新增 定义 MongoDB 搜索配置接口。 src/main/java/dev/langchain4j/store/embedding/mongodb/MongoDbConfigurationANN.java新增 实现 ANN 搜索的配置。 src/main/java/dev/langchain4j/store/embedding/mongodb/MongoDbConfigurationENN.java新增 实现 ENN 搜索的配置。 src/main/java/dev/langchain4j/store/embedding/mongodb/MongoDbConfigurationHybrid.java新增 实现 Hybrid 搜索的配置,支持向量和全文搜索。 src/main/java/dev/langchain4j/store/embedding/mongodb/MongoDbEmbeddingStore.java修改 添加对 ENN 和 Hybrid 搜索的支持。 langchain4j-mongodb-atlas/pom.xml修改 确保 MongoDB 驱动版本支持 ENN 和 Hybrid 搜索功能。 src/test/java/dev/langchain4j/store/embedding/mongodb/MongoDbEmbeddingStoreIT.java修改 添加对 ENN 和 Hybrid 搜索的集成测试用例。 src/test/java/dev/langchain4j/store/embedding/mongodb/MongoDbEmbeddingStoreENNIT.java新增 为 ENN 搜索编写集成测试用例。 src/test/java/dev/langchain4j/store/embedding/mongodb/MongoDbEmbeddingStoreHybridIT.java新增 为 Hybrid 搜索编写集成测试用例。 src/main/java/dev/langchain4j/store/embedding/mongodb/MappingUtils.java修改 添加对 Hybrid 搜索中文本索引的支持。 src/test/java/dev/langchain4j/store/embedding/mongodb/MongoDbTestFixture.java修改 添加 ENN 和 Hybrid 搜索初始化逻辑,以及创建全文搜索索引的方法。
后续步骤
修改代码: 按照上述文件修改和新增内容逐步实现。
测试验证: 运行新增的测试用例,确保 ENN 和 Hybrid 搜索功能正常工作。
文档更新: 更新项目文档,说明如何配置和使用 ENN 和 Hybrid 搜索功能。
这样可以确保 langchain4j-mongodb-atlas 对 MongoDB Atlas 的 ENN 和 Hybrid 搜索功能提供全面支持。
创建或修改必要的文件。
确保代码能正常运行。
添加集成测试和单元测试。
3. 添加变更到 Git 暂存区 bash Copy code
# 添加所有变更
git add .
# 提交变更
git commit -m "[FEATURE] Support MongoDB ENN and Hybrid Search"
4. 推送分支到远程仓库 bash Copy code
git push origin feature/mongodb-enn-hybrid-search
5. 创建 Pull Request (PR)
打开 GitHub 仓库 :
进入 langchain4j 的 GitHub 仓库页面。
创建 PR :
在仓库页面,点击 Pull requests 标签。
点击右侧的 New pull request 按钮。
在 compare 下拉框中,选择新分支 feature/mongodb-enn-hybrid-search。
在 base 下拉框中,确保选择主分支 main。
填写 PR 信息 :
标题 : [FEATURE] Support MongoDB ENN and Hybrid Search
描述 :
markdown Copy code
### Summary
This PR adds support for MongoDB Atlas Exact Nearest Neighbor (ENN) search and Hybrid search.
### Changes
- Introduced `MongoDbConfiguration` interface to support multiple search modes.
- Added `MongoDbConfigurationANN`, `MongoDbConfigurationENN`, and `MongoDbConfigurationHybrid` implementations.
- Updated `MongoDbEmbeddingStore` to support ENN and Hybrid search.
- Added integration tests for ENN and Hybrid search.
### How to Test
- Run the integration tests: `MongoDbEmbeddingStoreENNIT` and `MongoDbEmbeddingStoreHybridIT`.
### Breaking Changes
- None.
创建 PR :
点击 Create pull request 按钮。
6. 等待代码审核
通知项目维护者(例如,通过 @mention),请求他们对 PR 进行审核。
根据反馈对代码进行修改,并在本地提交后推送:
bash Copy code
# 修改代码后
git add .
git commit -m "Addressed review comments"
git push origin feature/mongodb-enn-hybrid-search
7. 合并 PR
完成以上步骤后,langchain4j 将成功支持 MongoDB Atlas 的 ENN 和 Hybrid 搜索功能!
package dev.langchain4j.store.embedding.mongodb;
import com.mongodb.MongoClientSettings;
import com.mongodb.MongoCommandException;
import com.mongodb.client.AggregateIterable;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.CreateCollectionOptions;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.SearchIndexModel;
import com.mongodb.client.model.SearchIndexType;
import com.mongodb.client.model.search.VectorSearchOptions;
import com.mongodb.client.result.InsertManyResult;
import dev.langchain4j.data.embedding.Embedding;
import dev.langchain4j.data.segment.TextSegment;
import dev.langchain4j.store.embedding.EmbeddingMatch;
import dev.langchain4j.store.embedding.EmbeddingSearchRequest;
import dev.langchain4j.store.embedding.EmbeddingSearchResult;
import dev.langchain4j.store.embedding.EmbeddingStore;
import dev.langchain4j.store.embedding.filter.Filter;
import org.bson.Document;
import org.bson.codecs.configuration.CodecRegistry;
import org.bson.codecs.pojo.PojoCodecProvider;
import org.bson.conversions.Bson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.StreamSupport;
import static com.mongodb.client.model.Aggregates.;
import static com.mongodb.client.model.Projections. ;
import static com.mongodb.client.model.search.SearchPath.fieldPath;
import static com.mongodb.client.model.search.VectorSearchOptions.approximateVectorSearchOptions;
import static dev.langchain4j.internal.Utils.;
import static dev.langchain4j.internal.ValidationUtils. ;
import static dev.langchain4j.store.embedding.mongodb.IndexMapping.defaultIndexMapping;
import static dev.langchain4j.store.embedding.mongodb.MappingUtils.*;
import static dev.langchain4j.store.embedding.mongodb.MongoDbMetadataFilterMapper.map;
import static java.util.Arrays.asList;
import static dev.langchain4j.store.embedding.mongodb.MappingUtils.fromIndexMapping;
import static dev.langchain4j.store.embedding.mongodb.MappingUtils.toMongoDbDocument;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static java.util.stream.Collectors.toList;
import static org.bson.codecs.configuration.CodecRegistries.fromProviders;
import static org.bson.codecs.configuration.CodecRegistries.fromRegistries;
/**
Represents a MongoDB indexed collection as an embedding store.
More info
on using MongoDb vector search.
tutorial
how to use vector search with MongoDB Atlas (great starting point).
To deploy a local instance of Atlas, see
this guide.
If you are using a free tier, {@code #createIndex = true} might not be supported,
so you will need to create an index manually.
In your Atlas web console go to: DEPLOYMENT -> Database -> {your cluster} -> Atlas Search tab
-> Create Index Search -> "JSON Editor" under "Atlas Vector Search" (not "Atlas Search") -> Next
-> Select your database in the left pane -> Insert the following JSON into the right pane
(set "numDimensions" and additional metadata fields to desired values)
{
"fields" : [ {
code Copy code
"type" : "vector",
code Copy code
"path" : "embedding",
code Copy code
"numDimensions" : 384,
code Copy code
"similarity" : "cosine"
}, {
code Copy code
"type" : "filter",
code Copy code
"path" : "metadata.test-key"
} ]
}
-> Next -> Create Search Index
*/
public class MongoDbEmbeddingStore implements EmbeddingStore {
private static final int SECONDS_TO_WAIT_FOR_INDEX = 20;
private static final Logger log = LoggerFactory.getLogger(MongoDbEmbeddingStore.class);
private final MongoCollection collection;
private final String indexName;
private final long maxResultRatio;
private final Bson globalPrefilter;
public MongoDbEmbeddingStore(MongoClient mongoClient,
String databaseName,
String collectionName,
String indexName,
Long maxResultRatio,
CreateCollectionOptions createCollectionOptions,
Bson filter,
IndexMapping indexMapping,
Boolean createIndex) {
databaseName = ensureNotNull(databaseName, "databaseName");
collectionName = ensureNotNull(collectionName, "collectionName");
createIndex = getOrDefault(createIndex, false);
this.indexName = ensureNotNull(indexName, "indexName");
this.maxResultRatio = getOrDefault(maxResultRatio, 10L);
code Copy code
CodecRegistry pojoCodecRegistry = fromProviders(PojoCodecProvider.builder()
.register(MongoDbDocument.class, MongoDbMatchedDocument.class)
.build());
CodecRegistry codecRegistry = fromRegistries(MongoClientSettings.getDefaultCodecRegistry(), pojoCodecRegistry);
// create collection if not exist
MongoDatabase database = mongoClient.getDatabase(databaseName);
if (!isCollectionExist(database, collectionName)) {
createCollection(database, collectionName, getOrDefault(createCollectionOptions, new CreateCollectionOptions()));
}
this.collection = database.getCollection(collectionName, MongoDbDocument.class).withCodecRegistry(codecRegistry);
this.globalPrefilter = filter;
if (!indexExists(this.indexName)) {
if (createIndex) {
createIndex(this.indexName, getOrDefault(indexMapping, defaultIndexMapping()));
} else {
throw new RuntimeException(String.format(
"Search Index '%s' not found and must be created via createIndex(true), or manually as a vector search index (not a regular index), via the createSearchIndexes command",
this.indexName));
}
}
Show full message · 419 lines 要在 MongoDbEmbeddingStore 中添加对 MongoDB Atlas 的 ENN(Exact Nearest Neighbor)和 Hybrid 搜索(混合搜索)的支持,需要对代码进行以下修改:
主要修改目标
支持 ENN 搜索:
ENN 搜索需要使用 MongoDB Atlas 提供的精确向量搜索功能。
修改 search 方法,支持 ENN 搜索逻辑。
支持 Hybrid 搜索:
Hybrid 搜索需要结合向量搜索和全文搜索。
修改 search 方法,结合向量搜索和全文搜索的结果。
引入配置机制:
使用 MongoDbConfiguration 接口动态选择搜索模式(ANN、ENN 或 Hybrid)。
代码实现步骤
1. 添加 MongoDbConfiguration 接口及实现类
增加配置接口和三个实现类,用于不同搜索模式(ANN、ENN 和 Hybrid)。
[Redacted Copy code
// 新增文件: MongoDbConfiguration.java
package dev.langchain4j.store.embedding.mongodb;
public interface MongoDbConfiguration {
String getDatabaseName();
String getCollectionName();
String getIndexName();
boolean isCreateIndexEnabled();
}
[Redacted Copy code
// 新增文件: MongoDbConfigurationANN.java
package dev.langchain4j.store.embedding.mongodb;
public class MongoDbConfigurationANN implements MongoDbConfiguration {
private final String databaseName;
private final String collectionName;
private final String indexName;
private final boolean createIndex;
public MongoDbConfigurationANN(String databaseName, String collectionName, String indexName, boolean createIndex) {
this.databaseName = databaseName;
this.collectionName = collectionName;
this.indexName = indexName;
this.createIndex = createIndex;
}
@[Redacted Person]
public String getDatabaseName() {
return databaseName;
}
@[Redacted Person]
public String getCollectionName() {
return collectionName;
}
@[Redacted Person]
public String getIndexName() {
return indexName;
}
@[Redacted Person]
public boolean isCreateIndexEnabled() {
return createIndex;
}
}
[Redacted Copy code
// 新增文件: MongoDbConfigurationENN.java
package dev.langchain4j.store.embedding.mongodb;
public class MongoDbConfigurationENN implements MongoDbConfiguration {
private final String databaseName;
private final String collectionName;
private final String indexName;
private final boolean createIndex;
public MongoDbConfigurationENN(String databaseName, String collectionName, String indexName, boolean createIndex) {
this.databaseName = databaseName;
this.collectionName = collectionName;
this.indexName = indexName;
this.createIndex = createIndex;
}
@[Redacted Person]
public String getDatabaseName() {
return databaseName;
}
@[Redacted Person]
public String getCollectionName() {
return collectionName;
}
@[Redacted Person]
public String getIndexName() {
return indexName;
}
@[Redacted Person]
public boolean isCreateIndexEnabled() {
return createIndex;
}
}
[Redacted Copy code
// 新增文件: MongoDbConfigurationHybrid.java
package dev.langchain4j.store.embedding.mongodb;
public class MongoDbConfigurationHybrid implements MongoDbConfiguration {
private final String databaseName;
private final String collectionName;
private final String vectorIndexName;
private final String textIndexName; // 用于全文搜索
private final boolean createIndex;
public MongoDbConfigurationHybrid(String databaseName, String collectionName, String vectorIndexName, String textIndexName, boolean createIndex) {
this.databaseName = databaseName;
this.collectionName = collectionName;
this.vectorIndexName = vectorIndexName;
this.textIndexName = textIndexName;
this.createIndex = createIndex;
}
@[Redacted Person]
public String getDatabaseName() {
return databaseName;
}
@[Redacted Person]
public String getCollectionName() {
return collectionName;
}
@[Redacted Person]
public String getIndexName() {
return vectorIndexName; // 默认返回向量索引
}
public String getTextIndexName() {
return textIndexName;
}
@[Redacted Person]
public boolean isCreateIndexEnabled() {
return createIndex;
}
}
2. 修改 MongoDbEmbeddingStore 构造器
修改 MongoDbEmbeddingStore,支持动态配置不同的搜索模式。
[Redacted Copy code
// 修改构造器,接受 MongoDbConfiguration
private final MongoDbConfiguration configuration;
public MongoDbEmbeddingStore(MongoClient mongoClient,
MongoDbConfiguration configuration) {
this.configuration = configuration;
// 使用配置初始化数据库和集合
MongoDatabase database = mongoClient.getDatabase(configuration.getDatabaseName());
CodecRegistry codecRegistry = CodecRegistries.fromRegistries(
MongoClientSettings.getDefaultCodecRegistry(),
CodecRegistries.fromProviders(PojoCodecProvider.builder()
.register(MongoDbDocument.class, MongoDbMatchedDocument.class)
.build()));
this.collection = database.getCollection(configuration.getCollectionName(), MongoDbDocument.class)
.withCodecRegistry(codecRegistry);
// 创建索引(如果配置允许自动创建)
if (configuration.isCreateIndexEnabled() && !indexExists(configuration.getIndexName())) {
createIndex(configuration.getIndexName(), defaultIndexMapping());
}
}
3. 修改 search 方法
根据 MongoDbConfiguration 类型,动态执行 ANN、ENN 或 Hybrid 搜索。
[Redacted Copy code
@[Redacted Person]
public EmbeddingSearchResult<TextSegment> search(EmbeddingSearchRequest request) {
if (configuration instanceof MongoDbConfigurationENN) {
return searchUsingENN(request);
} else if (configuration instanceof MongoDbConfigurationHybrid) {
return searchUsingHybrid(request);
} else {
return searchUsingANN(request);
}
}
// ENN 搜索逻辑
private EmbeddingSearchResult<TextSegment> searchUsingENN(EmbeddingSearchRequest request) {
log.info("Performing ENN search...");
// 使用 MongoDB Atlas ENN 搜索
List<Double> queryVector = request.queryEmbedding().vectorAsList().stream()
.map(Float::doubleValue)
.collect(Collectors.toList());
long numCandidates = request.maxResults() * maxResultRatio;
ArrayList<Bson> pipeline = new ArrayList<>();
pipeline.add(vectorSearch(
fieldPath("embedding"),
queryVector,
configuration.getIndexName(),
request.maxResults(),
VectorSearchOptions.vectorSearchOptions(numCandidates)));
pipeline.add(project(fields(
metaVectorSearchScore("score"),
include("embedding", "metadata", "text"))));
List<EmbeddingMatch<TextSegment>> result = executeSearchPipeline(pipeline);
return new EmbeddingSearchResult<>(result);
}
// Hybrid 搜索逻辑
private EmbeddingSearchResult<TextSegment> searchUsingHybrid(EmbeddingSearchRequest request) {
log.info("Performing Hybrid search...");
// 执行向量搜索
EmbeddingSearchResult<TextSegment> vectorResults = searchUsingANN(request);
// 执行全文搜索(假设实现了一种全文搜索逻辑)
List<EmbeddingMatch<TextSegment>> textResults = performTextSearch(request.textQuery(), configuration.getTextIndexName());
// 合并两种搜索结果(例如 Reciprocal Rank Fusion)
List<EmbeddingMatch<TextSegment>> mergedResults = mergeResults(vectorResults.matches(), textResults);
return new EmbeddingSearchResult<>(mergedResults);
}
4. 添加工具方法
performTextSearch:实现全文搜索。
mergeResults:实现 Hybrid 搜索结果合并。
[Redacted Copy code
private List<EmbeddingMatch<TextSegment>> performTextSearch(String query, String textIndexName) {
// 使用 MongoDB 的全文搜索
Bson matchStage = match(Filters.text(query));
Bson projectStage = project(fields(include("text", "metadata")));
AggregateIterable<Document> results = collection.aggregate(Arrays.asList(matchStage, projectStage));
return StreamSupport.stream(results.spliterator(), false)
.map(doc -> new EmbeddingMatch<>(0.0, doc.getObjectId("_id").toString(), null, TextSegment.from(doc.getString("text"))))
.collect(Collectors.toList());
}
private List<EmbeddingMatch<TextSegment>> mergeResults(List<EmbeddingMatch<TextSegment>> vectorResults,
List<EmbeddingMatch<TextSegment>> textResults) {
// 合并搜索结果(简单实现:按分数排序)
List<EmbeddingMatch<TextSegment>> mergedResults = new ArrayList<>(vectorResults);
mergedResults.addAll(textResults);
mergedResults.sort(Comparator.comparingDouble(EmbeddingMatch::score).reversed());
return mergedResults;
}
总结
增加了 MongoDbConfiguration 接口及其实现类,便于动态支持不同搜索模式。
修改了 MongoDbEmbeddingStore 的构造逻辑和 search 方法,支持 ENN 和 Hybrid 搜索。
添加了工具方法,用于执行全文搜索和合并搜索结果。
这些修改可以在不破坏现有功能的基础上,为 langchain4j 添加对 MongoDB Atlas ENN 和 Hybrid 搜索的支持。
Show full message · 282 lines searchUsingANN 是当前 MongoDbEmbeddingStore 类中已有的默认搜索逻辑(基于 Approximate Nearest Neighbor,ANN 搜索)。虽然代码中没有明确写出 searchUsingANN 方法,但实际上它就是当前的 search 方法的核心逻辑。
你需要将现有的 search 方法逻辑提取出来,重构为一个独立的 searchUsingANN 方法,以便清晰地支持三种搜索模式(ANN、ENN 和 Hybrid)。下面是如何实现的具体步骤:
提取 searchUsingANN 方法
将现有的 search 方法逻辑重构为 searchUsingANN 方法:
[Redacted Copy code
// 新增 searchUsingANN 方法
private EmbeddingSearchResult<TextSegment> searchUsingANN(EmbeddingSearchRequest request) {
// 提取现有 search 方法逻辑
List<Double> queryVector = request.queryEmbedding().vectorAsList().stream()
.map(Float::doubleValue)
.collect(toList());
long numCandidates = request.maxResults() * maxResultRatio;
Bson postFilter = null;
if (request.minScore() > 0) {
postFilter = Filters.gte("score", request.minScore());
}
if (request.filter() != null) {
Bson newFilter = map(request.filter());
postFilter = postFilter == null ? newFilter : Filters.and(postFilter, newFilter);
}
VectorSearchOptions vectorSearchOptions = this.globalPrefilter == null
? approximateVectorSearchOptions(numCandidates)
: approximateVectorSearchOptions(numCandidates).filter(this.globalPrefilter);
ArrayList<Bson> pipeline = new ArrayList<>();
pipeline.add(vectorSearch(
fieldPath("embedding"),
queryVector,
indexName,
request.maxResults(),
vectorSearchOptions));
pipeline.add(project(fields(
metaVectorSearchScore("score"),
include("embedding", "metadata", "text"))));
if (postFilter != null) {
Bson match = match(postFilter);
pipeline.add(match);
}
try {
AggregateIterable<MongoDbMatchedDocument> results = collection.aggregate(pipeline, MongoDbMatchedDocument.class);
List<EmbeddingMatch<TextSegment>> result = StreamSupport.stream(results.spliterator(), false)
.map(MappingUtils::toEmbeddingMatch)
.collect(toList());
return new EmbeddingSearchResult<>(result);
} catch (MongoCommandException e) {
log.error("Error in MongoDBEmbeddingStore.search", e);
throw new RuntimeException(e);
}
}
修改 search 方法
现在,将 search 方法改为根据配置动态调用 searchUsingANN、searchUsingENN 或 searchUsingHybrid:
[Redacted Copy code
@[Redacted Person]
public EmbeddingSearchResult<TextSegment> search(EmbeddingSearchRequest request) {
if (configuration instanceof MongoDbConfigurationENN) {
return searchUsingENN(request); // 调用 ENN 搜索
} else if (configuration instanceof MongoDbConfigurationHybrid) {
return searchUsingHybrid(request); // 调用 Hybrid 搜索
} else {
return searchUsingANN(request); // 调用默认 ANN 搜索
}
}
完整代码结构
经过重构后,MongoDbEmbeddingStore 的搜索相关方法结构如下:
searchUsingANN :
提取当前的 ANN 搜索逻辑。
用于 Approximate Nearest Neighbor 搜索。
searchUsingENN :
实现 MongoDB Atlas 的 ENN 搜索逻辑。
使用精确向量搜索。
searchUsingHybrid :
结合向量搜索(ANN 或 ENN)和全文搜索的结果。
使用 Reciprocal Rank Fusion 或其他合并策略。
search :
根据配置调用对应的搜索逻辑(ANN、ENN 或 Hybrid)。
最终的 MongoDbEmbeddingStore 搜索方法代码
通过这种方式,我们实现了以下功能:
提取现有的搜索逻辑为 searchUsingANN 方法。
添加了 searchUsingENN 和 searchUsingHybrid 方法,用于支持新的搜索模式。
修改了 search 方法,根据配置动态选择搜索逻辑。
从现在开始,你可以在新的 searchUsingENN 和 searchUsingHybrid 方法中逐步实现 ENN 和 Hybrid 搜索的具体逻辑。
Dataset releases Not yet included in a published release.
public static Builder builder() {
return new Builder();
}
public static class Builder {
code Copy code
private MongoClient mongoClient;
private String databaseName;
private String collectionName;
private String indexName;
private Long maxResultRatio;
private CreateCollectionOptions createCollectionOptions;
private Bson filter;
private IndexMapping indexMapping;
/**
* Whether MongoDB Atlas is deployed in cloud
*
* <p>if true, you need to create index in <a href="https://cloud.mongodb.com/">MongoDB Atlas</a></p>
* <p>if false, {@link MongoDbEmbeddingStore} will create collection and index automatically</p>
*/
private Boolean createIndex;
/**
* Build Mongo Client, Please close the client to release resources after usage
*/
public Builder fromClient(MongoClient mongoClient) {
this.mongoClient = mongoClient;
return this;
}
public Builder databaseName(String databaseName) {
this.databaseName = databaseName;
return this;
}
public Builder collectionName(String collectionName) {
this.collectionName = collectionName;
return this;
}
public Builder indexName(String indexName) {
this.indexName = indexName;
return this;
}
public Builder maxResultRatio(Long maxResultRatio) {
this.maxResultRatio = maxResultRatio;
return this;
}
public Builder createCollectionOptions(CreateCollectionOptions createCollectionOptions) {
this.createCollectionOptions = createCollectionOptions;
return this;
}
/**
* Document query filter, all fields included in filter must be contained in {@link IndexMapping#metadataFieldNames}
*
* <p>For example:</p>
*
* <ul>
* <li>AND filter: Filters.and(Filters.in("type", asList("TXT", "md")), Filters.eqFull("test-key", "test-value"))</li>
* <li>OR filter: Filters.or(Filters.in("type", asList("TXT", "md")), Filters.eqFull("test-key", "test-value"))</li>
* </ul>
*
* @param filter document query filter
* @return builder
*/
public Builder filter(Bson filter) {
this.filter = filter;
return this;
}
/**
* set MongoDB search index fields mapping
*
* <p>if {@link Builder#createIndex} is true, then indexMapping not work</p>
*
* @param indexMapping MongoDB search index fields mapping
* @return builder
*/
public Builder indexMapping(IndexMapping indexMapping) {
this.indexMapping = indexMapping;
return this;
}
/**
* Set whether in production mode, production mode will not create index automatically
*
* <p>default value is false</p>
*
* @param createIndex whether in production mode
* @return builder
*/
public Builder createIndex(Boolean createIndex) {
this.createIndex = createIndex;
return this;
}
public MongoDbEmbeddingStore build() {
return new MongoDbEmbeddingStore(
mongoClient, databaseName, collectionName, indexName,
maxResultRatio, createCollectionOptions, filter,
indexMapping, createIndex);
}
@[Redacted Person]
public String add(Embedding embedding) {
String id = randomUUID();
add(id, embedding);
return id;
}
@[Redacted Person]
public void add(String id, Embedding embedding) {
addInternal(id, embedding, null);
}
@[Redacted Person]
public String add(Embedding embedding, TextSegment textSegment) {
String id = randomUUID();
addInternal(id, embedding, textSegment);
return id;
}
@[Redacted Person]
public List addAll(List embeddings) {
List ids = embeddings.stream()
.map(ignored -> randomUUID())
.collect(toList());
addAll(ids, embeddings, null);
return ids;
}
@[Redacted Person]
public void removeAll() {
collection.deleteMany(Filters.empty());
}
@[Redacted Person]
public void removeAll(Collection ids) {
ensureNotEmpty(ids, "ids");
collection.deleteMany(Filters.in("_id", ids));
}
@[Redacted Person]
public void removeAll(Filter filter) {
ensureNotNull(filter, "filter");
collection.deleteMany(map(filter));
}
@[Redacted Person]
public EmbeddingSearchResult search(EmbeddingSearchRequest request) {
List queryVector = request.queryEmbedding().vectorAsList().stream()
.map(Float::doubleValue)
.collect(toList());
long numCandidates = request.maxResults() * maxResultRatio;
code Copy code
Bson postFilter = null;
if (request.minScore() > 0) {
postFilter = Filters.gte("score", request.minScore());
}
if (request.filter() != null) {
Bson newFilter = map(request.filter());
postFilter = postFilter == null ? newFilter : Filters.and(postFilter, newFilter);
}
VectorSearchOptions vectorSearchOptions = this.globalPrefilter == null
? approximateVectorSearchOptions(numCandidates)
: approximateVectorSearchOptions(numCandidates).filter(this.globalPrefilter);
ArrayList<Bson> pipeline = new ArrayList<>();
pipeline.add(vectorSearch(
fieldPath("embedding"),
queryVector,
indexName,
request.maxResults(),
vectorSearchOptions));
pipeline.add(project(fields(
metaVectorSearchScore("score"),
include("embedding", "metadata", "text"))));
if (postFilter != null) {
Bson match = match(postFilter);
pipeline.add(match);
}
try {
AggregateIterable<MongoDbMatchedDocument> results = collection.aggregate(pipeline, MongoDbMatchedDocument.class);
List<EmbeddingMatch<TextSegment>> result = StreamSupport.stream(results.spliterator(), false)
.map(MappingUtils::toEmbeddingMatch)
.collect(toList());
return new EmbeddingSearchResult<>(result);
} catch (MongoCommandException e) {
log.error("Error in MongoDBEmbeddingStore.search", e);
throw new RuntimeException(e);
}
private void addInternal(String id, Embedding embedding, TextSegment embedded) {
addAll(singletonList(id), singletonList(embedding), embedded == null ? null : singletonList(embedded));
}
@[Redacted Person]
public void addAll(List ids, List embeddings, List embedded) {
if (isNullOrEmpty(ids) || isNullOrEmpty(embeddings)) {
log.info("do not add empty embeddings to MongoDB Atlas");
return;
}
ensureTrue(ids.size() == embeddings.size(), "ids size is not equal to embeddings size");
ensureTrue(embedded == null || embeddings.size() == embedded.size(), "embeddings size is not equal to embedded size");
code Copy code
List<MongoDbDocument> documents = new ArrayList<>(ids.size());
for (int i = 0; i < ids.size(); i++) {
String id = ids.get(i);
MongoDbDocument document = toMongoDbDocument(id, embeddings.get(i), embedded == null ? null : embedded.get(i));
documents.add(document);
}
InsertManyResult result = collection.insertMany(documents);
if (!result.wasAcknowledged()) {
String errMsg = String.format("[MongoDbEmbeddingStore] Add document failed, Document=%s", documents);
log.error(errMsg);
throw new RuntimeException(errMsg);
}
private boolean isCollectionExist(MongoDatabase database, String collectionName) {
return StreamSupport.stream(database.listCollectionNames().spliterator(), false)
.anyMatch(collectionName::equals);
}
private void createCollection(MongoDatabase database, String collectionName, CreateCollectionOptions createCollectionOptions) {
database.createCollection(collectionName, createCollectionOptions);
}
private boolean indexExists(String indexName) {
Document indexRecord = indexRecord(collection, indexName);
return indexRecord != null && !indexRecord.getString("status").equals("DOES_NOT_EXIST");
}
private static Document indexRecord(
MongoCollection collection, String indexName) {
return StreamSupport.stream(collection.listSearchIndexes().spliterator(), false)
.filter(index -> indexName.equals(index.getString("name")))
.findAny().orElse(null);
}
private void createIndex(String indexName, IndexMapping indexMapping) {
collection.createSearchIndexes(List.of(new SearchIndexModel(
indexName,
fromIndexMapping(indexMapping),
SearchIndexType.vectorSearch())));
code Copy code
waitForIndex(collection, indexName);
static void waitForIndex(MongoCollection collection, String indexName) {
long startTime = System.nanoTime();
long timeoutNanos = TimeUnit.SECONDS.toNanos(SECONDS_TO_WAIT_FOR_INDEX);
while (System.nanoTime() - startTime < timeoutNanos) {
Document indexRecord = indexRecord(collection, indexName);
if (indexRecord != null) {
if ("FAILED".equals(indexRecord.getString("status"))) {
throw new RuntimeException("Search index has failed status.");
}
if (indexRecord.getBoolean("queryable")) {
return;
}
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
}
log.warn("Index {} was not created or did not exit INITIAL_SYNC within {} seconds",
indexName, SECONDS_TO_WAIT_FOR_INDEX);
}
}
怎么改
@[Redacted Person]
public EmbeddingSearchResult<TextSegment> search(EmbeddingSearchRequest request) {
if (configuration instanceof MongoDbConfigurationENN) {
return searchUsingENN(request); // ENN 搜索逻辑
} else if (configuration instanceof MongoDbConfigurationHybrid) {
return searchUsingHybrid(request); // Hybrid 搜索逻辑
} else {
return searchUsingANN(request); // 默认 ANN 搜索逻辑
}
}
// ANN 搜索逻辑(提取现有代码)
private EmbeddingSearchResult<TextSegment> searchUsingANN(EmbeddingSearchRequest request) {
List<Double> queryVector = request.queryEmbedding().vectorAsList().stream()
.map(Float::doubleValue)
.collect(toList());
long numCandidates = request.maxResults() * maxResultRatio;
Bson postFilter = null;
if (request.minScore() > 0) {
postFilter = Filters.gte("score", request.minScore());
}
if (request.filter() != null) {
Bson newFilter = map(request.filter());
postFilter = postFilter == null ? newFilter : Filters.and(postFilter, newFilter);
}
VectorSearchOptions vectorSearchOptions = this.globalPrefilter == null
? approximateVectorSearchOptions(numCandidates)
: approximateVectorSearchOptions(numCandidates).filter(this.globalPrefilter);
ArrayList<Bson> pipeline = new ArrayList<>();
pipeline.add(vectorSearch(
fieldPath("embedding"),
queryVector,
indexName,
request.maxResults(),
vectorSearchOptions));
pipeline.add(project(fields(
metaVectorSearchScore("score"),
include("embedding", "metadata", "text"))));
if (postFilter != null) {
Bson match = match(postFilter);
pipeline.add(match);
}
try {
AggregateIterable<MongoDbMatchedDocument> results = collection.aggregate(pipeline, MongoDbMatchedDocument.class);
List<EmbeddingMatch<TextSegment>> result = StreamSupport.stream(results.spliterator(), false)
.map(MappingUtils::toEmbeddingMatch)
.collect(toList());
return new EmbeddingSearchResult<>(result);
} catch (MongoCommandException e) {
log.error("Error in MongoDBEmbeddingStore.search", e);
throw new RuntimeException(e);
}
}
// ENN 搜索逻辑
private EmbeddingSearchResult<TextSegment> searchUsingENN(EmbeddingSearchRequest request) {
log.info("Performing ENN search...");
// 使用 MongoDB Atlas ENN 搜索逻辑
// TODO: 添加 ENN 搜索的具体实现
return new EmbeddingSearchResult<>(new ArrayList<>());
}
// Hybrid 搜索逻辑
private EmbeddingSearchResult<TextSegment> searchUsingHybrid(EmbeddingSearchRequest request) {
log.info("Performing Hybrid search...");
// 执行向量搜索(ANN 或 ENN)
EmbeddingSearchResult<TextSegment> vectorResults = searchUsingANN(request); // 或 searchUsingENN(request)
// 执行全文搜索
List<EmbeddingMatch<TextSegment>> textResults = performTextSearch(request.textQuery(), configuration.getTextIndexName());
// 合并结果
List<EmbeddingMatch<TextSegment>> mergedResults = mergeResults(vectorResults.matches(), textResults);
return new EmbeddingSearchResult<>(mergedResults);
}