Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

移除 MongoDB 作为向量数据库的方式 #347

Merged
merged 1 commit into from
Jan 1, 2025

Conversation

Hoshino-Yumetsuki
Copy link
Contributor

@Hoshino-Yumetsuki Hoshino-Yumetsuki commented Dec 31, 2024

Summary by CodeRabbit

  • New Features

    • Removed support for MongoDB as a vector store, including configuration and middleware integration.
  • Documentation

    • Updated usage documentation to reflect the removal of MongoDB configuration details.
  • Bug Fixes

    • Eliminated potential errors related to MongoDB integration.
  • Refactor

    • Simplified the middleware array by excluding MongoDB, focusing on remaining vector store options.

Copy link

coderabbitai bot commented Dec 31, 2024

Walkthrough

The pull request removes the MongoDB integration from the vector store service. Key changes include the deletion of the apply function responsible for MongoDB operations, as well as the removal of related configuration properties from the Config interface and schema. Documentation updates reflect this shift, eliminating references to MongoDB. Additionally, the middleware array in the vectorstore.ts file has been modified to exclude MongoDB, streamlining the control flow by focusing on other vector store options.

Changes

File Change Summary
packages/vector-store-service/src/vectorstore/mongodb.ts - Removed the apply function, including all MongoDB-related logic and error handling.
packages/vector-store-service/src/index.ts - Modified Config interface to remove mongodbUrl, mongodbDbName, mongodbCollectionName.
- Updated Config schema to remove MongoDB properties and related documentation.
packages/vector-store-service/src/locales/en-US.schema.yml - Removed MongoDB database settings, including descriptions and keys for MongoDB configuration.
packages/vector-store-service/src/locales/zh-CN.schema.yml - Removed MongoDB database settings, including descriptions and keys for MongoDB configuration.
packages/vector-store-service/src/vectorstore.ts - Updated middleware array to exclude mongodb, retaining only faiss, lunavdb, milvus, and redis.

Possibly related PRs

Poem

🐰 A Rabbit's Farewell to MongoDB 🌌
In the forest of data, we've bid adieu,
MongoDB's whispers fade, it's true.
With vectors we frolic, in fields so wide,
Redis and Milvus now take the ride.
A new path we carve, with joy and glee! 🌟


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4c996d7 and de7ab92.

📒 Files selected for processing (5)
  • packages/vector-store-service/src/index.ts (1 hunks)
  • packages/vector-store-service/src/locales/en-US.schema.yml (0 hunks)
  • packages/vector-store-service/src/locales/zh-CN.schema.yml (0 hunks)
  • packages/vector-store-service/src/vectorstore.ts (1 hunks)
  • packages/vector-store-service/src/vectorstore/mongodb.ts (0 hunks)
💤 Files with no reviewable changes (3)
  • packages/vector-store-service/src/locales/en-US.schema.yml
  • packages/vector-store-service/src/locales/zh-CN.schema.yml
  • packages/vector-store-service/src/vectorstore/mongodb.ts

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (4)
packages/vector-store-service/src/vectorstore/mongodb.ts (4)

27-27: Consider initializing the client to undefined
Although it's declared now, it might be good for clarity to set it to undefined explicitly to make it clear that it’s not yet connected.

- let client: MongoClient
+ let client: MongoClient | undefined

59-60: Log errors on repeated connection attempts
Currently, errors during client.connect() are ignored with an empty catch. Consider logging them in case insight is needed into repeated connection failures.

try {
    await client.connect()
- } catch {}
+ } catch (err) {
+   logger.warn('Failed to connect to MongoDB in deletableFunction:', err)
+ }

98-100: Log errors on repeated connection attempts
Same recommendation as for the deletableFunction. Logging might help diagnose repeated connection issues in addDocumentsFunction.

try {
    await client.connect()
- } catch {}
+ } catch (err) {
+   logger.warn('Failed to connect to MongoDB in addDocumentsFunction:', err)
+ }

116-119: Remove or implement the commented-out save logic
Leaving commented-out code can lead to confusion. If the logic is no longer needed, remove it to improve readability; otherwise, finalize and test it.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 141c3f5 and a336f3b.

📒 Files selected for processing (1)
  • packages/vector-store-service/src/vectorstore/mongodb.ts (2 hunks)
