Skip to content

Add semantic search functionality#72

Merged
RamRamez merged 6 commits intodevelopfrom
add-search-functionality
Apr 16, 2025
Merged

Add semantic search functionality#72
RamRamez merged 6 commits intodevelopfrom
add-search-functionality

Conversation

@RamRamez
Copy link
Member

@RamRamez RamRamez commented Apr 16, 2025

Summary by CodeRabbit

  • New Features

    • Added full-text search functionality for polls, allowing users to search polls by title, description, and tags.
    • Introduced search filtering for user activities, enabling users to find actions related to polls matching a search term.
  • Improvements

    • Enhanced poll and user activity filtering and sorting options.
    • Standardized date formatting and improved participant count retrieval in user activity responses.
  • Bug Fixes

    • Improved error handling for missing required fields in poll queries.
  • Style

    • Updated validation rules and types for user activity data.

@coderabbitai
Copy link

coderabbitai bot commented Apr 16, 2025

Walkthrough

This update introduces full-text search capabilities for polls by adding a searchVector column to the database, updating the Prisma schema, and integrating search functionality into the application logic. The PollService now supports searching polls using PostgreSQL's text search features, and the DTOs for polls and user activities are extended with optional search parameters. Related service and module files are updated to support these features, including dependency injection and improved participant count handling. Validation decorators and response formatting are also refined in user-related DTOs and services.

Changes

File(s) Change Summary
prisma/migrations/…/migration.sql, prisma/schema.prisma Added searchVector tsvector column and GIN index to Poll table; created trigger and function for automatic search vector updates; updated Prisma schema to reflect these changes.
src/poll/Poll.dto.ts Added optional search string property to GetPollsDto for poll search queries.
src/poll/poll.service.ts Added searchPolls method using full-text search; updated getPolls to handle search queries and improved filter typing and error handling.
src/user/user.dto.ts Added optional search to GetUserActivitiesDto; refined validation, types, and decorators in user activity DTOs; added isActive and standardized date handling.
src/user/user.module.ts Added PollService as a provider to enable its injection in UserModule.
src/user/user.service.ts Injected PollService; added poll search to user activities; optimized participant count retrieval; standardized date formatting in responses.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Controller
    participant PollService
    participant Database

    Client->>Controller: GET /polls?search=term
    Controller->>PollService: getPolls({ search: "term", ... })
    PollService->>PollService: searchPolls("term")
    PollService->>Database: SELECT poll IDs WHERE searchVector @@ to_tsquery('term')
    Database-->>PollService: poll IDs
    PollService->>Database: SELECT polls WHERE id IN (poll IDs) AND other filters
    Database-->>PollService: poll data
    PollService-->>Controller: filtered polls
    Controller-->>Client: poll results
Loading
sequenceDiagram
    participant Client
    participant Controller
    participant UserService
    participant PollService
    participant Database

    Client->>Controller: GET /user/activities?search=term
    Controller->>UserService: getUserActivities({ search: "term", ... })
    UserService->>PollService: searchPolls("term")
    PollService->>Database: SELECT poll IDs WHERE searchVector @@ to_tsquery('term')
    Database-->>PollService: poll IDs
    UserService->>Database: SELECT user actions WHERE pollId IN (poll IDs)
    Database-->>UserService: user actions
    UserService-->>Controller: user activities DTO
    Controller-->>Client: user activities response
Loading

Possibly related PRs

Suggested reviewers

  • lovelgeorge99
  • Meriem-BM

Poem

In the garden of queries, a search now blooms,
With vectors and triggers, the database resumes.
Polls are now searchable, swift as the breeze,
User activities filter with elegant ease.
With DTOs polished and services bright,
This code hops forward—searching done right!
🐇✨

✨ 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.
    • 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.
  • @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: 1

🧹 Nitpick comments (3)
prisma/migrations/20250416649699_add_search_vector/migration.sql (1)

21-22: Note about updating existing records

Setting all existing records' searchVector to NULL will trigger recalculation on subsequent updates, but existing polls won't be searchable until they're updated. Consider adding another statement to immediately populate search vectors for existing records if immediate searchability is required.

