1 import { Table, TypeList, Prerequisites } from "docs-ui"
2
3 export const metadata = {
4 title: `Reindexing and Migrations`,
5 }
6
7 # {metadata.title}
8
9 In this guide, you'll learn how the Search Module creates physical indexes, fills them, and rebuilds them when a definition changes.
10
11 <Prerequisites
12 items={[
13 {
14 text: "Medusa v2.21.1+",
15 link: "https://github.com/medusajs/medusa/releases/tag/v2.21.1"
16 }
17 ]}
18 />
19
20 ## Index Migrations
21
22 A [search index definition](../index-definitions/page.mdx) declares what an index should look like. The physical index in the search engine is a separate thing, so the [Search Module](../page.mdx) has to bring the two in line. It does that with an index migration.
23
24 Index migrations run as part of the `db:migrate` command:
25
26 ```bash npx2yarn
27 npx medusa db:migrate
28 ```
29
30 <Note title="Tip">
31
32 You can pass `--skip-search` to `db:migrate` to skip search migrations.
33
34 </Note>
35
36 You can also run them on their own with the following command:
37
38 ```bash npx2yarn
39 npx medusa db:migrate:search
40 ```
41
42 The command plans the actions first, then prints what it did:
43
44 ```bash
45 info: Migrating search indexes...
46 ┌────────────────────────────────────┐
47 │ │
48 │ Created following search indexes │
49 │ - product (product) │
50 │ │
51 └────────────────────────────────────┘
52 info: Search indexes migrated. They are filled when the application starts
53 ```
54
55 Every action is idempotent, so running it twice has no adverse effect. When the physical indexes already match every definition, the command prints `Search indexes already up-to-date` and changes nothing.
56
57 The command reports each action under one of the following:
58
59 <Table>
60 <Table.Header>
61 <Table.Row>
62 <Table.HeaderCell>
63 Action
64 </Table.HeaderCell>
65 <Table.HeaderCell>
66 When it Happens
67 </Table.HeaderCell>
68 </Table.Row>
69 </Table.Header>
70 <Table.Body>
71 <Table.Row>
72 <Table.Cell>
73 `create`
74 </Table.Cell>
75 <Table.Cell>
76 No version of the index has ever gone live, so the module builds its first version. Nothing serves the index until a seed fills that version.
77 </Table.Cell>
78 </Table.Row>
79 <Table.Row>
80 <Table.Cell>
81 `migrate`
82 </Table.Cell>
83 <Table.Cell>
84 The definition's `fields` or `settings` changed, or the index moved to another provider. The module builds a new version to match, leaving the active one serving reads.
85 </Table.Cell>
86 </Table.Row>
87 <Table.Row>
88 <Table.Cell>
89 `drop`
90 </Table.Cell>
91 <Table.Cell>
92 No definition declares the index any more, so the module removes every version it ever built for it, along with the record tracking them. This is the only destructive action, and the only one the command asks about first. Refer to [Dropping Removed Indexes](#dropping-removed-indexes).
93 </Table.Cell>
94 </Table.Row>
95 <Table.Row>
96 <Table.Cell>
97 `noop`
98 </Table.Cell>
99 <Table.Cell>
100 The physical index already matches the definition. The module still removes the versions an earlier swap left behind, as explained in [How Index Changes Are Handled](#how-index-changes-are-handled).
101 </Table.Cell>
102 </Table.Row>
103 </Table.Body>
104 </Table>
105
106 ### Dropping Removed Indexes
107
108 When you remove an index definition from your application, the index in the search engine stays behind. So, the command plans a `drop` for it, which deletes every document it holds and can't be undone. The only way back is to declare the definition again and let it seed.
109
110 Since that's destructive, the command lists those indexes and asks which of them to drop before it touches any of them:
111
112 ```bash
113 ┌──────────────────────────────────────────────────────────┐
114 │ │
115 │ Select the search indexes to DROP. No │
116 │ definition declares them any more, and │
117 │ dropping one deletes every document it holds. │
118 │ │
119 └──────────────────────────────────────────────────────────┘
120 ? Select search indexes to drop
121 ❯ ◯ article (article_v2, article_v1)
122 ```
123
124 Pass one of the following options to `db:migrate` or `db:migrate:search` to skip the prompt:
125
126 - `--execute-all-search`: drop every index that no definition declares any more.
127 - `--execute-safe-search`: leave those indexes in place.
128
129 <Note>
130
131 A command with no terminal to prompt in, such as in a CI pipeline, leaves those indexes in place unless you pass `--execute-all-search`. It never drops an index you didn't approve.
132
133 </Note>
134
135 ### How Index Changes Are Handled
136
137 An index name, such as `product`, isn't one physical index. The Search Module builds a version of the index per definition change, and one of those versions is the index's active version. A query resolves the name to the active version, so which physical index answers a search can change without your code changing.
138
139 That's what makes a schema change zero-downtime. When a definition changes, the module builds a new version alongside the active one, fills it, then makes the new version active. Reads keep hitting the old version throughout and never see a half-built one. A version that fails to fill never goes live, so the active version keeps answering queries. The next on-demand rebuild removes that failed version once it creates the version it builds.
140
141 Once a swap makes a new version active, the module removes every older version except the one the swap replaced. Other processes can keep reading from the replaced version until they pick up the new active version, so the module only removes it at the start of the next migration or rebuild.
142
143 ```mermaid
144 flowchart TD
145 S["query.search()"]
146 S -->|"resolves the active version"| V2
147
148 subgraph phys["Physical indexes"]
149 direction LR
150 V1["v1<br/>removed"]
151 V2["v2<br/>active"]
152 V3["v3<br/>pending"]
153 end
154
155 D["Definition change"] --> V3
156 V3 -. "becomes the active version<br/>once it's filled" .-> V2
157 ```
158
159 A version is also what lets an index move between providers. Setting a different `provider` on a definition makes the module build the new version on that provider, and the old provider's data only gets dropped once the new version is active.
160
161 <Note title="Warning" type="warning">
162
163 The module only fills a new version in worker or shared mode. An application running in server mode never seeds, so the new version stays inactive until a worker or shared process runs, or until you rebuild the index [on demand](#seeding-on-demand).
164
165 </Note>
166
167 ---
168
169 ## Seeding at Application Start
170
171 When your application starts in worker or shared mode, the Search Module checks every index and fills the ones that need data. An application running in server mode skips this entirely, so at least one worker or shared process has to run for an index to be filled.
172
173 The module runs an index definition's [seed](../index-definitions/page.mdx#fill-the-index-with-seed) function in the following cases:
174
175 1. A migration created the index and nothing has filled it yet.
176 2. The index exists and holds no documents, such as after an engine restart wiped it.
177 3. A migration built a new version of the index, which the module fills and then makes active.
178 4. The previous seed didn't complete, so the module resumes it.
179 5. You rebuild the index on demand with the Search Module's `reindex` method. Refer to [Seeding on Demand](#seeding-on-demand).
180 6. The module runs the catch-up pass that follows a full run, which picks up what changed while that run was writing. Refer to [The Catch-Up Pass](#the-catch-up-pass).
181
182 The first four cases run when your application starts. The module records every seed run, so an interrupted run passes its `last_key` back to the `seed` function and resumes where it stopped.
183
184 ---
185
186 ## Seeding on Demand
187
188 You can rebuild an index manually from the [Medusa Admin dashboard](!user-guide!/settings/search), or programmatically with the `reindex` method of the Search Module's service.
189
190 For example, the following workflow step rebuilds only the published products in the `product` index:
191
192 export const highlights = [
193 ["15", "index", "The indexes to rebuild. Defaults to every index."],
194 ["16", "filters", "Passed to the definition's `seed` function."],
195 ]
196
197 ```ts title="src/workflows/steps/reindex-products.ts" highlights={highlights}
198 import { Modules } from "@medusajs/framework/utils"
199 import {
200 createStep,
201 StepResponse,
202 } from "@medusajs/framework/workflows-sdk"
203
204 export const reindexProductsStep = createStep(
205 "reindex-products",
206 async (_, { container }) => {
207 const searchModuleService = container.resolve(
208 Modules.SEARCH
209 )
210
211 const result = await searchModuleService.reindex({
212 index: "product",
213 filters: { status: "published" },
214 })
215
216 return new StepResponse(result)
217 }
218 )
219 ```
220
221 ### Parameters
222
223 `reindex` accepts the following input:
224
225 <TypeList
226 types={[
227 {
228 name: "index",
229 type: "`string` \\| `string[]`",
230 optional: true,
231 defaultValue: "Every registered index",
232 description: "The name of an index, or an array of names, to rebuild."
233 },
234 {
235 name: "strategy",
236 type: "`\"swap\"` \\| `\"in_place\"`",
237 optional: true,
238 defaultValue: "swap",
239 description: "How to rebuild the index. Refer to [Reindex Strategies](#reindex-strategies)."
240 },
241 {
242 name: "filters",
243 type: "`Record<string, unknown>`",
244 optional: true,
245 description: "Filters passed to the definition's `seed` function for a partial rebuild."
246 }
247 ]}
248 sectionTitle="Seeding on Demand"
249 />
250
251 ### Returns
252
253 `reindex` returns to an object with the following properties:
254
255 <TypeList
256 types={[
257 {
258 name: "job_id",
259 type: "`string`",
260 optional: false,
261 description: "The ID of the job that performed the reindex."
262 },
263 {
264 name: "indexes",
265 type: "`string[]`",
266 optional: false,
267 description: "The names of the indexes that the method rebuilt."
268 }
269 ]}
270 sectionTitle="Returns"
271 />
272
273 The method rebuilds every index before it returns this objectg, so you don't poll the `job_id` to know when it finished.
274
275 ### Reindex Strategies
276
277 You can specify how the module rebuilds an index with the `strategy` option. The two strategies are:
278
279 <Table>
280 <Table.Header>
281 <Table.Row>
282 <Table.HeaderCell>
283 Strategy
284 </Table.HeaderCell>
285 <Table.HeaderCell>
286 Description
287 </Table.HeaderCell>
288 </Table.Row>
289 </Table.Header>
290 <Table.Body>
291 <Table.Row>
292 <Table.Cell>
293 `swap` (default)
294 </Table.Cell>
295 <Table.Cell>
296 Fills a new version of the index, then makes it the active one. The version already serving reads keeps doing so throughout.
297 </Table.Cell>
298 </Table.Row>
299 <Table.Row>
300 <Table.Cell>
301 `in_place`
302 </Table.Cell>
303 <Table.Cell>
304 Writes into the version already serving reads, rather than building a new one. Cheaper, but the index serves partial data while the seed runs.
305 </Table.Cell>
306 </Table.Row>
307 </Table.Body>
308 </Table>
309
310 <Note title="Tip">
311
312 Passing `filters` to `reindex` always rebuilds in place, even if you set `strategy` to `swap`. A partial rebuild would only hold the filtered slice, so making it the active version would drop every other document.
313
314 </Note>
315
316 ---
317
318 ## The Catch-Up Pass
319
320 A full seed run reads your data while your application keeps writing to it, so a record that changes mid-run might land in the index stale, or not at all.
321
322 To close that gap, the module runs `seed` a second time as soon as the run finishes, passing it `catchup.since`, which is the time the run started. A swap only makes the new index active once this pass finishes.
323
324 The following diagram shows a full seed run and the catch-up pass that follows it:
325
326 ```mermaid
327 sequenceDiagram
328 participant DB as Your data
329 participant M as Search Module
330 participant IDX as New index version
331
332 Note over M: Full seed run starts at t0
333 M->>DB: Read records
334 DB-->>M: Records
335 M->>IDX: Write documents
336 Note over DB: A record changes<br/>while the run is writing
337 Note over M: Full seed run finishes
338 M->>DB: Read records updated since t0
339 DB-->>M: The changed record
340 M->>IDX: Write the catch-up documents
341 M->>IDX: Make this version active
342 ```
343
344 `graphSeed` handles the pass for you. To handle it in a `seed` function you write yourself, refer to [Handle the Catch-Up Pass](../index-definitions/page.mdx#handle-the-catch-up-pass).
345
346 ---
347
348 ## Keeping Indexes in Sync
349
350 An index holds a copy of your data, so it can fall behind the database. The [`events` and `consume`](../index-definitions/page.mdx#keep-an-index-up-to-date) properties of an index definition close that gap as changes happen, and a reindex repairs it when the gap grows too wide.
351
352 ### Why an Index Diverges
353
354 An index drifts from the database for one of the following reasons:
355
356 <Table>
357 <Table.Header>
358 <Table.Row>
359 <Table.HeaderCell>
360 Reason
361 </Table.HeaderCell>
362 <Table.HeaderCell>
363 Details
364 </Table.HeaderCell>
365 </Table.Row>
366 </Table.Header>
367 <Table.Body>
368 <Table.Row>
369 <Table.Cell>
370 A change emits no declared event
371 </Table.Cell>
372 <Table.Cell>
373 Nothing routes a change whose event name is missing from the definition's `events` array. The same applies to a change that emits no event at all, such as a direct SQL update.
374 </Table.Cell>
375 </Table.Row>
376 <Table.Row>
377 <Table.Cell>
378 `consume` throws
379 </Table.Cell>
380 <Table.Cell>
381 The Event Bus Module logs the failure. The change never lands in the index.
382 </Table.Cell>
383 </Table.Row>
384 <Table.Row>
385 <Table.Cell>
386 A filtered rebuild left documents behind
387 </Table.Cell>
388 <Table.Cell>
389 A rebuild that passes `filters` writes over the documents its seed produces and keeps the rest, since it never clears the index. Documents outside the filtered slice keep whatever they held. Refer to [Reindex Strategies](#reindex-strategies).
390 </Table.Cell>
391 </Table.Row>
392 </Table.Body>
393 </Table>
394
395 ### Recover with a Reindex
396
397 A reindex is the repair path for a diverged index, since it rebuilds documents from the definition's `seed` function rather than from an event. Refer to [Seeding on Demand](#seeding-on-demand) for how to call it.
398
399 Two details matter when you reindex to recover:
400
401 - Pass `filters` to rebuild only the affected slice. A filtered run costs less than a full rebuild, and it always writes in place, so the documents outside the slice keep serving reads.
402 - Omit `filters` for a full repair. Both strategies then rebuild every document from the seed, and either one drops what the seed no longer produces. Keep the default `swap` if the index must keep answering queries while it rebuilds.
403
404 <Note title="Tip">
405
406 Query the `search_index_sync` entity to find out whether a run succeeded, how many documents it wrote, and the error it failed with.
407
408 </Note>