🔇 Additional comments (3)
packages/vector-store-service/src/vectorstore/mongodb.ts (3)

6-6: Great use of type-only import for MongoClient
This helps to ensure type safety without bundling the entire module.


29-31: Connection logic is clear and properly enclosed in a try-catch
This refactoring ensures that we handle errors gracefully when connecting to MongoDB.


33-39: Properly closing the client on disposal
Good check to ensure the connection is only closed if it exists. This prevents crashes on shutdown.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (2)
packages/vector-store-service/src/vectorstore/mongodb.ts (2)

26-26: Use const instead of let for client declaration

The client variable is never reassigned after initialization. Following TypeScript best practices, use const instead.

-        let client: MongoClient
+        const client: MongoClient

Line range hint 114-116: Remove or implement commented code

The saveableFunction contains commented-out code. Either implement the necessary cleanup logic or remove the comments if they're no longer needed.

             async saveableFunction(_store) {
-                /* await client.close()
-                logger.info('MongoDB connection closed during save') */
+                // Add implementation if cleanup is needed during save
             }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a336f3b and 20ee4bc.

📒 Files selected for processing (1)
  • packages/vector-store-service/src/vectorstore/mongodb.ts (7 hunks)
🧰 Additional context used
🪛 GitHub Check: CodeFactor
packages/vector-store-service/src/vectorstore/mongodb.ts

[warning] 28-28: packages/vector-store-service/src/vectorstore/mongodb.ts#L28
'client' is never reassigned. Use 'const' instead. (prefer-const)


[warning] 72-72: packages/vector-store-service/src/vectorstore/mongodb.ts#L72
Replace ⏎····································|·string⏎··································· with ·string (prettier/prettier)

🪛 eslint
packages/vector-store-service/src/vectorstore/mongodb.ts

[error] 28-28: 'client' is never reassigned. Use 'const' instead.

(prefer-const)


[error] 72-74: Replace ⏎····································|·string⏎··································· with ·string

(prettier/prettier)

🔇 Additional comments (2)
packages/vector-store-service/src/vectorstore/mongodb.ts (2)

31-35: LGTM! Proper cleanup handling

Good implementation of connection cleanup with null check and logging.


Line range hint 37-55: LGTM! Proper vector store initialization

The vector store setup is well-structured with all necessary configuration parameters.

packages/vector-store-service/src/vectorstore/mongodb.ts Outdated Show resolved Hide resolved
Comment on lines 28 to 27
client = new MongoDB.MongoClient(config.mongodbUrl)
await client.connect()
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add error handling for MongoDB connection

The connection attempt should include error handling to gracefully handle connection failures and provide meaningful error messages.

-        client = new MongoDB.MongoClient(config.mongodbUrl)
-        await client.connect()
+        client = new MongoDB.MongoClient(config.mongodbUrl)
+        try {
+            await client.connect()
+            logger.info('Successfully connected to MongoDB')
+        } catch (error) {
+            logger.error(`Failed to connect to MongoDB: ${error.message}`)
+            throw error
+        }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
client = new MongoDB.MongoClient(config.mongodbUrl)
await client.connect()
client = new MongoDB.MongoClient(config.mongodbUrl)
try {
await client.connect()
logger.info('Successfully connected to MongoDB')
} catch (error) {
logger.error(`Failed to connect to MongoDB: ${error.message}`)
throw error
}
🧰 Tools
🪛 GitHub Check: CodeFactor

[warning] 28-28: packages/vector-store-service/src/vectorstore/mongodb.ts#L28
'client' is never reassigned. Use 'const' instead. (prefer-const)

🪛 eslint

[error] 28-28: 'client' is never reassigned. Use 'const' instead.

(prefer-const)

packages/vector-store-service/src/vectorstore/mongodb.ts Outdated Show resolved Hide resolved
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
packages/vector-store-service/src/vectorstore/mongodb.ts (2)

26-28: Use const for immutable declarations

The client variable is never reassigned after initialization. Follow TypeScript best practices by using const.

-        let client: MongoClient
-
-        client = new MongoDB.MongoClient(config.mongodbUrl)
+        const client = new MongoDB.MongoClient(config.mongodbUrl)
🧰 Tools
🪛 eslint