-- Update existing records
UPDATE "Poll" SET "searchVector" = NULL; 
+ -- Immediately populate search vectors for existing records
+ UPDATE "Poll" SET "searchVector" = 
+   setweight(to_tsvector('english', COALESCE(title, '')), 'A') ||
+   setweight(to_tsvector('english', COALESCE(description, '')), 'B') ||
+   setweight(to_tsvector('english', array_to_string(tags, ' ')), 'C');
src/user/user.service.ts (2)

134-147: Consider removing bracket notation for the private method call.
Accessing searchPolls with this.pollService['searchPolls'] might raise concerns about calling a private method, depending on TS configurations. A direct call (this.pollService.searchPolls(...)) is typically more conventional and ensures long-term maintainability.

- pollIds = await this.pollService['searchPolls'](dto.search);
+ pollIds = await this.pollService.searchPolls(dto.search);

168-169: Address the TODO comment regarding authorWorldId.
This workaround for retrieving authorWorldId from the UserAction can be improved by introducing the property directly in the entity or via a joined query.

Do you want help creating a pull request or migration that adds authorWorldId to UserAction?

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6740851 and b483a75.

📒 Files selected for processing (7)
  • prisma/migrations/20250416649699_add_search_vector/migration.sql (1 hunks)
  • prisma/schema.prisma (1 hunks)
  • src/poll/Poll.dto.ts (1 hunks)
  • src/poll/poll.service.ts (6 hunks)
  • src/user/user.dto.ts (2 hunks)
  • src/user/user.module.ts (1 hunks)
  • src/user/user.service.ts (5 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/user/user.module.ts (1)
src/app.module.ts (1)
  • Module (11-16)
🔇 Additional comments (27)
src/poll/Poll.dto.ts (1)

55-57: Clean implementation of search parameter

The addition of the optional search property with proper validation decorators follows the application's patterns and enables the full-text search functionality introduced in this PR.

src/user/user.module.ts (2)

2-2: Proper import of PollService

The import of PollService is correctly defined with a relative path.


8-8: Appropriate module configuration for cross-service functionality

Adding PollService to the providers array properly enables dependency injection, allowing the UserService to utilize poll search functionality.

prisma/schema.prisma (2)

52-52: Appropriate use of PostgreSQL tsvector for search functionality

The searchVector field is correctly defined using Unsupported("tsvector") with the @db.TsVector annotation, which is the proper way to implement full-text search in PostgreSQL via Prisma.


57-57: Efficient indexing for search performance

The GIN index on the searchVector field is essential for optimizing full-text search queries. This will ensure search operations remain efficient even as the number of polls grows.

prisma/migrations/20250416649699_add_search_vector/migration.sql (2)

1-13: Well-structured implementation of PostgreSQL full-text search

The implementation correctly adds a tsvector column and creates a function that generates a weighted search vector from different poll fields. The weighting approach (A for title, B for description, C for tags) will provide relevant search results with titles prioritized. The function also properly handles NULL values using COALESCE.


15-20: Efficient automatic updating of search vectors

The trigger setup ensures that search vectors are automatically updated whenever poll records are inserted or modified, eliminating the need for application-level maintenance of search data.

src/user/user.service.ts (4)

15-15: Good addition of PollService import.
Injecting the PollService allows for streamlined integration of the poll search functionality in the UserService.


40-42: Poll ID filter addition looks appropriate.
Adding pollId?: { in?: number[] } to UserActionFilters enhances the filtering options for user actions by specific polls.


48-51: Constructor injection of PollService is well-structured.
This improves modularity and enables the UserService to delegate search functionality to PollService.


180-184: Enhanced user action details look consistent.
Exposing endDate, isActive, votersParticipated, authorWorldId, and createdAt as strings and booleans aligns well with the updated DTO pattern.

src/poll/poll.service.ts (5)

2-2: Prisma import is properly utilized for type safety.
Introducing Prisma for typed filtering and sorting is a best practice to maintain clarity in query logic.


90-90: Search parameter integration is well-designed.
Making search optional in the method signature aligns with typical search flows where a user may or may not input a search term.


120-120: Improved error handling with BadRequestException.
Raising a BadRequestException('worldId Not Provided') is clearer to API consumers than a generic error.


145-152: Combined poll ID filtering logic is cohesive.
Merging the search-based ID filter (pollId: { in: pollIds }) with existing filters using AND is a straightforward approach for multi-criteria queries.


154-154: Type-safe orderBy definition is beneficial.
Explicitly typing orderBy as Prisma.PollOrderByWithRelationInput ensures compile-time checks for valid fields and directions.

src/user/user.dto.ts (11)

1-2: Imports from class-transformer and prisma client are properly organized.
These imports set the stage for advanced transformations and validations.


4-6: Added decorators for arrays, booleans, and date strings.
Using @IsArray(), @IsBoolean(), and @IsDateString() clarifies type expectations, improving validation coverage.


8-8: Migration from @IsNumber() to @ISINT() is precise.
Restricting numerical fields (e.g., IDs) to integers prevents invalid floating-point assignments.


49-52: Optional search parameter addition is consistent.
The search?: string property allows user activity queries to incorporate full-text search terms without breaking backward compatibility.


56-56: Strict integer ID ensures resilience.
Enforcing @IsInt() for id in UserActionDto is a good practice for entity identification.


62-62: Ensuring pollId is an integer.
@IsInt() aligns with the database schema where poll IDs are numeric.


71-72: Switching endDate to string is consistent with ISO date representation.
Returning ISO-formatted strings ensures easy consumption on the client side.


74-75: New isActive boolean field.
@IsBoolean() appropriately validates the state of a poll or user action.


77-78: Defining votersParticipated as an integer.
This ensures clarity and consistency when representing participant counts.


83-84: Representing createdAt as a string.
ISO date strings allow consistent serialization results from the backend.


88-89: Refined userActions array validation.
Applying @IsArray() and @Type(() => UserActionDto) guarantees more robust schema conformance for nested user actions.

Comment on lines +15 to +28
private async searchPolls(searchTerm: string): Promise<number[]> {
const searchQuery = searchTerm
.split(' ')
.map((word) => `${word}:*`)
.join(' & ');
const searchResults = await this.databaseService.$queryRaw<
{ pollId: number }[]
>`
SELECT "pollId" FROM "Poll"
WHERE "searchVector" @@ to_tsquery('english', ${searchQuery})
ORDER BY ts_rank("searchVector", to_tsquery('english', ${searchQuery})) DESC
`;
return searchResults.map((result) => result.pollId);
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Ensure input sanitization for raw PostgreSQL full-text search.
While $queryRaw with parameter interpolation is typically safe, consider guarding against invalid or malicious search strings by pre-validating or escaping user input. This prevents unexpected query parser errors or injection attempts.

private async searchPolls(searchTerm: string): Promise<number[]> {
  // Potential approach: replace non-alphanumeric characters or handle special tokens
+  const safeTerm = searchTerm.replace(/[^a-zA-Z0-9\s]/g, '');
+  const searchQuery = safeTerm
    .split(' ')
    // ...
}
📝 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
private async searchPolls(searchTerm: string): Promise<number[]> {
const searchQuery = searchTerm
.split(' ')
.map((word) => `${word}:*`)
.join(' & ');
const searchResults = await this.databaseService.$queryRaw<
{ pollId: number }[]
>`
SELECT "pollId" FROM "Poll"
WHERE "searchVector" @@ to_tsquery('english', ${searchQuery})
ORDER BY ts_rank("searchVector", to_tsquery('english', ${searchQuery})) DESC
`;
return searchResults.map((result) => result.pollId);
}
private async searchPolls(searchTerm: string): Promise<number[]> {
// Potential approach: replace non-alphanumeric characters or handle special tokens
const safeTerm = searchTerm.replace(/[^a-zA-Z0-9\s]/g, '');
const searchQuery = safeTerm
.split(' ')
.map((word) => `${word}:*`)
.join(' & ');
const searchResults = await this.databaseService.$queryRaw<
{ pollId: number }[]
>`
SELECT "pollId" FROM "Poll"
WHERE "searchVector" @@ to_tsquery('english', ${searchQuery})
ORDER BY ts_rank("searchVector", to_tsquery('english', ${searchQuery})) DESC
`;
return searchResults.map((result) => result.pollId);
}

Copy link
Collaborator

@Meriem-BM Meriem-BM left a comment

Choose a reason for hiding this comment

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

Thanks!

@RamRamez RamRamez changed the title Add search functionality Add semantic search functionality Apr 16, 2025
@RamRamez RamRamez merged commit c001d3f into develop Apr 16, 2025
1 check passed
@RamRamez RamRamez deleted the add-search-functionality branch April 16, 2025 11:03
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