1 import { Note, Prerequisites, Table } from "docs-ui"
2
3 export const metadata = {
4 title: `Migrate from Meilisearch to Medusa Search`,
5 keywords: [
6 "search",
7 "medusa search",
8 "meilisearch",
9 "migration",
10 "migrate",
11 "search module",
12 ],
13 }
14
15 # {metadata.title}
16
17 In this guide, you'll migrate a Medusa project that indexes and searches products in Meilisearch to use [Medusa Search](../page.mdx).
18
19 <Note title="Not a Cloud user yet?">
20
21 [Sign up for Cloud](../../sign-up/page.mdx) to use Medusa Search and other Cloud features.
22
23 </Note>
24
25 <Prerequisites
26 items={[
27 {
28 text: "A Cloud project",
29 link: "/first-project",
30 },
31 {
32 text: "Medusa v2.21.1+",
33 link: "https://github.com/medusajs/medusa/releases/tag/v2.21.1",
34 },
35 ]}
36 />
37
38 ## Migrate with an AI Agent
39
40 If you use an AI agent, such as Claude Code or Codex, ask it to fetch this page:
41
42 ```bash
43 Fetch https://docs.medusajs.com/cloud/search/migrate-from-meilisearch and follow the instructions.
44 ```
45
46 It will receive the following prompt with instructions on performing the full migration:
47
48 ```md title="Migration Prompt" collapsed noLineNumbers
49 <role>
50 You are a senior Medusa developer migrating an existing
51 Medusa project from a custom Meilisearch integration to
52 Medusa Search, the managed search service of Cloud.
53 </role>
54
55 <task>
56 Replace this project's custom Meilisearch integration with
57 the Search Module and Medusa Search, keeping the storefront's
58 search behavior intact.
59 </task>
60
61 <context>
62 - Medusa Search is a provider of the Search Module, which
63 ships with Medusa v2.21.1 and later. Cloud registers and
64 configures it for every environment, so it needs no
65 credentials or configuration in the project.
66 - Medusa declares no index by default, so a project
67 declares its own `product` index definition under
68 `src/search`. A project installed after v2.21.1 ships with
69 one at `src/search/product.ts`, and any other project may
70 or may not have it.
71 - An index definition lives in a file under `src/search`,
72 declares the fields the engine holds, fills the index with
73 a `seed` async generator, and keeps it current with its
74 `events` and `consume` properties.
75 - The `graphSeed` and `graphConsume` helpers build `seed`
76 and `consume` from Query, so an index of an entity Query
77 exposes needs neither written by hand. They take the same
78 options, including a `transform` that maps a page of
79 records to the documents to index. Every document must
80 carry the record's primary key as `id`, and a record you
81 leave out of the returned array stays out of the index.
82 - Medusa's Store API has a `POST /store/search` route that
83 searches any index of the application, so a project
84 doesn't need its own product search route. The body is a
85 search query naming the index in `entity`, or a batch of
86 them under `queries`.
87 - An index is only reachable through `POST /store/search`
88 once a middleware allows it with `configureStoreSearch`
89 from `@medusajs/framework/http`, which takes an
90 `allowed_indexes` object. The route narrows a product
91 index to published products in the publishable API key's
92 sales channels, and any further constraint is that
93 middleware's `filters` option.
94 - Queries run through `query.search` in an API route. Medusa
95 Search has no browser-side querying and no search-only
96 key, so the storefront searches through the Medusa backend
97 rather than the engine.
98 - The `@medusajs/instantsearch-adapter` package is a search
99 client for InstantSearch widgets, so a storefront built on
100 `react-instantsearch` keeps its widgets and swaps the
101 client.
102 - Medusa Search does not support synonyms, custom stop-word
103 lists, geo search, configurable ranking rules, engine-side
104 embedders, or sorting alongside a text query. An index or a
105 query that relies on them fails.
106 - Medusa Search supports typo tolerance and highlighting, but
107 unlike Meilisearch both are opt-in per query through
108 `search_options`. Pass them in the search query to keep the
109 storefront's current behavior.
110 </context>
111
112 <steps>
113 1. Inspect the project and report what it has before you
114 change anything: the Meilisearch module, the sync
115 workflows and their steps, the subscribers, the admin sync
116 route and UI route, the storefront's search client and
117 search modal, and the Medusa version in `package.json`.
118 2. If the Medusa version is below v2.21.1, stop and tell the
119 user to upgrade first.
120 3. List the fields the project indexes in Meilisearch, taken
121 from the `fields` array of `syncProductsWorkflow`, and ask
122 the user for the index settings of their Meilisearch
123 instance. They can read them from
124 `GET /indexes/{index}/settings`.
125 4. Check whether the project already declares a `product`
126 index, which ships at `src/search/product.ts`. If it
127 does and every indexed field and setting is covered by
128 it, skip to step 8 and say why. Otherwise, the project
129 needs an index definition of its own.
130 5. Create the index definition under `src/search`. Map
131 Meilisearch's `searchableAttributes` to `searchable()`
132 fields with a weight, `filterableAttributes` to
133 `facetable()` or `filterable()`, `sortableAttributes` to
134 `sortable()`, and the attributes missing from
135 `displayedAttributes` to `retrievable(false)`. Build
136 `seed` and `consume` with `graphSeed` and `graphConsume`,
137 sharing one options object between them, and reproduce
138 the project's indexing rules in its `transform`, such as
139 leaving a product that isn't published out of the
140 documents it returns. List
141 the entity's create, update, and delete events in
142 `events`.
143 6. Allow every index the storefront searches on
144 `/store/search` with the `configureStoreSearch`
145 middleware in `src/api/middlewares.ts`. An index the
146 middleware doesn't allow answers exactly like one that
147 doesn't exist. The route narrows a product index to
148 published products in the publishable API key's sales
149 channels, so add a `filters` option only for a further
150 constraint.
151 7. Don't create a product search route, since
152 `POST /store/search` serves the storefront. Only write a
153 route with `query.search` for a result the built-in route
154 can't answer with, such as one reshaped for the
155 storefront. In such a route, respond with the hydrated
156 records from `data` and the metadata from `search_result`,
157 and don't also return `search_result.hits`, since each
158 hit's `document` repeats a record already returned.
159 8. Replace any manual sync trigger with a workflow step that
160 calls the Search Module's `reindex` method.
161 9. Delete the Meilisearch module, the sync workflows and
162 steps, the product subscribers, the module's entry in
163 `medusa-config.ts`, and the `meilisearch` dependency.
164 Do this here and not earlier, since the application fails
165 to boot while the module is still registered and the
166 package is gone. Leave the Meilisearch environment
167 variables in place and tell the user to remove them after
168 the cutover.
169 10. Update the storefront to search through Medusa. If it
170 uses InstantSearch widgets, install
171 `@medusajs/instantsearch-adapter`, create its search
172 client with the storefront's JS SDK instance and the
173 path `/store/search`, pass the client and the index
174 name to the existing `InstantSearch` provider, and
175 change every component that reads a hit's `_formatted`
176 fields to read its `highlights` instead. Otherwise, post
177 to `/store/search` with the JS SDK and read the `hits`
178 and `metadata` it returns. Remove the
179 `@meilisearch/instant-meilisearch` package, the
180 Meilisearch `searchClient` export, and the
181 `NEXT_PUBLIC_MEILISEARCH_*` variables. Keep
182 `react-instantsearch`, which the adapter works with.
183 11. Run `npx medusa db:migrate --execute-all-links` to
184 create the index locally, then run the project's type
185 check and tests, and report the result. Never run
186 `medusa db:migrate` without that flag: it asks which
187 link tables to sync, and the prompt is swallowed when
188 the command's output is piped, so it waits forever.
189 </steps>
190
191 <constraints>
192 - Do not add a feature that Medusa Search does not support.
193 When the project relies on one, report it and propose the
194 closest alternative instead of implementing it silently.
195 - Do not delete the user's Meilisearch instance, indexes, or
196 keys, and do not call the Meilisearch API.
197 - Do not expose the search index to the browser. Every query
198 goes through the Medusa backend.
199 - Do not modify `POST /store/search` or recreate it in the
200 project.
201 - Do not refine a widget or a filter on a field the index
202 definition doesn't mark `searchable()`, `filterable()`,
203 `facetable()`, or `sortable()`.
204 - Do not run a deployment or push to any branch.
205 - Never run a Medusa CLI command that can prompt without the
206 flag that skips its prompts. A swallowed prompt reads as a
207 hung command rather than an error, since the command keeps
208 waiting with no output.
209 - Keep every package the current integration imports
210 installed until step 9, so the application boots at every
211 point before it.
212 - Consult the Medusa documentation at
213 https://docs.medusajs.com or the Docs MCP server for any
214 API details you need, including the index definition
215 properties, field types and modifiers, the options of
216 `graphSeed` and `graphConsume`, and the options of
217 `query.search`.
218 </constraints>
219
220 <error_handling>
221 - If the project has no Meilisearch integration, report that
222 and stop.
223 - If the integration differs from the files listed in step
224 1, map each responsibility you find to its Search Module
225 equivalent and report the mapping before you change code.
226 - If you cannot tell whether a field is searched, filtered,
227 faceted, or only displayed, ask the user rather than
228 guessing its modifiers.
229 - If a storefront feature has no Medusa Search equivalent,
230 list it under manual follow-ups instead of removing the
231 feature. The adapter doesn't support `geoSearch`, Insights
232 and Analytics widgets, Query Rules, related-items widgets,
233 autocomplete, or Algolia-style `filters` strings.
234 - If the storefront's search can't be expressed with the
235 built-in route's parameters, ask the user before adding a
236 custom search route for products.
237 </error_handling>
238
239 <output_format>
240 Respond with the following markdown sections:
241
242 ## Changes
243 A table of every file you created, modified, or deleted,
244 with one sentence on what changed in it.
245
246 ## Behavior differences
247 Each Meilisearch behavior the project relied on that Medusa
248 Search does not support, and what you did about it.
249
250 ## Manual follow-ups
251 The steps the user has to take themselves, such as removing
252 environment variables, validating relevance, and deploying.
253 </output_format>
254
255 <success_criteria>
256 - The project builds and type checks with no reference to
257 `meilisearch` or `@meilisearch/instant-meilisearch` left
258 in the backend or the storefront.
259 - Every field the project indexed in Meilisearch is either
260 held by the new index definition, covered by the default
261 product index, or listed as an intentional removal.
262 - Every index the storefront searches is allowed in a
263 `configureStoreSearch` middleware on `/store/search`.
264 - The storefront searches products through
265 `POST /store/search`, and no Meilisearch key reaches the
266 browser.
267 - Every remaining search route uses `query.search` and
268 returns each record once.
269 - Every unsupported Meilisearch behavior appears under
270 "Behavior differences".
271 </success_criteria>
272 ```
273
274 ---
275
276 ## Who This Guide Is For
277
278 This guide assumes your project follows the [Integrate Meilisearch with Medusa](!resources!/integrations/guides/meilisearch) guide, which is the most common Meilisearch setup in Medusa projects. That setup has the following pieces:
279
280 - A Meilisearch Module in `src/modules/meilisearch` that wraps Meilisearch's client.
281 - A `syncProductsWorkflow` and its steps that index and delete products in Meilisearch.
282 - Subscribers on product events and a custom `meilisearch.sync` event.
283 - An admin UI route and API route that trigger a full sync.
284 - A storefront that queries Meilisearch directly from the browser with `@meilisearch/instant-meilisearch` and a search key.
285
286 If your integration differs, the mapping in the [Mapping MeiliSearch Settings to Medusa Search](#mapping-meilisearch-settings-to-medusa-search) section still applies, since every Meilisearch integration owns the same responsibilities.
287
288 <Note title="Not sure whether to migrate?">
289
290 Refer to [Medusa Search vs Meilisearch](../meilisearch/page.mdx) for a feature-by-feature comparison, including the Meilisearch features that Medusa Search doesn't offer.
291
292 </Note>
293
294 ---
295
296 ## What Changes in Your Project
297
298 Medusa Search isn't a drop-in replacement for the Meilisearch client. It's a provider of the [Search Module](!resources!/infrastructure-modules/search), which owns the parts of the integration you wrote by hand. So the migration deletes more code than it adds.
299
300 <Table>
301 <Table.Header>
302 <Table.Row>
303 <Table.HeaderCell>
304 Responsibility
305 </Table.HeaderCell>
306 <Table.HeaderCell>
307 Your Meilisearch integration
308 </Table.HeaderCell>
309 <Table.HeaderCell>
310 Medusa Search
311 </Table.HeaderCell>
312 </Table.Row>
313 </Table.Header>
314 <Table.Body>
315 <Table.Row>
316 <Table.Cell>
317 Running the engine
318 </Table.Cell>
319 <Table.Cell>
320 A self-hosted instance or a Meilisearch Cloud project, which you upgrade and monitor.
321 </Table.Cell>
322 <Table.Cell>
323 Cloud provisions the service and passes the credentials, so nothing to run.
324 </Table.Cell>
325 </Table.Row>
326 <Table.Row>
327 <Table.Cell>
328 Connecting to the engine
329 </Table.Cell>
330 <Table.Cell>
331
332 The Meilisearch Module's service, its options, and three environment variables.
333
334 </Table.Cell>
335 <Table.Cell>
336 Nothing to write.
337 </Table.Cell>
338 </Table.Row>
339 <Table.Row>
340 <Table.Cell>
341 Index schema and settings
342 </Table.Cell>
343 <Table.Cell>
344 Index settings stored on the Meilisearch instance, outside your repository.
345 </Table.Cell>
346 <Table.Cell>
347
348 An [index definition](!resources!/infrastructure-modules/search/index-definitions) in `src/search`, which deploys with your code.
349
350 </Table.Cell>
351 </Table.Row>
352 <Table.Row>
353 <Table.Cell>
354 Initial and full sync
355 </Table.Cell>
356 <Table.Cell>
357
358 `syncProductsWorkflow`, the `meilisearch.sync` subscriber, the admin API route, and the admin UI route.
359
360 </Table.Cell>
361 <Table.Cell>
362
363 The index definition's `seed` generator, which Medusa runs on deployment, plus the `reindex` method for a manual rebuild.
364
365 </Table.Cell>
366 </Table.Row>
367 <Table.Row>
368 <Table.Cell>
369 Incremental sync
370 </Table.Cell>
371 <Table.Cell>
372
373 The `product-sync` and `product-delete` subscribers, and the delete workflow.
374
375 </Table.Cell>
376 <Table.Cell>
377
378 The `events` and `consume` properties of the index definition.
379
380 </Table.Cell>
381 </Table.Row>
382 <Table.Row>
383 <Table.Cell>
384 Rollback on a failed write
385 </Table.Cell>
386 <Table.Cell>
387 Compensation functions that reindex the previous documents.
388 </Table.Cell>
389 <Table.Cell>
390
391 Not needed. A failed `consume` leaves the index behind, and a [reindex](!resources!/infrastructure-modules/search/reindexing#recover-with-a-reindex) repairs it.
392
393 </Table.Cell>
394 </Table.Row>
395 <Table.Row>
396 <Table.Cell>
397 Waiting on a write
398 </Table.Cell>
399 <Table.Cell>
400 Meilisearch queues every write as a task, so a document isn't searchable the moment the call returns.
401 </Table.Cell>
402 <Table.Cell>
403 Medusa Search doesn't defer its writes, so there's no task to poll.
404 </Table.Cell>
405 </Table.Row>
406 <Table.Row>
407 <Table.Cell>
408 Querying
409 </Table.Cell>
410 <Table.Cell>
411 The storefront's Meilisearch client, calling the engine from the browser with a search key.
412 </Table.Cell>
413 <Table.Cell>
414
415 Medusa provides the `/store/search` route out-of-the-box, and you can search as well with [`query.search`](!docs!/learn/fundamentals/query/search).
416
417 </Table.Cell>
418 </Table.Row>
419 <Table.Row>
420 <Table.Cell>
421 Per-environment isolation
422 </Table.Cell>
423 <Table.Cell>
424 An index name or an instance per environment, provisioned and configured by you.
425 </Table.Cell>
426 <Table.Cell>
427
428 [One set of indexes per environment](../page.mdx#search-indexes-per-environment), created for you.
429
430 </Table.Cell>
431 </Table.Row>
432 </Table.Body>
433 </Table>
434
435 ### Behavior Differences to Settle First
436
437 Some Meilisearch behaviors have no equivalent in Medusa Search, and an index or a query that relies on them fails rather than degrading. Decide what to do about each one before you write any code:
438
439 <Table>
440 <Table.Header>
441 <Table.Row>
442 <Table.HeaderCell>
443 Behavior
444 </Table.HeaderCell>
445 <Table.HeaderCell>
446 What to do
447 </Table.HeaderCell>
448 </Table.Row>
449 </Table.Header>
450 <Table.Body>
451 <Table.Row>
452 <Table.Cell>
453 Synonyms and stop words
454 </Table.Cell>
455 <Table.Cell>
456 Medusa Search supports neither, and an index that declares them fails at startup. Expand a query's terms in your API route, or index the alternative terms as a searchable field.
457 </Table.Cell>
458 </Table.Row>
459 <Table.Row>
460 <Table.Cell>
461 Ranking rules
462 </Table.Cell>
463 <Table.Cell>
464
465 Medusa Search ranks by the [weight](!resources!/infrastructure-modules/search/index-definitions/modifiers#searchable) you set on each searchable field. Meilisearch's `rankingRules` order, including a custom `attribute:asc` rule, has no equivalent, so reproduce the ordering you need in the API route.
466
467 </Table.Cell>
468 </Table.Row>
469 <Table.Row>
470 <Table.Cell>
471 Sorting by an attribute
472 </Table.Cell>
473 <Table.Cell>
474
475 Medusa Search sorts by any number of `sortable` fields, but not alongside a text query, which Meilisearch allows. A sorted product listing therefore runs as a separate query from a search, without a `q` filter.
476
477 </Table.Cell>
478 </Table.Row>
479 <Table.Row>
480 <Table.Cell>
481 Hybrid search and embedders
482 </Table.Cell>
483 <Table.Cell>
484
485 On the Scale and Enterprise plans, Medusa Search runs [vector search](!docs!/learn/fundamentals/query/search#vector-and-hybrid-search) on embeddings you compute and store in the index, and it blends text and vector results by a semantic ratio the same way. On the Enterprise plan it can also create the embeddings for you, so you don't configure an embedder yourself.
486
487 </Table.Cell>
488 </Table.Row>
489 <Table.Row>
490 <Table.Cell>
491 Geo search
492 </Table.Cell>
493 <Table.Cell>
494
495 Medusa Search doesn't support geo fields, and an index that declares one fails at startup. Filter on a region or a country field instead of a `_geo` attribute.
496
497 </Table.Cell>
498 </Table.Row>
499 <Table.Row>
500 <Table.Cell>
501 Tenant tokens
502 </Table.Cell>
503 <Table.Cell>
504 Medusa Search has no equivalent, since the engine never sees a request from the browser. Apply the tenant's filter in your API route, where you already know the authenticated customer.
505 </Table.Cell>
506 </Table.Row>
507 </Table.Body>
508 </Table>
509
510 ---
511
512 ## Step 1: Upgrade Your Medusa Application
513
514 Medusa Search requires [Medusa v2.21.1 or later](https://github.com/medusajs/medusa/releases/tag/v2.21.1). Upgrade your application, then confirm it starts locally before you change any search code.
515
516 Refer to the [Update Medusa](../../update-medusa/page.mdx) guide for the upgrade steps.
517
518 Once you upgrade, the Search Module is registered by default with the [PostgreSQL Search Module Provider](!resources!/infrastructure-modules/search/providers/postgres) locally, and with Medusa Search on Cloud. So you don't have to register anything in `medusa-config.ts`.
519
520 ---
521
522 ## Step 2: Declare Your Index
523
524 Medusa declares no index by default, so your application declares its own `product` index in a file under `src/search`. If you installed your Medusa application after v2.21.1, it already has that definition at `src/search/product.ts`. Otherwise, check whether the file is there, and declare the index if it isn't.
525
526 Customize your `product` index definition, or declare another index, in the following cases:
527
528 - Your Meilisearch documents hold custom fields that your `product` index doesn't. You can then add those fields to the definition.
529 - You need index settings or field options that your definition doesn't apply, such as a different weight, a facetable field, or a [Medusa Search setting](../page.mdx#medusa-search-settings).
530 - You indexed data models other than products in Meilisearch, such as product categories. You then declare an index for each of them.
531
532 Otherwise, skip to [Step 3](#step-3-replace-the-search-api-route) and query the `product` index you already have.
533
534 An [index definition](!resources!/infrastructure-modules/search/index-definitions) replaces your Meilisearch index's settings, holding the schema, the initial fill, and the event handling in one file that deploys with your code. The definition alone decides what the index holds, so customize `src/search/product.ts` rather than adding a second definition named `product`.
535
536 <Note title="Tip">
537
538 The example index below is simplified to show one feature at a time. For examples of indexing prices in multiple currencies, option values, categories, and other product data, refer to the [Product Index Examples guide](!resources!/infrastructure-modules/search/product-index-examples).
539
540 </Note>
541
542 For example, the integration guide indexes each product's `id`, `title`, `description`, `handle`, `thumbnail`, `categories`, and `tags`, and it indexes published products only. To reproduce that, create the file `src/search/product.ts` with the following content:
543
544 export const definitionHighlights = [
545 ["29", "title", "Outweighs the description in relevance."],
546 ["32", "thumbnail", "Held by the index, but never searched or filtered."],
547 ["33", "status", "Lets the Store Search API route scope the index to published products."],
548 ["37", "categories", "An array of objects, so a filter matches any category."],
549 ["43", "facetable", "Powers the storefront's category filter counts."],
550 ]
551
552 ```ts title="src/search/product.ts" highlights={definitionHighlights}
553 import {
554 defineSearchIndex,
555 graphConsume,
556 graphSeed,
557 search,
558 } from "@medusajs/framework/utils"
559
560 const source = {
561 fields: [
562 "id",
563 "title",
564 "description",
565 "handle",
566 "thumbnail",
567 "status",
568 "categories.id",
569 "categories.name",
570 "categories.handle",
571 "tags.id",
572 "tags.value",
573 ],
574 }
575
576 export const productIndex = defineSearchIndex({
577 name: "product",
578 entity: "product",
579 fields: search.define({
580 id: search.keyword().filterable(),
581 title: search.text().searchable({ weight: 3 }),
582 description: search.text().searchable(),
583 handle: search.keyword().filterable(),
584 thumbnail: search.keyword(),
585 status: search
586 .keyword()
587 .filterable()
588 .retrievable(false),
589 categories: search
590 .object({
591 id: search.keyword().filterable(),
592 name: search
593 .keyword()
594 .searchable()
595 .facetable(),
596 handle: search.keyword().filterable(),
597 })
598 .array(),
599 tags: search
600 .object({
601 id: search.keyword().filterable(),
602 value: search
603 .keyword()
604 .searchable()
605 .facetable(),
606 })
607 .array(),
608 }),
609 events: [
610 "product.created",
611 "product.updated",
612 "product.deleted",
613 ],
614 consume: graphConsume(source),
615 seed: graphSeed(source),
616 })
617 ```
618
619 The definition declares the fields the engine holds, then lets the [`graphSeed`](!resources!/infrastructure-modules/search/index-definitions#fill-the-index-from-query-with-graphseed) and [`graphConsume`](!resources!/infrastructure-modules/search/index-definitions#consume-events-from-query-with-graphconsume) helpers read those fields from [Query](!docs!/learn/fundamentals/query). Note the following about it:
620
621 - `graphSeed` fills the index for the first time, reading the catalog in batches and resuming an interrupted run, so you don't paginate the read yourself.
622 - `graphConsume` replaces your `product-sync` and `product-delete` subscribers. Medusa routes each event in `events` to it, and it upserts or deletes the affected product's document.
623 - Both helpers share the same `source`, so an event writes the same document the seed does. Its `transform` indexes published products only, which is the check the `syncProductsWorkflow` performs in its `transform` function, and leaving any other product out of the documents it returns deletes that product's document, the way `deleteProductsFromAlgoliaStep` did.
624
625 ### Mapping Meilisearch Settings to Medusa Search
626
627 If you're creating a custom index for Medusa Search, you'll need to map each Meilisearch setting to its equivalent in Medusa Search:
628
629 <Table>
630 <Table.Header>
631 <Table.Row>
632 <Table.HeaderCell>
633 Meilisearch
634 </Table.HeaderCell>
635 <Table.HeaderCell>
636 Medusa Search
637 </Table.HeaderCell>
638 </Table.Row>
639 </Table.Header>
640 <Table.Body>
641 <Table.Row>
642 <Table.Cell>
643 `searchableAttributes`
644 </Table.Cell>
645 <Table.Cell>
646
647 A [`search.text()`](!resources!/infrastructure-modules/search/index-definitions/fields#searchtext) field with the [`searchable()`](!resources!/infrastructure-modules/search/index-definitions/modifiers#searchable) modifier. The attribute's position in Meilisearch's ordered list becomes a `weight`.
648
649 </Table.Cell>
650 </Table.Row>
651 <Table.Row>
652 <Table.Cell>
653 `filterableAttributes`
654 </Table.Cell>
655 <Table.Cell>
656
657 The [`facetable()`](!resources!/infrastructure-modules/search/index-definitions/modifiers#facetable) modifier for an attribute the storefront shows counts for, and [`filterable()`](!resources!/infrastructure-modules/search/index-definitions/modifiers#filterable) for one you only filter on. Meilisearch uses one setting for both, so check which attributes your storefront facets on.
658
659 </Table.Cell>
660 </Table.Row>
661 <Table.Row>
662 <Table.Cell>
663 `sortableAttributes`
664 </Table.Cell>
665 <Table.Cell>
666
667 The [`sortable()`](!resources!/infrastructure-modules/search/index-definitions/modifiers#sortable) modifier, with the caveat that a sort doesn't run alongside a text query.
668
669 </Table.Cell>
670 </Table.Row>
671 <Table.Row>
672 <Table.Cell>
673 `displayedAttributes`
674 </Table.Cell>
675 <Table.Cell>
676
677 The [`retrievable()`](!resources!/infrastructure-modules/search/index-definitions/modifiers#retrievable) modifier set to `false` on every attribute you left out of the list.
678
679 </Table.Cell>
680 </Table.Row>
681 <Table.Row>
682 <Table.Cell>
683 `rankingRules`
684 </Table.Cell>
685 <Table.Cell>
686
687 A `weight` per searchable field. Medusa Search has no equivalent for the rest of Meilisearch's ranking criteria.
688
689 </Table.Cell>
690 </Table.Row>
691 <Table.Row>
692 <Table.Cell>
693 `distinctAttribute`
694 </Table.Cell>
695 <Table.Cell>
696
697 The [`distinct_attribute`](../page.mdx#index-settings) index setting, or the `distinct` search option for a single query.
698
699 </Table.Cell>
700 </Table.Row>
701 <Table.Row>
702 <Table.Cell>
703 `faceting.maxValuesPerFacet`
704 </Table.Cell>
705 <Table.Cell>
706
707 The `faceting.max_values_per_facet` index setting, alongside `faceting.sort_by`.
708
709 </Table.Cell>
710 </Table.Row>
711 <Table.Row>
712 <Table.Cell>
713 `pagination.maxTotalHits`
714 </Table.Cell>
715 <Table.Cell>
716
717 The `pagination.max_total_hits` index setting. Medusa Search caps a query at the 10,000th result regardless.
718
719 </Table.Cell>
720 </Table.Row>
721 <Table.Row>
722 <Table.Cell>
723 `typoTolerance`
724 </Table.Cell>
725 <Table.Cell>
726
727 The [`typo_tolerance`](../page.mdx#typo-tolerance) index setting, which carries the same `min_word_size_for_one_typo` and `min_word_size_for_two_typos` thresholds. `disableOnAttributes` becomes `disabled_on_attributes`, and `disableOnWords` has no equivalent. A query then opts in with the `typo_tolerance` search option, which Meilisearch didn't require.
728
729 </Table.Cell>
730 </Table.Row>
731 <Table.Row>
732 <Table.Cell>
733 `synonyms` and `stopWords`
734 </Table.Cell>
735 <Table.Cell>
736
737 No equivalent. Settle them as explained in [Behavior Differences to Settle First](#behavior-differences-to-settle-first).
738
739 </Table.Cell>
740 </Table.Row>
741 <Table.Row>
742 <Table.Cell>
743 Primary key
744 </Table.Cell>
745 <Table.Cell>
746
747 The index's [`primary_key`](!resources!/infrastructure-modules/search/index-definitions#index-definition-properties), which defaults to `id`. Since the integration guide indexes each product under its own ID, you can keep the default.
748
749 </Table.Cell>
750 </Table.Row>
751 <Table.Row>
752 <Table.Cell>
753 One index or instance per environment
754 </Table.Cell>
755 <Table.Cell>
756
757 One index definition. Cloud scopes the physical indexes per environment, so the `MEILISEARCH_PRODUCT_INDEX_NAME` variable goes away.
758
759 </Table.Cell>
760 </Table.Row>
761 </Table.Body>
762 </Table>
763
764 ### Test the Index Locally
765
766 Locally, the PostgreSQL provider holds the index in your database, so run the migrations that create it:
767
768 ```bash npm2yarn
769 npx medusa db:migrate
770 ```
771
772 Then start your application. The Search Module fills the index when the application starts in worker or shared mode. You no longer need a Meilisearch instance running on your machine to develop against search.
773
774 ---
775
776 ## Step 3: Replace the Search API Route
777
778 Medusa's Store API has a [`POST /store/search` API route](!api!/store/search/search-indexes) that searches any index of your application, including the `product` index you declared in [Step 2](#step-2-declare-your-index).
779
780 An index isn't searchable through the route until a middleware allows it, so add the `configureStoreSearch` middleware in `src/api/middlewares.ts`:
781
782 ```ts title="src/api/middlewares.ts"
783 import {
784 configureStoreSearch,
785 defineMiddlewares,
786 } from "@medusajs/framework/http"
787
788 export default defineMiddlewares({
789 routes: [
790 {
791 matcher: "/store/search",
792 middlewares: [
793 configureStoreSearch({
794 allowed_indexes: {
795 product: true,
796 },
797 }),
798 ],
799 },
800 ],
801 })
802 ```
803
804 The route narrows a product index to published products in the publishable API key's sales channels. Learn more in the [Store Search API Route guide](!resources!/infrastructure-modules/search/store-search).
805
806 Then, you can delete the route you previously created for searching products, and use the built-in route instead:
807
808 ```bash
809 MEDUSA_URL=https://your-project.medusajs.app
810
811 curl -X POST "$MEDUSA_URL/store/search" \
812 -H "x-publishable-api-key: {your_publishable_api_key}" \
813 -H "Content-Type: application/json" \
814 --data '{
815 "entity": "product",
816 "filters": { "q": "sweatshirt" },
817 "pagination": { "take": 20 }
818 }'
819 ```
820
821 The route returns a JSON response like the following:
822
823 ```json
824 {
825 "results": [
826 {
827 "hits": [
828 {
829 "id": "prod_01KXR3J9J610DT161E2E4ZS6P1",
830 "score": 1.42,
831 "document": {
832 "id": "prod_01KXR3J9J610DT161E2E4ZS6P1",
833 "title": "Medusa Sweatshirt",
834 "description": "A classic sweatshirt, reimagined.",
835 "handle": "sweatshirt",
836 "thumbnail": "https://medusa-public-images.s3.eu-west-1.amazonaws.com/sweatshirt-vintage-front.png"
837 }
838 }
839 ],
840 "metadata": {
841 "skip": 0,
842 "take": 20,
843 "count": 12,
844 "query": "sweatshirt",
845 "processing_time_ms": 7
846 }
847 }
848 ]
849 }
850 ```
851
852 The route answers with one result per posted query, each holding the matching `hits` ranked by relevance and the query's `metadata`. Where Meilisearch reported `estimatedTotalHits`, the count is in `metadata.count`. [Step 4](#step-4-update-the-storefront) provides guidance on updating your storefront to read the new response shape.
853
854 ### Search a Custom Index
855
856 If you indexed data models other than products in Meilisearch, such as brands, create an API route that searches their index with [`query.search`](!docs!/learn/fundamentals/query/search).
857
858 For example, to search a `brand` index, create the file `src/api/store/brands/search/route.ts` with the following content:
859
860 ```ts title="src/api/store/brands/search/route.ts"
861 import {
862 MedusaRequest,
863 MedusaResponse,
864 } from "@medusajs/framework/http"
865 import {
866 ContainerRegistrationKeys,
867 } from "@medusajs/framework/utils"
868 import { z } from "@medusajs/framework/zod"
869
870 export const SearchSchema = z.object({
871 query: z.string(),
872 limit: z.number().optional().default(20),
873 offset: z.number().optional().default(0),
874 })
875
876 type SearchRequest = z.infer<typeof SearchSchema>
877
878 export async function POST(
879 req: MedusaRequest<SearchRequest>,
880 res: MedusaResponse
881 ) {
882 const query = req.scope.resolve(
883 ContainerRegistrationKeys.QUERY
884 )
885
886 const { query: q, limit, offset } = req.validatedBody
887
888 const { data, search_result } = await query.search({
889 entity: "brand",
890 fields: ["id", "name", "country"],
891 filters: { q },
892 pagination: { skip: offset, take: limit },
893 })
894
895 res.json({
896 brands: data,
897 metadata: search_result.metadata,
898 })
899 }
900 ```
901
902 The route resolves [Query](!docs!/learn/fundamentals/query) from the Medusa container and searches the `brand` index, which is the `name` of its definition. `query.search` returns the hydrated entities in `data` and the engine's own result in `search_result`.
903
904 ### Add Filters, Facets, and Sorting
905
906 You can apply filters, facets, and sorting directly in the API route using the `filters` and `search_options` parameters of `query.search`.
907
908 For example, to filter the brands by country and return the country counts:
909
910 ```ts title="src/api/store/brands/search/route.ts"
911 const { data, search_result } = await query.search({
912 entity: "brand",
913 fields: ["id", "name", "country"],
914 filters: {
915 q,
916 country: req.validatedBody.country,
917 },
918 search_options: {
919 facets: ["country"],
920 disjunctive_facets: true,
921 },
922 pagination: { skip: offset, take: limit },
923 })
924 ```
925
926 `disjunctive_facets` keeps the sibling country counts visible while a country filter is active, which is what a filter sidebar needs. Refer to [Search Queries](!docs!/learn/fundamentals/query/search) for every filter operator, facet type, and sorting option.
927
928 <Note>
929
930 Medusa Search can't sort by a field alongside a text query. If your storefront offers "sort by price" on a search results page, run the sorted listing as a separate query without a `q` filter.
931
932 </Note>
933
934 ---
935
936 ## Step 4: Update the Storefront
937
938 Medusa provides an [InstantSearch adapter](!resources!/instantsearch) for connecting your storefront to the Medusa backend and searching products. You can use the same widgets for displaying search results as you did with Meilisearch.
939
940 In your storefront, install the adapter:
941
942 ```bash npm2yarn
943 npm install @medusajs/instantsearch-adapter
944 ```
945
946 You should also install InstantSearch packages specific for your frontend framework if you haven't already, such as `react-instantsearch` or `vue-instantsearch`.
947
948 Then, replace the Meilisearch `searchClient` with the adapter's client. For example, create the file `src/lib/search-client.ts` with the following content:
949
950 ```ts title="src/lib/search-client.ts"
951 import {
952 createInstantSearchAdapter,
953 } from "@medusajs/instantsearch-adapter"
954 // JS SDK instance
955 import { sdk } from "./config"
956
957 export const PRODUCT_INDEX_NAME = "product"
958
959 export const { searchClient } = createInstantSearchAdapter({
960 sdk,
961 path: "/store/search",
962 })
963 ```
964
965 The adapter sends the requests with the [Medusa JS SDK](!resources!/js-sdk) instance your storefront already exports, so the publishable API key and the other headers are set for you.
966
967 Next, pass the client to your existing `InstantSearch` provider and set `indexName` to the `name` of your index definition:
968
969 ```tsx title="src/components/search/index.tsx"
970 import {
971 Configure,
972 InstantSearch,
973 SearchBox,
974 } from "react-instantsearch"
975 import {
976 PRODUCT_INDEX_NAME,
977 searchClient,
978 } from "../../lib/search-client"
979
980 const Search = () => (
981 <InstantSearch
982 indexName={PRODUCT_INDEX_NAME}
983 searchClient={searchClient}
984 >
985 <Configure hitsPerPage={12} />
986 <SearchBox />
987 {/* your existing hit list, filters, and pagination widgets */}
988 </InstantSearch>
989 )
990
991 export default Search
992 ```
993
994 Finally, clean up what's left behind from the Meilisearch integration:
995
996 1. Remove the Meilisearch `searchClient` from `src/lib/config.ts`, along with the `@meilisearch/instant-meilisearch` dependency and environment variables like `NEXT_PUBLIC_MEILISEARCH_*`.
997 2. Change every component that reads a hit's `objectID` to read `id` instead, since the adapter builds a hit from the document your index holds.
998 3. Confirm each field your widgets filter, facet, or sort on is marked `filterable()`, `facetable()`, or `sortable()` in the index definition you wrote in [Step 2](#step-2-declare-your-index). A widget can't refine on a field the index doesn't hold that way.
999
1000 Refer to the [InstantSearch Adapter](!resources!/instantsearch) guide for the full setup, the adapter's configuration options, and the widgets it supports. For filters, facets, sorting, and pagination, refer to the [Filtering, Sorting, and Pagination](!resources!/instantsearch/examples/filtering-sorting-pagination) example.
1001
1002 ---
1003
1004 ## Step 5: Replace the Manual Sync
1005
1006 The integration guide's admin page triggers a full sync through the `meilisearch.sync` event. You no longer need that sync for everyday changes:
1007
1008 1. Medusa fills the index on deployment.
1009 2. Medusa keeps the index current from the `events` and `consume` properties of the index definition, applying every product change as it happens. This applies for both the product index Medusa creates by default or the custom definition you wrote in [Step 2](#step-2-declare-your-index).
1010
1011 A manual rebuild is only for repairing a diverged index, such as after a `consume` call failed or a change reached the database without emitting an event.
1012
1013 For a manual rebuild, you can drop the custom admin page entirely: admin users can rebuild any index from Settings -> Search in the Medusa Admin dashboard. Refer to the [Manage Search Indexes](!user-guide!/settings/search) user guide.
1014
1015 ### Triggering a Manual Rebuild in Code
1016
1017 If you'd rather trigger the rebuild from your own code, replace the `syncProductsWorkflow` with a step that calls the Search Module's [`reindex`](!resources!/infrastructure-modules/search/reindexing#seeding-on-demand) method.
1018
1019 For example, create the file `src/workflows/steps/reindex-products.ts` with the following content:
1020
1021 ```ts title="src/workflows/steps/reindex-products.ts"
1022 import { Modules } from "@medusajs/framework/utils"
1023 import {
1024 createStep,
1025 StepResponse,
1026 } from "@medusajs/framework/workflows-sdk"
1027
1028 export const reindexProductsStep = createStep(
1029 "reindex-products",
1030 async (_, { container }) => {
1031 const searchModuleService = container.resolve(
1032 Modules.SEARCH
1033 )
1034
1035 const result = await searchModuleService.reindex({
1036 index: "product",
1037 })
1038
1039 return new StepResponse(result)
1040 }
1041 )
1042 ```
1043
1044 In this example, you use the `reindex` method from the Search Module to trigger a manual rebuild of the product index. You can then use this step in a workflow to programmatically rebuild the index whenever needed.
1045
1046 <Note>
1047
1048 `reindex` waits for the rebuild to finish before it resolves, so run it in a workflow rather than in the request handler of your admin API route. Refer to [Long-Running Workflows](!docs!/learn/fundamentals/workflows/long-running-workflow) if the rebuild outlasts your request timeout.
1049
1050 </Note>
1051
1052 ---
1053
1054 ## Step 6: Remove the Meilisearch Integration
1055
1056 Once your searches run against the new index, delete the code that Medusa Search replaces. From a project that followed the integration guide, remove the following:
1057
1058 <Table>
1059 <Table.Header>
1060 <Table.Row>
1061 <Table.HeaderCell>
1062 What to remove
1063 </Table.HeaderCell>
1064 <Table.HeaderCell>
1065 Why
1066 </Table.HeaderCell>
1067 </Table.Row>
1068 </Table.Header>
1069 <Table.Body>
1070 <Table.Row>
1071 <Table.Cell>
1072
1073 `src/modules/meilisearch`
1074
1075 </Table.Cell>
1076 <Table.Cell>
1077 The Search Module and its provider replace the client wrapper.
1078 </Table.Cell>
1079 </Table.Row>
1080 <Table.Row>
1081 <Table.Cell>
1082
1083 The module's entry in the `modules` array of `medusa-config.ts`
1084
1085 </Table.Cell>
1086 <Table.Cell>
1087 Removing the directory without this leaves your application failing to boot.
1088 </Table.Cell>
1089 </Table.Row>
1090 <Table.Row>
1091 <Table.Cell>
1092
1093 `src/workflows/sync-products.ts`, `src/workflows/delete-products-from-meilisearch.ts`, and their steps
1094
1095 </Table.Cell>
1096 <Table.Cell>
1097
1098 The index definition's `seed` and `consume` functions replace them.
1099
1100 </Table.Cell>
1101 </Table.Row>
1102 <Table.Row>
1103 <Table.Cell>
1104
1105 `src/subscribers/meilisearch-sync.ts`, `src/subscribers/product-sync.ts`, and `src/subscribers/product-delete.ts`
1106
1107 </Table.Cell>
1108 <Table.Cell>
1109
1110 Medusa subscribes to the events in the definition's `events` array.
1111
1112 </Table.Cell>
1113 </Table.Row>
1114 <Table.Row>
1115 <Table.Cell>
1116
1117 The `meilisearch` dependency
1118
1119 </Table.Cell>
1120 <Table.Cell>
1121 Nothing in the backend calls Meilisearch anymore.
1122 </Table.Cell>
1123 </Table.Row>
1124 <Table.Row>
1125 <Table.Cell>
1126
1127 The `MEILISEARCH_HOST`, `MEILISEARCH_API_KEY`, and `MEILISEARCH_PRODUCT_INDEX_NAME` variables
1128
1129 </Table.Cell>
1130 <Table.Cell>
1131
1132 Remove them from every environment, including the [Cloud environment variables](../../environments/environment-variables/page.mdx). Delete them last, after the cutover.
1133
1134 </Table.Cell>
1135 </Table.Row>
1136 </Table.Body>
1137 </Table>
1138
1139 ---
1140
1141 ## Step 7: Deploy and Fill the Index to Preview
1142
1143 With the backend and the storefront changes in place, push your changes to the branch of a Cloud environment. Use a [preview](../../environments/preview/page.mdx) or [staging](../../environments/long-lived/page.mdx) rather than production for the first deployment, so you can make sure everything works as expected.
1144
1145 During the deployment, Cloud runs the search migrations, which create the physical index for your definition. The Search Module then fills it with the documents that `seed` yields when the application starts.
1146
1147 Once your application is deployed, you can check the Medusa Admin dashboard for the status of the search index by going to Settings -> Search. Learn more in the [User Guide](!user-guide!/settings/search).
1148
1149 If the index status is successful, it means the seeding has finished. You can test it out either by [sending a request to the Store Search API route](#step-3-replace-the-search-api-route), or by using the storefront search interface to confirm that products appear as expected.
1150
1151 ---
1152
1153 ## Step 8: Deploy Your Index
1154
1155 Once the preview environment's search holds up, merge your changes into your production environment. Cloud builds and deploys your project, creates the production index, and fills it with the documents that `seed` yields.
1156
1157 ---
1158
1159 ## Next Steps
1160
1161 - Index your other data models, including your custom ones, as explained in [Searching Custom Data Models](../page.mdx#searching-custom-data-models).
1162 - Configure how Medusa Search treats your index and its fields with the [Medusa Search Settings](../page.mdx#medusa-search-settings).
1163 - Add semantic search, either over embeddings you store in the index or over ones Medusa Search creates for you, as explained in [Vector and Hybrid Search](!docs!/learn/fundamentals/query/search#vector-and-hybrid-search).