[error] 28-28: 'client' is never reassigned. Use 'const' instead.

(prefer-const)

🪛 GitHub Check: CodeFactor

[warning] 28-28: packages/vector-store-service/src/vectorstore/mongodb.ts#L28
'client' is never reassigned. Use 'const' instead. (prefer-const)


26-35: Consider implementing a connection manager

The current implementation handles connections independently in each operation. Consider implementing a centralized connection manager to handle connection lifecycle and state.

This could include:

  1. Connection state tracking
  2. Automatic reconnection with backoff
  3. Connection pooling
  4. Centralized error handling

Would you like me to provide an example implementation of a MongoDB connection manager class?

🧰 Tools
🪛 eslint

[error] 28-28: 'client' is never reassigned. Use 'const' instead.

(prefer-const)

🪛 GitHub Check: CodeFactor

[warning] 28-28: packages/vector-store-service/src/vectorstore/mongodb.ts#L28
'client' is never reassigned. Use 'const' instead. (prefer-const)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 20ee4bc and 4c996d7.

📒 Files selected for processing (1)
  • packages/vector-store-service/src/vectorstore/mongodb.ts (6 hunks)
🧰 Additional context used
🪛 eslint
packages/vector-store-service/src/vectorstore/mongodb.ts

[error] 28-28: 'client' is never reassigned. Use 'const' instead.

(prefer-const)


[error] 74-76: Replace ⏎····································|·string⏎··································· with ·string

(prettier/prettier)

🪛 GitHub Check: CodeFactor
packages/vector-store-service/src/vectorstore/mongodb.ts

[warning] 28-28: packages/vector-store-service/src/vectorstore/mongodb.ts#L28
'client' is never reassigned. Use 'const' instead. (prefer-const)

🔇 Additional comments (3)
packages/vector-store-service/src/vectorstore/mongodb.ts (3)

85-87: ⚠️ Potential issue

Add error handling for ObjectId conversion

Converting string IDs to ObjectId can fail if the input format is invalid. Add proper error handling.

         _id: {
-            $in: ids.map((id) => new MongoDB.ObjectId(id))
+            $in: ids.map((id) => {
+                try {
+                    return new MongoDB.ObjectId(id)
+                } catch (error) {
+                    logger.warn(`Invalid ObjectId format: ${id}, skipping...`)
+                    return null
+                }
+            }).filter(Boolean)
         }

Likely invalid or redundant comment.


28-29: ⚠️ Potential issue

Add robust connection error handling

The MongoDB connection attempt should include proper error handling and logging.

-        await client.connect()
+        try {
+            await client.connect()
+            logger.info('Successfully connected to MongoDB vector store')
+        } catch (error) {
+            logger.error(`Failed to connect to MongoDB vector store: ${error.message}`)
+            throw new Error(`MongoDB connection failed: ${error.message}`)
+        }

Likely invalid or redundant comment.

🧰 Tools
🪛 eslint

[error] 28-28: 'client' is never reassigned. Use 'const' instead.

(prefer-const)

🪛 GitHub Check: CodeFactor

[warning] 28-28: packages/vector-store-service/src/vectorstore/mongodb.ts#L28
'client' is never reassigned. Use 'const' instead. (prefer-const)


96-98: ⚠️ Potential issue

Improve connection management in add documents function

Similar to the delete function, improve connection handling and error management.

         try {
-            await client.connect()
+            if (!client.isConnected()) {
+                await client.connect()
+                logger.debug('Reconnected to MongoDB for add operation')
+            }
         } catch (error) {
-        } catch {}
+            logger.warn(`Connection attempt failed during add operation: ${error.message}`)
+        }

Likely invalid or redundant comment.

packages/vector-store-service/src/vectorstore/mongodb.ts Outdated Show resolved Hide resolved
Copy link
Member

@dingyi222666 dingyi222666 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lint 没有通过

@Hoshino-Yumetsuki Hoshino-Yumetsuki changed the title 在 MongoDB 进行操作之前确保连接到数据库 移除 MongoDB 作为向量数据库的方式 Jan 1, 2025
@dingyi222666 dingyi222666 merged commit 7146352 into ChatLunaLab:v1-dev Jan 1, 2025
7 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants