Skip to content

feat: add schema indexes #1138

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

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft

Conversation

MohamedAliBouhaouala
Copy link
Contributor

@MohamedAliBouhaouala MohamedAliBouhaouala commented Jun 16, 2025

Motivation

The following PR introduces new indexes to the database schemas to optimize query performance and improve data retrieval efficiency. The added indexes target frequently queried fields identified through analysis of query patterns and slow queries, resulting in faster lookup times and reduced database load.
It is worth noting that no data migrations are necessary since indexes can be created on existing collections without modifying the data when applying indexes on an existing dump.

Fixes # (1099)[https://github.com//issues/1099]

Type of change:

Please delete options that are not relevant.

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • This change requires a documentation update

Checklist:

  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • I have added unit tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes

Summary by CodeRabbit

  • New Features

    • Improved database performance by adding indexes to frequently queried fields across multiple modules.
    • Enforced uniqueness for specific combinations of fields to prevent duplicate entries in certain collections.
  • Chores

    • Updated copyright year to 2025 in several files.

Copy link
Contributor

coderabbitai bot commented Jun 16, 2025

Walkthrough

Several schema files were updated to add or modify database indexes. These changes include adding single-field indexes to properties such as name, title, and text, as well as introducing compound and unique compound indexes on combinations of fields in various schemas. Some copyright years were also updated.

Changes

File(s) Change Summary
api/src/attachment/schemas/attachment.schema.ts Added an index to the name property in the AttachmentStub schema.
api/src/chat/schemas/subscriber.schema.ts Added indexes to first_name, last_name, foreign_id; added compound index on first_name + last_name; updated copyright year.
api/src/cms/schemas/content.schema.ts Added an index to the title property in the ContentStub schema.
api/src/nlp/schemas/nlp-sample-entity.schema.ts Added unique compound index on sample, entity, and value in NlpSampleEntityStub; updated copyright year.
api/src/nlp/schemas/nlp-sample.schema.ts Added an index to the text property in the NlpSampleStub schema; updated copyright year.
api/src/nlp/schemas/nlp-value.schema.ts Added unique compound index on value and entity in NlpValueModel.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant MongoDB
    Note over Client,MongoDB: Example: Query with indexed fields
    Client->>MongoDB: Find documents by indexed field (e.g., title, name, text)
    MongoDB-->>Client: Return results using index for faster lookup
Loading
sequenceDiagram
    participant MongoDB
    Note over MongoDB: On insert or update
    MongoDB->>MongoDB: Enforce unique compound index (e.g., value+entity)
    alt Duplicate found
        MongoDB-->>Client: Error (duplicate key)
    else No duplicate
        MongoDB-->>Client: Insert/Update successful
    end
Loading

Poem

In the warren where queries hop and bound,
New indexes bloom, making searches sound.
Compound and unique, they keep things neat,
Ensuring no duplicates, making results sweet.
With each schema tuned, our data runs fast—
A rabbit’s delight, efficiency unsurpassed!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @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.

@MohamedAliBouhaouala MohamedAliBouhaouala requested review from marrouchi and yassinedorbozgithub and removed request for marrouchi June 16, 2025 14:46
Copy link
Contributor

@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

🔭 Outside diff range comments (1)
api/src/nlp/schemas/nlp-value.schema.ts (1)

35-36: Conflicting uniqueness constraints

value is still marked unique: true, yet you just added a compound unique index (value, entity).
The single-field unique index will forbid the same value across different entities, negating the purpose of the new compound index and potentially blocking existing data.

Diff to remove the obsolete unique flag:

-  @Prop({ type: String, required: true, unique: true })
+  @Prop({ type: String, required: true })
🧹 Nitpick comments (1)
api/src/nlp/schemas/nlp-sample.schema.ts (1)

29-30: Large text field index – monitor index size

Indexing text strings can explode index size quickly. If you need equality look-ups it’s fine; if you mostly do $text search consider a text index instead. At minimum add a .index({ text: 1 }, { collation, partialFilterExpression… }) directly on the schema to control options.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e309474 and 2a46442.

