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