Okay, I understand. The user is requesting that langchain4j-mongodb-atlas be enhanced to support Exact Nearest Neighbor (ENN) search and hybrid search, similar to how langchain4j-elasticsearch handles different search configurations. Here's a breakdown of the proposed solution and how it could be implemented, along with considerations for potential breaking changes:
Proposed Solution
The suggested approach is to introduce a MongoDbConfiguration interface and concrete implementations for different search strategies, mirroring the ElasticsearchEmbeddingStore and ElasticsearchConfiguration design:
MongoDbConfiguration Interface:
This interface would define a contract for how search queries are executed against MongoDB Atlas.
It would likely have a method like search(MongoClient client, String indexName, EmbeddingSearchRequest embeddingSearchRequest) that takes the necessary parameters and returns the search results.
Implementations of MongoDbConfiguration:
MongoDbConfigurationANN: This would represent the current Approximate Nearest Neighbor (ANN) search implementation, likely using the existing vector search functionality in MongoDbEmbeddingStore.
MongoDbConfigurationENN: This would implement Exact Nearest Neighbor search, leveraging MongoDB's new ENN capabilities.
MongoDbConfigurationHybrid: This would implement hybrid search, combining vector search with full-text search. It would require handling two indexes: one for vector embeddings and another for full-text search.
Implementation Details and Considerations
MongoDbEmbeddingStore Modification:
The MongoDbEmbeddingStore constructor should be updated to accept a MongoDbConfiguration object instead of individual parameters related to search index creation. This will allow the store to be configured with different search strategies at runtime.
The search() method would delegate the actual search execution to the provided MongoDbConfiguration instance.
Index Management:
ANN and ENN: These configurations might be able to share the same vector search index but with different query options. The implementations will need to be responsible for generating the correct query depending on the selected search method.
User
哪些文件修改
Assistant
User
创建分支,提交pr
Assistant
User
Assistant
User
[Redacted Person]在哪儿
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Hybrid Search: This will introduce the biggest challenge. It will require the user to have two indexes configured (one for vector search, and one for full-text search). The MongoDbConfigurationHybrid implementation will need to be able to use both of them during search.
Breaking Changes:
The most significant breaking change would be the change in the constructor of MongoDbEmbeddingStore. The user would need to use a MongoDbConfiguration object.
The introduction of hybrid search with two indexes might also be a breaking change for users who rely on the existing behavior of MongoDbEmbeddingStore.
It will be very important to provide clear documentation and migration paths.
Filter Support:
Filters should be supported in both ANN, ENN and hybrid searches. This will mean that the MongoDbConfiguration implementations will need to be able to handle them.
Configuration:
The MongoDbConfiguration implementations should be easily configurable (e.g., using builder patterns)
Code Snippets (Illustrative)
[Redacted
// MongoDbConfiguration Interface
interface MongoDbConfiguration {
EmbeddingSearchResult<TextSegment> search(MongoClient client, String indexName, EmbeddingSearchRequest embeddingSearchRequest);
}
// MongoDbConfigurationANN Implementation (Example)
class MongoDbConfigurationANN implements MongoDbConfiguration{
//Existing implementation using approximate vector search
}
// MongoDbConfigurationENN Implementation (Example)
class MongoDbConfigurationENN implements MongoDbConfiguration{
//Implementation using exact nearest neighbor
}
// MongoDbConfigurationHybrid Implementation (Example)
class MongoDbConfigurationHybrid implements MongoDbConfiguration{
//Implementation combining vector and full-text search
//needs to be configurable with both index names
}
// Modified MongoDbEmbeddingStore
public class MongoDbEmbeddingStore implements EmbeddingStore<TextSegment> {
private final MongoCollection<MongoDbDocument> collection;
private final MongoDbConfiguration configuration;
private final String indexName;
public MongoDbEmbeddingStore(MongoClient mongoClient,
String databaseName,
String collectionName,
String indexName,
MongoDbConfiguration configuration) {
//... existing code
this.configuration = configuration;
}
@[Redacted Person]
public EmbeddingSearchResult<TextSegment> search(EmbeddingSearchRequest request) {
return configuration.search(mongoClient, indexName, request);
}
}
Next Steps:
Create MongoDbConfiguration Interface: Define the contract for search configurations.
Implement MongoDbConfigurationANN, MongoDbConfigurationENN, and MongoDbConfigurationHybrid: Create concrete implementations for each search strategy.
Update MongoDbEmbeddingStore: Modify the constructor and the search() method to use MongoDbConfiguration.
Handle Index Creation: Ensure that the code is capable of creating the necessary indexes for hybrid search.
Add Tests: Implement tests for each search configuration.
Document the changes: Provide clear instructions about how to use the new features.
Conclusion
This approach provides a flexible and extensible way to handle different search strategies in MongoDB Atlas. The key challenge will be handling the hybrid search scenario, including the need for two separate indexes, and communicating these changes to the users.
Based on the provided context and the proposed solution, here's a breakdown of the files that would need to be modified or created:
Constructor: Modify the constructor to accept a MongoDbConfiguration object instead of individual parameters related to search index creation. Remove the index creation logic from the constructor, since this should be delegated to the MongoDbConfiguration.
search() Method: Modify the search() method to delegate the actual search execution to the provided MongoDbConfiguration instance.
Remove the indexName field. The index name will now be part of the configuration.
Remove createIndex and indexMapping parameters. This will be part of the configurations.
This file will need to be updated to use the new MongoDbConfiguration classes. New tests will need to be added to test each configuration.
Summary
In summary, the changes will primarily focus on the langchain4j-mongodb-atlas module, adding new classes and modifying the existing MongoDbEmbeddingStore to support pluggable search configurations. No changes will be needed in the langchain4j-core module.
Okay, I understand. As a large language model, I can't directly create branches or submit pull requests on GitHub. However, I can outline the steps you would take to do so, and provide you with the necessary commands and context.
Steps to Create a Branch and Submit a PR
Create a local branch:
First, make sure you have the latest version of the langchain4j repository on your local machine. Use the following command in your terminal:
bash
git checkout main
git pull origin main
Now, create a new branch for your changes. Choose a descriptive name that indicates the feature you're working on:
Go to the original langchain4j repository on GitHub.
You should see a banner indicating that you have recently pushed a branch to your fork. Click on the "Compare & pull request" button.
Review the changes in your PR, add a descriptive title and comment to the PR, and submit it.
If the PR is created from a forked repo, make sure the base is set to main and the head is your branch from the forked repo.
Important Considerations for the PR
Descriptive Commit Message: Follow the conventional commits specification when writing your commit message.
PR Title: Use a clear title for your PR (e.g., "feat(mongodb-atlas): Implement ENN and hybrid search support").
PR Description: Provide a detailed description of the changes in the PR, including:
The problem this PR solves.
The approach you have taken.
Any potential breaking changes.
Instructions for testing.
Tests: Ensure that all unit tests and integration tests are green before submitting a PR.
Documentation: Update the documentation to include the new features.
Example of PR Description
code
This PR adds support for Exact Nearest Neighbor (ENN) search and hybrid search to the `langchain4j-mongodb-atlas` module.
**Problem**
The existing implementation only supports Approximate Nearest Neighbor (ANN) search. This PR aims to enhance the library to support new search strategies available in MongoDB Atlas.
**Solution**
* Introduced a `MongoDbConfiguration` interface and implementations for ANN, ENN, and hybrid search.
* Modified the `MongoDbEmbeddingStore` to accept a `MongoDbConfiguration` object.
* Implemented the search logic for ENN and hybrid search.
**Breaking Changes**
* The `MongoDbEmbeddingStore` constructor has been changed to use a `MongoDbConfiguration` object.
* The way indexes are created and used has changed for hybrid search, which requires two indexes.
**Testing**
* Added new unit and integration tests to verify the functionality of ENN and hybrid search.
* All tests pass locally.
**Documentation**
* Updated documentation to reflect the new changes.
Please review and let me know if you have any questions.
Summary
This step-by-step guide should help you create a branch, implement the necessary changes, and submit a pull request to the langchain4j repository. Let me know if you have any other questions!
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
"type" : "vector",
code
"path" : "embedding",
code
"numDimensions" : 384,
code
"similarity" : "cosine"
}, {
code
"type" : "filter",
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;
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));
}
}
Okay, let's modify the MongoDbEmbeddingStore.java file based on our previous discussions. Here's the modified code with explanations:
[Redacted
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.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.Collection;
import java.util.List;
import java.util.stream.StreamSupport;
import static com.mongodb.client.model.Aggregates.*;
import static com.mongodb.client.model.Projections.*;
import static dev.langchain4j.internal.Utils.*;
import static dev.langchain4j.internal.ValidationUtils.*;
import static dev.langchain4j.store.embedding.mongodb.MappingUtils.toMongoDbDocument;
import static dev.langchain4j.store.embedding.mongodb.MongoDbMetadataFilterMapper.map;
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 <a href="https://www.mongodb.com/">MongoDB</a> indexed collection as an embedding store.
* <p>
* More <a href="https://www.mongodb.com/docs/atlas/atlas-vector-search/vector-search-overview/">info</a>
* on using MongoDb vector search.
* <p>
* <a href="https://www.mongodb.com/developer/products/atlas/semantic-search-mongodb-atlas-vector-search/">tutorial</a>
* how to use vector search with MongoDB Atlas (great starting point).
* <p>
* To deploy a local instance of Atlas, see
* <a href="https://www.mongodb.com/docs/atlas/cli/current/atlas-cli-deploy-local/">this guide</a>.
*/
public class MongoDbEmbeddingStore implements EmbeddingStore<TextSegment> {
private static final Logger log = LoggerFactory.getLogger(MongoDbEmbeddingStore.class);
private final MongoCollection<MongoDbDocument> collection;
private final MongoDbConfiguration configuration;
public MongoDbEmbeddingStore(MongoClient mongoClient,
String databaseName,
String collectionName,
MongoDbConfiguration configuration,
CreateCollectionOptions createCollectionOptions) {
databaseName = ensureNotNull(databaseName, "databaseName");
collectionName = ensureNotNull(collectionName, "collectionName");
this.configuration = ensureNotNull(configuration, "configuration");
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);
}
public static Builder builder() {
return new Builder();
}
public static class Builder {
private MongoClient mongoClient;
private String databaseName;
private String collectionName;
private MongoDbConfiguration configuration;
private CreateCollectionOptions createCollectionOptions;
/**
* 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 createCollectionOptions(CreateCollectionOptions createCollectionOptions) {
this.createCollectionOptions = createCollectionOptions;
return this;
}
public Builder configuration(MongoDbConfiguration configuration) {
this.configuration = configuration;
return this;
}
public MongoDbEmbeddingStore build() {
return new MongoDbEmbeddingStore(
mongoClient, databaseName, collectionName,
configuration, createCollectionOptions);
}
}
@[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<String> addAll(List<Embedding> embeddings) {
List<String> 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<String> 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<TextSegment> search(EmbeddingSearchRequest request) {
return configuration.search(collection.getMongoClient(), collection.getNamespace().getCollectionName(),request);
}
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<String> ids, List<Embedding> embeddings, List<TextSegment> 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");
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);
}
}
Key Changes and Explanations:
Removed Index-Related Parameters:
The indexName, filter, indexMapping, and createIndex parameters have been removed from the constructor. These are now part of the MongoDbConfiguration.
MongoDbConfiguration Parameter:
The constructor now accepts a MongoDbConfiguration object, which will be used for search operations.
search() Method Delegation:
The search() method now delegates the actual search operation to the MongoDbConfiguration instance. The mongo client and collection name are passed to it.
Builder Pattern Update:
The builder class was updated to remove the index related parameters, and to add the MongoDbConfiguration.
Removed Index Creation Logic: The index creation logic was removed from the constructor.
Next Steps
After modifying this file, you would need to create the MongoDbConfiguration interface and its implementations (MongoDbConfigurationANN, MongoDbConfigurationENN, MongoDbConfigurationHybrid). Remember to create the corresponding test files for the new classes.
This modified MongoDbEmbeddingStore provides a basic structure for pluggable search configurations. The next step would be to implement the different MongoDbConfiguration implementations, which will handle the details of executing each type of search against MongoDB Atlas. Remember to update the test class as well to use the new configurations.
You are right to ask! My apologies, I got carried away with the refactoring and missed a crucial detail. The searchAnn method (or the logic for performing an ANN search) is not explicitly present in the modified MongoDbEmbeddingStore.java I provided.
The intention was to delegate the actual search execution to the MongoDbConfiguration implementations. Therefore, the ANN search logic (which was previously embedded inside the search method of MongoDbEmbeddingStore) should now reside within the MongoDbConfigurationANN class.
Where the ANN Search Logic Should Go
MongoDbConfigurationANN.java: This is where the code that performs the Approximate Nearest Neighbor (ANN) search will be located.
MongoDbConfiguration Interface: The MongoDbConfiguration interface needs a search method definition that will be implemented by the different search strategies.
Example Code (Illustrative)
First, let's define the MongoDbConfiguration interface:
The searchAnn logic (i.e., the ANN search implementation) is not inside MongoDbEmbeddingStore anymore. It has been moved to the MongoDbConfigurationANN class, which is responsible for executing the specific type of search. The MongoDbEmbeddingStore now delegates the search to the MongoDbConfiguration.
This makes the code more modular and extensible, as you can add other search strategies by simply implementing the MongoDbConfiguration interface.
Remember to create similar MongoDbConfigurationENN and MongoDbConfigurationHybrid classes for ENN and hybrid searches, respectively, and to adapt the tests accordingly.
@[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
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);
}
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);
}
}
怎么改