📒 Files selected for processing (6)
  • api/src/attachment/schemas/attachment.schema.ts (1 hunks)
  • api/src/chat/schemas/subscriber.schema.ts (4 hunks)
  • api/src/cms/schemas/content.schema.ts (1 hunks)
  • api/src/nlp/schemas/nlp-sample-entity.schema.ts (2 hunks)
  • api/src/nlp/schemas/nlp-sample.schema.ts (2 hunks)
  • api/src/nlp/schemas/nlp-value.schema.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: API-Tests
  • GitHub Check: Frontend Tests
  • GitHub Check: Analyze (actions)
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (8)
api/src/attachment/schemas/attachment.schema.ts (1)

38-42: Index looks fine – consider build-time impact

Adding a single-field index on name is straightforward. Just make sure the collection size isn’t huge when this rolls out; @Prop({ …, index: true }) defaults to a foreground build during syncIndexes(). For large datasets you may prefer a background build or manual creation in the deployment script.

api/src/cms/schemas/content.schema.ts (1)

37-38: Minor: keep text and single-field index coherent

ContentSchema already defines a text index on title (lines 94-106). The extra single-field B-tree index on title may be redundant; MongoDB can’t use the text index to satisfy ordinary equality/ordering queries, but the reverse is also true. If the workload is search-only you can drop the B-tree index to save space; otherwise keep both intentionally.

api/src/nlp/schemas/nlp-value.schema.ts (1)

122-125: 👍 Compound unique index adds proper guardrails

The (value, entity) unique index is the right level of granularity for NLP values. Once the single-field index is removed (see above) this will enforce the intended constraint.

api/src/nlp/schemas/nlp-sample-entity.schema.ts (1)

110-113: Unique triple-key index – verify null safety

The (sample, entity, value) unique index is correct. Ensure no historical rows have any of these fields null/undefined; otherwise the index build will fail. If that’s a risk, add partialFilterExpression to exclude docs with nulls.

api/src/chat/schemas/subscriber.schema.ts (4)

28-34: Consider collation or text index for name look-ups

Plain B-Tree indexes on first_name speed up equality matches but not case-insensitive or partial-text searches—both are very common on names.
If you routinely search with $regex, provide autocomplete, or need locale-aware case-folding, specify:

-@Prop({ type: String, required: true, index: true })
+@Prop({
+  type: String,
+  required: true,
+  index: { collation: { locale: 'en', strength: 2 } }, // or use `text: true`
+})

Otherwise you’ll still fall back to collection scans.
[ suggest_optional_refactor ]


36-41: Same remark applies to last_name

Align the indexing strategy of last_name with whatever decision you take for first_name to avoid mixed behaviour.
[ duplicate_comment ]


69-73: foreign_id should be declared unique

foreign_id is typically an external system identifier and should be unique to prevent data duplication.
Lacking a uniqueness constraint the application relies on code to guarantee integrity, which is fragile.

-@Prop({ type: String, index: true })
+@Prop({ type: String, index: { unique: true } })

[ raise_critical_issue ]


160-164: Redundant single-field + compound indexes = write overhead

You now have:
• single–field indexes on first_name and last_name
• a compound { first_name: 1, last_name: 1 } index

MongoDB can use the compound index to satisfy single-field predicates that are a prefix of the compound key, so the individual ones are redundant and double write-amplification (~ 2× index maintenance on every insert/update).

Two options:

@@
-schema: SchemaFactory.createForClass(SubscriberStub).index({
-  first_name: 1,
-  last_name: 1,
-}),
+schema: SchemaFactory.createForClass(SubscriberStub)
+  // Drop single-field indexes above, keep only the compound one
+  .index({ first_name: 1, last_name: 1 }),

or delete index: true on the two props and keep the compound index only.
[ suggest_essential_refactor ][ request_verification ]

@MohamedAliBouhaouala MohamedAliBouhaouala linked an issue Jun 16, 2025 that may be closed by this pull request
Copy link
Collaborator

@yassinedorbozgithub yassinedorbozgithub left a comment

Choose a reason for hiding this comment

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

LGTM 👍
image

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.

Need to define indexes for schemas
2 participants