meilisearch-js-plugins icon indicating copy to clipboard operation
meilisearch-js-plugins copied to clipboard

feature: handle per index meilisearch params

Open 8byr0 opened this issue 11 months ago • 5 comments

Pull Request

Related issue

Fixes #1361

What does this PR do?

  • Allow configuring meilisearchParams for each index individually (multi search)

From :

const client = instantMeiliSearch(
      "host",
      "key",
      {
        meiliSearchParams: {
          matchingStrategy: MatchingStrategies.ALL,
        },
      },
    ).searchClient;

To :

const client = instantMeiliSearch("host", "key", {
  meiliSearchParams: {
    indexesOverrides: {
      products: { matchingStrategy: MatchingStrategies.ALL },
      categories: { matchingStrategy: MatchingStrategies.LAST },
    },
  },
}).searchClient

PR checklist

Please check if your PR fulfills the following requirements:

  • [x] Does this PR fix an existing issue, or have you listed the changes applied in the PR description (and why they are needed)?
  • [x] Have you read the contributing guidelines?
  • [x] Have you made sure that the title is accurate and descriptive of the changes?

Thank you so much for contributing to Meilisearch!

8byr0 avatar Jan 17 '25 15:01 8byr0

⚠️ No Changeset found

Latest commit: 7502e75a0af91e402ad656d168e22860509964a5

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

changeset-bot[bot] avatar Jan 17 '25 15:01 changeset-bot[bot]

My initial proposal in #1364 was to be able to override directly like :

const client = instantMeiliSearch(
      "host",
      "key",
      {
        meiliSearchParams: {
          products: { matchingStrategy: MatchingStrategies.ALL },
          categories: { matchingStrategy: MatchingStrategies.LAST },
        },
      },
    ).searchClient;

Unfortunately as far as I've seen it's not possible using typescript

This one works fine for accessing the values

export type OverridableMeiliSearchSearchParameters = BaseMeiliSearchSearchParameters & {
  [K in Exclude<string, keyof BaseMeiliSearchSearchParameters>]?: BaseMeiliSearchSearchParameters;
};
// No TS errors
const res = myobject[indexName].attributesToRetrieve;

// TS error
const meiliSearchParams: OverridableMeiliSearchSearchParameters = {
      attributesToHighlight: ['movies', 'genres'],
      highlightPreTag: '<em>',
      highlightPostTag: '</em>',
      matchingStrategy: MatchingStrategies.ALL,
    }

This one works fine for declaring values

export type OverridableMeiliSearchSearchParameters =
  | BaseMeiliSearchSearchParameters
  | (BaseMeiliSearchSearchParameters & {
      [K in Exclude<
        string,
        keyof BaseMeiliSearchSearchParameters
      >]?: BaseMeiliSearchSearchParameters
    })
// TS errors
const res = myobject[indexName].attributesToRetrieve;

// No TS errors
const meiliSearchParams: OverridableMeiliSearchSearchParameters = {
      attributesToHighlight: ['movies', 'genres'],
      highlightPreTag: '<em>',
      highlightPostTag: '</em>',
      matchingStrategy: MatchingStrategies.ALL,
    }

Open to discuss it if anyone has another approach in mind

8byr0 avatar Jan 17 '25 16:01 8byr0

Thank you for opening this PR, I will take a look and review it ASAP.

Strift avatar Jan 21 '25 05:01 Strift

Just realised the override mechanism was not setup for filters and facets arguments so I added it in the same way as others (latest commit)

8byr0 avatar Jan 21 '25 15:01 8byr0

@Strift any update on this ?

8byr0 avatar Feb 14 '25 07:02 8byr0

Walkthrough

Adds per-index meiliSearchParams: types now allow an indexesOverrides map, the search-params adapter resolves per-index values before global ones for many MeiliSearch parameters, client merging of indexesOverrides is added, and tests + README updated. No public function signatures changed.

Changes

Cohort / File(s) Summary
Docs
packages/instant-meilisearch/README.md
Adds documentation and an example demonstrating meiliSearchParams.indexesOverrides for per-index parameter overrides.
Types
packages/instant-meilisearch/src/types/types.ts
Introduces BaseOverridableMeiliSearchSearchParameters and updates OverridableMeiliSearchSearchParameters to include optional indexesOverrides?: Record<string, BaseOverridableMeiliSearchSearchParameters>.
Adapter Logic
packages/instant-meilisearch/src/adapter/search-request-adapter/search-params-adapter.ts
Implements per-index precedence for many params: resolves overrideParams?.indexesOverrides?.[indexUid]?.<param> ?? overrideParams?.<param> ?? source/default for numerous MeiliSearch params (facets, attributesToCrop, cropLength, cropMarker, filter, attributesToRetrieve, attributesToHighlight, highlightPreTag, highlightPostTag, showMatchesPosition, matchingStrategy, showRankingScore, attributesToSearchOn, hybrid, vector, distinct, rankingScoreThreshold, etc.).
Client Merge
packages/instant-meilisearch/src/client/instant-meilisearch-client.ts
setMeiliSearchParams now merges existing and new indexesOverrides objects so per-index overrides are combined rather than replaced.
Tests: Adapter
packages/instant-meilisearch/src/adapter/search-request-adapter/__tests__/search-params.test.ts
Adds unit tests asserting per-index override precedence across multiple parameters (highlight tags, matchingStrategy, hybrid, vector, rankingScoreThreshold, distinct, filters behavior).
Tests: Integration
packages/instant-meilisearch/__tests__/overridden-meilisearch-parameters.test.ts
Adds integration tests for per-index highlight tag overrides and that per-index sort overrides global sort.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant UI as InstantSearch UI
  participant IMS as instantMeiliSearch Client
  participant SPA as SearchParamsAdapter
  participant MS as Meilisearch

  UI->>IMS: search({ indexUid, query })
  IMS->>SPA: buildSearchParams(indexUid, baseParams)
  rect rgb(239,248,255)
    note right of SPA: Resolution order: per-index → global → source/default
    SPA->>SPA: value = overrideParams?.indexesOverrides?.[indexUid]?.param
    alt value undefined
      SPA->>SPA: value = overrideParams?.param
    end
    SPA->>SPA: fallback = original/source/default
  end
  SPA-->>IMS: resolved per-index meiliSearchParams
  IMS->>MS: multi-search(requests with per-index params)
  MS-->>IMS: results
  IMS-->>UI: render results

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Assessment against linked issues

Objective Addressed Explanation
Add per-index meiliSearchParams for multi search (#1361)
Update types to support per-index overrides (#1361)
Apply per-index handling for relevant params in adapter (#1361)

I hop through indexes, one by one,
I tweak the tags, I make it fun.
Per-index rules, precise and neat,
Each query gets its proper seat.
Rabbit cheers — overrides complete! 🐇✨

[!TIP]

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • [ ] 📝 Generate Docstrings
🧪 Generate unit tests
  • [ ] Create PR with unit tests
  • [ ] Post copyable unit tests in a comment

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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

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

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit 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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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.

coderabbitai[bot] avatar Aug 28 '25 23:08 coderabbitai[bot]