1 import { Table, TypeList, Prerequisites } from "docs-ui"
2
3 export const metadata = {
4 title: `Search Index Definitions`,
5 }
6
7 # {metadata.title}
8
9 In this guide, you'll learn how to declare a search index and control what the search engine holds.
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 ## What is a Search Index Definition?
21
22 A search index definition declares one index: the entity it indexes, the fields the search engine holds, and how to fill it. The [Search Module](../page.mdx) owns everything around it, including creating the physical index, batching writes, and rebuilding the index when the definition changes.
23
24 <Note title="Tip">
25
26 The product indexes in this guide's snippets are 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](../product-index-examples/page.mdx).
27
28 </Note>
29
30 Define an index with `defineSearchIndex` in a file under the `src/search` directory of your Medusa application or plugin. Medusa loads every file in that directory before the application boots, and each file registers its indexes on import.
31
32 For example, create the file `src/search/brand.ts` with the following content:
33
34 export const highlights = [
35 ["11", "name", "The unique index name a query resolves against."],
36 ["12", "entity", "The Query entity used to hydrate other fields."],
37 ["13", "fields", "The fields the search engine holds."],
38 ["18", "events", "The events that change the indexed data."],
39 ["23", "consume", "Applies each of those events to the index."],
40 ["24", "seed", "Fills the index with every brand."],
41 ]
42
43 ```ts title="src/search/brand.ts" highlights={highlights}
44 import {
45 defineSearchIndex,
46 graphConsume,
47 graphSeed,
48 search,
49 } from "@medusajs/framework/utils"
50
51 const fields = ["id", "name", "country"]
52
53 export const brandIndex = defineSearchIndex({
54 name: "brand",
55 entity: "brand",
56 fields: search.define({
57 id: search.keyword().filterable(),
58 name: search.text().searchable(),
59 country: search.keyword().filterable(),
60 }),
61 events: [
62 "brand.created",
63 "brand.updated",
64 "brand.deleted",
65 ],
66 consume: graphConsume({ fields }),
67 seed: graphSeed({ fields }),
68 })
69 ```
70
71 `graphSeed` and `graphConsume` are helpers that build the index's data from [Query](!docs!/learn/fundamentals/query):
72
73 - [`graphSeed`](#fill-the-index-from-query-with-graphseed) reads the entity's records to fill the index for the first time.
74 - [`graphConsume`](#consume-events-from-query-with-graphconsume) reads the records that an event changed to keep the index current.
75
76 Most indexes are a projection of an entity that Query already exposes, so the helpers cover them. Refer to [Custom `seed` and `consume` Implementation](#custom-seed-and-consume-implementation) for an index whose data doesn't come from Query.
77
78 If you're using the [PostgreSQL Search Module Provider](../providers/postgres/page.mdx) or a provider that makes changes to the database, you must also run the migrations that create the necessary tables:
79
80 ```bash npx2yarn
81 npx medusa db:migrate
82 ```
83
84 ---
85
86 ## Index Definition Properties
87
88 <Table>
89 <Table.Header>
90 <Table.Row>
91 <Table.HeaderCell>
92 Property
93 </Table.HeaderCell>
94 <Table.HeaderCell>
95 Description
96 </Table.HeaderCell>
97 <Table.HeaderCell>
98 Required
99 </Table.HeaderCell>
100 </Table.Row>
101 </Table.Header>
102 <Table.Body>
103 <Table.Row>
104 <Table.Cell>
105 `name`
106 </Table.Cell>
107 <Table.Cell>
108 A unique name for the index. This is the value for `entity` passed to `query.search`.
109 </Table.Cell>
110 <Table.Cell>
111 Yes
112 </Table.Cell>
113 </Table.Row>
114 <Table.Row>
115 <Table.Cell>
116 `entity`
117 </Table.Cell>
118 <Table.Cell>
119 The [Query](!docs!/learn/fundamentals/query) entry point used to hydrate the fields that the search index doesn't hold.
120 </Table.Cell>
121 <Table.Cell>
122 Yes
123 </Table.Cell>
124 </Table.Row>
125 <Table.Row>
126 <Table.Cell>
127 `fields`
128 </Table.Cell>
129 <Table.Cell>
130 The fields the search engine holds. Must be a schema built with `search.define`. Refer to [Search Index Fields](./fields/page.mdx) for every field type and modifier.
131 </Table.Cell>
132 <Table.Cell>
133 Yes
134 </Table.Cell>
135 </Table.Row>
136 <Table.Row>
137 <Table.Cell>
138 `seed`
139 </Table.Cell>
140 <Table.Cell>
141 An async generator that yields batches of writes, usually built with [`graphSeed`](#fill-the-index-from-query-with-graphseed). Refer to [Fill the Index with `seed`](#fill-the-index-with-seed) for when the Search Module runs it.
142 </Table.Cell>
143 <Table.Cell>
144 Yes
145 </Table.Cell>
146 </Table.Row>
147 <Table.Row>
148 <Table.Cell>
149 `events`
150 </Table.Cell>
151 <Table.Cell>
152 The workflow events that change the data this index holds. Medusa subscribes to them and routes each one to `consume`. Refer to [Keep an Index Up-to-Date](#keep-an-index-up-to-date) for details.
153 </Table.Cell>
154 <Table.Cell>
155 No
156 </Table.Cell>
157 </Table.Row>
158 <Table.Row>
159 <Table.Cell>
160 `consume`
161 </Table.Cell>
162 <Table.Cell>
163 A function that turns an event into document writes, usually built with [`graphConsume`](#consume-events-from-query-with-graphconsume). Required when you set `events`. Refer to [Keep an Index Up-to-Date](#keep-an-index-up-to-date) for details.
164 </Table.Cell>
165 <Table.Cell>
166 No
167 </Table.Cell>
168 </Table.Row>
169 <Table.Row>
170 <Table.Cell>
171 `primary_key`
172 </Table.Cell>
173 <Table.Cell>
174 The field holding each document's unique identifier. Defaults to `id`. Declare it in `fields` too, otherwise the module rejects the definition at startup.
175 </Table.Cell>
176 <Table.Cell>
177 No
178 </Table.Cell>
179 </Table.Row>
180 <Table.Row>
181 <Table.Cell>
182 `provider`
183 </Table.Cell>
184 <Table.Cell>
185 The identifier of the [Search Module Provider](../providers/page.mdx) that holds this index, such as `search-postgres`. Defaults to the module's [default provider](../providers/page.mdx#default-search-module-provider).
186 </Table.Cell>
187 <Table.Cell>
188 No
189 </Table.Cell>
190 </Table.Row>
191 <Table.Row>
192 <Table.Cell>
193 `settings`
194 </Table.Cell>
195 <Table.Cell>
196 Engine settings for this index, such as the field to deduplicate results on. Only the [Medusa Search](!cloud!/search) provider supports them. Refer to [Index Settings](!cloud!/search/settings#index-settings) for the settings it accepts.
197 </Table.Cell>
198 <Table.Cell>
199 No
200 </Table.Cell>
201 </Table.Row>
202 </Table.Body>
203 </Table>
204
205 <Note>
206
207 Changing `fields` or `settings` changes the definition's hash, which the Search Module treats as a schema change. Refer to the [Reindexing and Migrations guide](../reindexing/page.mdx) to learn how it rebuilds the index.
208
209 </Note>
210
211 ---
212
213 ## Fill the Index with `seed`
214
215 `seed` fills the index with documents. Every index definition must set it.
216
217 The Search Module decides when to run `seed`, such as when a migration creates the index, when you rebuild it on demand, or when it runs the [catch-up pass](#catch-up-on-changes-during-a-run). Refer to [Seeding at Application Start](../reindexing/page.mdx#seeding-at-application-start) for every case that triggers it and how the module plans each one.
218
219 ### Fill the Index from Query with `graphSeed`
220
221 Build `seed` with the `graphSeed` helper when the index holds an entity that [Query](!docs!/learn/fundamentals/query) exposes, which is the case for most indexes.
222
223 For example:
224
225 ```ts title="src/search/brand.ts"
226 import {
227 defineSearchIndex,
228 graphSeed,
229 search,
230 } from "@medusajs/framework/utils"
231
232 export const brandIndex = defineSearchIndex({
233 name: "brand",
234 entity: "brand",
235 fields: search.define({
236 id: search.keyword().filterable(),
237 name: search.text().searchable(),
238 }),
239 seed: graphSeed({ fields: ["id", "name"] }),
240 })
241 ```
242
243 `graphSeed` reads the entity through `query.graph` and writes every row it reads to the index. It also does the following for you:
244
245 - Pages the read, so a large catalog never loads into memory at once.
246 - Resumes an interrupted run from the record it stopped at, rather than restarting it.
247 - Handles the [catch-up pass](#catch-up-on-changes-during-a-run), including deleting the documents of records that were removed while the run was writing.
248
249 #### Index Part of an Entity
250
251 `transform` receives a page of records and returns the documents to index. To index a subset of an entity's records, leave the records the index must not hold out of the array you return, rather than narrowing the read with a filter.
252
253 For example, to index published products only:
254
255 ```ts title="src/search/product.ts"
256 export const productIndex = defineSearchIndex({
257 // ...
258 seed: graphSeed({
259 fields: ["id", "title", "status"],
260 transform: (products) => {
261 return products.filter(
262 (product) => product.status === "published"
263 )
264 },
265 }),
266 })
267 ```
268
269 `graphSeed` deletes the document of a record you leave out on the catch-up pass, so a product that stops qualifying leaves the index instead of going stale in it. A filtered read can't do that, since it never sees the record again.
270
271 <Note title="Important">
272
273 Every document you return must carry the record's primary key value as its `id`, since that's how `graphSeed` matches a document back to the record it came from. The helper throws if a document has no `id`.
274
275 </Note>
276
277 Use `transform` too when the document differs from the record, such as when you flatten a relation into an array of IDs.
278
279 For example, `query.graph` returns a product's categories as an array of objects, whereas the index holds their IDs in a `category_ids` field:
280
281 ```ts title="src/search/product.ts"
282 export const productIndex = defineSearchIndex({
283 // ...
284 fields: search.define({
285 id: search.keyword().filterable(),
286 title: search.text().searchable(),
287 category_ids: search.keyword().filterable(),
288 }),
289 seed: graphSeed({
290 fields: ["id", "title", "categories.id"],
291 transform: (products) => products.map((product) => ({
292 id: product.id,
293 title: product.title,
294 category_ids: product.categories.map(
295 (category) => category.id
296 ),
297 })),
298 }),
299 })
300 ```
301
302 #### Read More Data in transform
303
304 `transform` is asynchronous and receives a whole page of records at a time, so a document that needs data beyond what one `query.graph` call returns costs a fixed number of extra queries per page, rather than one per record.
305
306 For example, to index a French title alongside the English one, read the page again with the `locale` option:
307
308 export const transformAsyncHighlights = [
309 ["11", "async", "The function can await other reads."],
310 ["12", "container", "Resolve Query from the context's container."],
311 ["15", "query.graph", "One extra read for the whole page."],
312 ]
313
314 ```ts title="src/search/product.ts" highlights={transformAsyncHighlights}
315 export const productIndex = defineSearchIndex({
316 name: "product",
317 entity: "product",
318 fields: search.define({
319 id: search.keyword().filterable(),
320 title_en: search.text().searchable(),
321 title_fr: search.text().searchable(),
322 }),
323 seed: graphSeed({
324 fields: ["id", "title"],
325 transform: async (products, { container }) => {
326 const { query } = container
327 const ids = products.map((product) => product.id)
328
329 const { data: translated } = await query.graph({
330 entity: "product",
331 fields: ["id", "title"],
332 filters: { id: ids },
333 }, { locale: "fr-FR" })
334
335 const frTitles = new Map(
336 translated.map((product) => [
337 product.id,
338 product.title,
339 ])
340 )
341
342 return products.map((product) => ({
343 id: product.id,
344 title_en: product.title,
345 title_fr:
346 frTitles.get(product.id) ?? product.title,
347 }))
348 },
349 }),
350 })
351 ```
352
353 #### Pass a Query Context
354
355 Some fields only resolve when `query.graph` receives a [query context](!docs!/learn/fundamentals/query/query-context), such as `variants.calculated_price`, which needs a currency or a region to calculate a price for. Pass that context to `graphSeed` with the `context` option:
356
357 ```ts title="src/search/product.ts"
358 import { QueryContext } from "@medusajs/framework/utils"
359
360 export const productIndex = defineSearchIndex({
361 name: "product",
362 entity: "product",
363 fields: search.define({
364 // ...
365 }),
366 seed: graphSeed({
367 fields: [
368 "id",
369 "title",
370 "variants.calculated_price.*",
371 ],
372 context: {
373 variants: {
374 calculated_price: QueryContext({
375 currency_code: "usd",
376 }),
377 },
378 },
379 }),
380 })
381 ```
382
383 `graphSeed` applies the context to the full run and to the [catch-up pass](#catch-up-on-changes-during-a-run) alike. `graphConsume` accepts the same option, so pass it to both helpers to write the same document from an event.
384
385 You can also pass a function, which receives the same context `seed` receives. Use it when the query context depends on the index being filled:
386
387 ```ts title="src/search/product.ts"
388 export const productIndex = defineSearchIndex({
389 // ...
390 seed: graphSeed({
391 // ...
392 context: ({ index }) => ({
393 variants: {
394 calculated_price: QueryContext({
395 currency_code: index.name.endsWith("_eur")
396 ? "eur"
397 : "usd",
398 }),
399 },
400 }),
401 }),
402 })
403 ```
404
405 #### graphSeed Options
406
407 <TypeList
408 types={[
409 {
410 name: "fields",
411 type: "`string[]`",
412 optional: false,
413 description: "The fields to select from `query.graph`. The helper adds the index's `primary_key`, and `deleted_at` on the catch-up pass."
414 },
415 {
416 name: "entity",
417 type: "`string`",
418 optional: true,
419 description: "The `query.graph` entry point to read from.",
420 defaultValue: "The index definition's `entity`"
421 },
422 {
423 name: "transform",
424 type: "`function`",
425 optional: true,
426 description: "Maps a page of records to the documents to index. Receives the records and the same context `seed` receives, and can be asynchronous. Every document must carry the record's primary key value as its `id`. Leave a record out of the returned array to keep it out of the index.",
427 defaultValue: "Indexes the records as-is"
428 },
429 {
430 name: "context",
431 type: "`object` \\| `function`",
432 optional: true,
433 description: "The [query context](!docs!/learn/fundamentals/query/query-context) that `query.graph` reads the records with, such as the pricing context that `variants.calculated_price` needs. Pass a function to build it from the context `seed` receives. Applied to the full run, the catch-up pass, and `consume` alike."
434 },
435 {
436 name: "batch_size",
437 type: "`number`",
438 optional: true,
439 description: "The number of records to read from `query.graph` per page.",
440 defaultValue: "200"
441 }
442 ]}
443 sectionTitle="graphSeed Options"
444 />
445
446 ### Catch Up on Changes During a Run
447
448 A full seed or rebuild reads your data while your application keeps writing to it, so a record that changes mid-run can land in the index stale, or not at all. To close that gap, the Search Module runs `seed` a second time as soon as the run finishes, passing `catchup.since`, which is the time the run started.
449
450 The pass must read the records updated at or after `catchup.since`, including the ones that were deleted, then write the changes to the index. `graphSeed` does all of that, so an index using it needs nothing else. Refer to [Handle the Catch-Up Pass](#handle-the-catch-up-pass) to handle it in a `seed` you write yourself.
451
452 The module skips the pass for a [partial rebuild](../reindexing/page.mdx#seeding-on-demand), since a filtered run is already scoped to what the caller asked for.
453
454 ---
455
456 ## Keep an Index Up-to-Date
457
458 If you omit `events` and `consume`, the Search Module only fills an index in the [cases listed for `seed`](#fill-the-index-with-seed). So the index holds whatever the last run produced until something triggers another one.
459
460 <Note>
461
462 A restart doesn't refill an index that already has documents. The module only seeds an index that holds no documents, or one whose previous seed didn't finish.
463
464 </Note>
465
466 To ensure your index is always up-to-date, add the following to your index definition:
467
468 - `events`: an array of workflow event names that change the data the index holds. Medusa subscribes to them and calls `consume` for each one.
469 - See the [Events Reference](/references/events) for the full list of events Medusa emits and their payloads. You can also use custom events that you emit.
470 - `consume`: a function that turns an event into document writes.
471
472 ### Consume Events from Query with `graphConsume`
473
474 Build `consume` with the `graphConsume` helper when the index holds an entity that [Query](!docs!/learn/fundamentals/query) exposes, the same way [`graphSeed`](#fill-the-index-from-query-with-graphseed) builds `seed`.
475
476 For example:
477
478 ```ts title="src/search/brand.ts"
479 import {
480 defineSearchIndex,
481 graphConsume,
482 graphSeed,
483 search,
484 } from "@medusajs/framework/utils"
485
486 const fields = ["id", "name"]
487
488 export const brandIndex = defineSearchIndex({
489 // ...
490 events: [
491 "brand.created",
492 "brand.updated",
493 "brand.deleted",
494 ],
495 consume: graphConsume({ fields }),
496 seed: graphSeed({ fields }),
497 })
498 ```
499
500 `graphConsume` reads the records the event affects through `query.graph` and writes them to the index.
501
502 It deletes a record's document instead when the event's name ends in `.deleted`, when the read doesn't return the record, or when a `transform` leaves it out of the documents it returns.
503
504 #### Share the Options with `graphSeed`
505
506 Pass the same options to both helpers so a document written by an event matches the one the seed writes. Declare them once and reuse them, rather than repeating the `fields` and `transform` in each call.
507
508 For example, this is the [published-products index](#index-part-of-an-entity) with its events applied to it:
509
510 ```ts title="src/search/product.ts"
511 const source = {
512 fields: ["id", "title", "status"],
513 transform: (products) => {
514 return products.filter(
515 (product) => product.status === "published"
516 )
517 },
518 }
519
520 export const productIndex = defineSearchIndex({
521 // ...
522 events: [
523 "product.created",
524 "product.updated",
525 "product.deleted",
526 ],
527 consume: graphConsume(source),
528 seed: graphSeed(source),
529 })
530 ```
531
532 `graphConsume` deletes the document of a product the `transform` leaves out, so unpublishing a product removes it from the index as soon as its `product.updated` event arrives, rather than waiting for the next seed.
533
534 The same holds for a `transform` that reshapes the record. For example, this is the [category IDs index](#index-part-of-an-entity) kept current by its events:
535
536 ```ts title="src/search/product.ts"
537 const source = {
538 fields: ["id", "title", "categories.id"],
539 transform: (products) => products.map((product) => ({
540 id: product.id,
541 title: product.title,
542 category_ids: product.categories.map(
543 (category) => category.id
544 ),
545 })),
546 }
547
548 export const productIndex = defineSearchIndex({
549 // ...
550 events: [
551 "product.created",
552 "product.updated",
553 "product.deleted",
554 ],
555 consume: graphConsume(source),
556 seed: graphSeed(source),
557 })
558 ```
559
560 #### graphConsume Options
561
562 <TypeList
563 types={[
564 {
565 name: "fields",
566 type: "`string[]`",
567 optional: false,
568 description: "The fields to select from `query.graph`. The helper adds the index's `primary_key`."
569 },
570 {
571 name: "entity",
572 type: "`string`",
573 optional: true,
574 description: "The `query.graph` entry point to read from.",
575 defaultValue: "The index definition's `entity`"
576 },
577 {
578 name: "transform",
579 type: "`function`",
580 optional: true,
581 description: "Maps a page of records to the documents to index. Receives the records and the same context `consume` receives, and can be asynchronous. Every document must carry the record's primary key value as its `id`. Leave a record out of the returned array to delete its document instead.",
582 defaultValue: "Indexes the records as-is"
583 },
584 {
585 name: "context",
586 type: "`object` \\| `function`",
587 optional: true,
588 description: "The [query context](!docs!/learn/fundamentals/query/query-context) that `query.graph` reads the records with, such as the pricing context that `variants.calculated_price` needs. Pass a function to build it from the context `consume` receives."
589 },
590 {
591 name: "resolve_ids",
592 type: "`function`",
593 optional: true,
594 description: "Returns the IDs of the documents the event affects, as a string or an array of strings. Set it for an event whose payload names the affected documents under another property, such as a variant event that carries its product's ID.",
595 defaultValue: "Reads `event.data.id`"
596 },
597 {
598 name: "is_delete",
599 type: "`function`",
600 optional: true,
601 description: "Returns whether the event removes its documents from the index rather than updating them. The helper deletes them by ID without reading them back.",
602 defaultValue: "An event whose name ends in `.deleted`"
603 }
604 ]}
605 sectionTitle="graphConsume Options"
606 />
607
608 <Note title="Tip">
609
610 `graphSeed` and `graphConsume` can also select fields from a linked module, such as a product's brand. Refer to the [Index Data from a Linked Module guide](./linked-data/page.mdx) to learn how.
611
612 </Note>
613
614 ---
615
616 ## Custom `seed` and `consume`
617
618 Write `seed` and `consume` yourself when the index doesn't map to a single Query read, such as when its documents come from an external service, or when building a document takes more than reading the entity's fields.
619
620 Both return the same writes, which are one of the following:
621
622 - `{ action: "upsert", documents }`: writes the documents into the index, replacing any document already stored under the same ID.
623 - `{ action: "delete", filters }`: removes every document matching the filters.
624
625 The examples in this section index an `article` entity whose content lives in a headless CMS rather than in your Medusa application, so they call a `cms` client instead of Query.
626
627 <Note title="Warning" type="warning">
628
629 The `container` that `seed` and `consume` receive isn't the Medusa container. It only exposes `query`, to read data with Query, and `logger`, to report what an ingestion run is doing. You can't resolve a module or another registration from it, so import the client you need into the file instead, as the examples do.
630
631 </Note>
632
633 ### Custom `seed` Implementation
634
635 `seed` is an async generator, so `yield` a batch of writes as you build it. The Search Module writes each batch to the engine as it arrives, rather than holding the entire index in memory.
636
637 For example:
638
639 export const customSeedHighlights = [
640 ["15", "listArticles", "Reads one page of articles from the CMS."],
641 ["24", "yield", "Writes the page before reading the next one."],
642 ]
643
644 ```ts title="src/search/article.ts" highlights={customSeedHighlights}
645 import { cms } from "../lib/cms"
646
647 export const articleIndex = defineSearchIndex({
648 name: "article",
649 entity: "article",
650 fields: search.define({
651 id: search.keyword().filterable(),
652 title: search.text().searchable(),
653 body: search.text().searchable(),
654 }),
655 async *seed() {
656 let page = 1
657
658 while (true) {
659 const articles = await cms.listArticles({
660 page,
661 limit: 200,
662 })
663
664 if (!articles.length) {
665 break
666 }
667
668 yield [{
669 action: "upsert",
670 documents: articles,
671 }]
672
673 page++
674 }
675 },
676 })
677 ```
678
679 #### Log an Ingestion Run
680
681 A full run can take a while, so use the `logger` of the `container` to report what it's doing. Its messages show in your application's logs alongside the messages that the Search Module logs itself.
682
683 ```ts title="src/search/article.ts"
684 export const articleIndex = defineSearchIndex({
685 // ...
686 async *seed({ container, index }) {
687 const { logger } = container
688
689 // ...
690
691 logger.info(
692 `Seeding ${index.name} with ` +
693 `${articles.length} articles`
694 )
695 },
696 })
697 ```
698
699 `seed` receives an object parameter with the following properties:
700
701 <TypeList
702 types={[
703 {
704 name: "container",
705 type: "`object`",
706 optional: false,
707 description: "A limited Medusa container exposing `query`, so you can read data with [Query](!docs!/learn/fundamentals/query), and `logger`, so you can log what the run is doing."
708 },
709 {
710 name: "index",
711 type: "`object`",
712 optional: false,
713 description: "The definition of the index being filled, as you passed it to `defineSearchIndex`. Refer to [Index Definition Properties](#index-definition-properties) for more details on each property.",
714 children: [
715 {
716 name: "name",
717 type: "`string`",
718 optional: false,
719 description: "The index's unique name, which is the `entity` that `query.search` resolves against."
720 },
721 {
722 name: "entity",
723 type: "`string`",
724 optional: false,
725 description: "The [Query](!docs!/learn/fundamentals/query) entry point that hydrates the fields the index doesn't hold."
726 },
727 {
728 name: "fields",
729 type: "`Record<string, object>`",
730 optional: false,
731 description: "The fields the index holds, keyed by their path in the document. Read them to build the documents you yield, rather than hard-coding the field list twice. Refer to [Search Index Fields](./fields/page.mdx) for a field definition's shape."
732 },
733 {
734 name: "seed",
735 type: "`function`",
736 optional: false,
737 description: "The generator function that yields the index's writes, which is the function receiving this context."
738 },
739 {
740 name: "primary_key",
741 type: "`string`",
742 optional: true,
743 description: "The field holding each document's unique identifier. The Search Module reads it from every document you yield to track the run's `last_key`.",
744 defaultValue: "id"
745 },
746 {
747 name: "provider",
748 type: "`string`",
749 optional: true,
750 description: "The identifier of the [Search Module Provider](../providers/page.mdx) holding this index, such as `search-postgres`.",
751 defaultValue: "The module's default provider"
752 },
753 {
754 name: "settings",
755 type: "`object`",
756 optional: true,
757 description: "The engine settings applied to this index. Refer to [Index Settings](!cloud!/search/settings#index-settings) for the settings [Medusa Search](!cloud!/search) accepts."
758 },
759 {
760 name: "events",
761 type: "`string[]`",
762 optional: true,
763 description: "The workflow events that change the data this index holds."
764 },
765 {
766 name: "consume",
767 type: "`function`",
768 optional: true,
769 description: "The function that turns one of those events into document writes. Refer to [Keep an Index Up-to-Date](#keep-an-index-up-to-date)."
770 }
771 ]
772 },
773 {
774 name: "filters",
775 type: "`Record<string, unknown>`",
776 optional: true,
777 description: "The filters passed to a partial reindex. Apply them to index a subset of the entity."
778 },
779 {
780 name: "last_key",
781 type: "`string`",
782 optional: true,
783 description: "The cursor of an interrupted run, so you can resume where it stopped."
784 },
785 {
786 name: "catchup",
787 type: "`object`",
788 optional: true,
789 description: "Set only for the catch-up pass that follows a full run. Scope your query to what changed since `catchup.since` and yield a `delete` write for anything that's gone. Refer to [Handle the Catch-Up Pass](#handle-the-catch-up-pass).",
790 expandable: false,
791 children: [
792 {
793 name: "since",
794 type: "`Date`",
795 optional: false,
796 description: "The time the run before this pass started. Only records changed at or after it matter to the pass."
797 }
798 ]
799 }
800 ]}
801 sectionTitle="Custom `seed` Implementation"
802 />
803
804 #### Handle the Catch-Up Pass
805
806 A `seed` you write yourself also runs as the [catch-up pass](#catch-up-on-changes-during-a-run) that follows a full run. Handle it by doing the following:
807
808 1. Narrow your read to records changed at or after `catchup.since`, so the pass stays small.
809 2. Include the records that were deleted, since a record removed mid-run is a document the index must lose.
810 3. Yield an `upsert` write for a record that still exists, and a `delete` write for one that's gone.
811
812 For example:
813
814 ```ts title="src/search/article.ts"
815 export const articleIndex = defineSearchIndex({
816 // ...
817 async *seed({ catchup }) {
818 const articles = await cms.listArticles({
819 changed_since: catchup?.since,
820 include_deleted: !!catchup,
821 })
822
823 const live = articles.filter((a) => !a.deleted)
824 const gone = articles.filter((a) => a.deleted)
825
826 yield [
827 ...(live.length
828 ? [{ action: "upsert", documents: live }]
829 : []),
830 ...gone.map((article) => ({
831 action: "delete",
832 filters: { id: [article.id] },
833 })),
834 ]
835 },
836 })
837 ```
838
839 ### Custom `consume` Implementation
840
841 `consume` turns one event into the writes that apply it to the index. It returns them in an array rather than yielding them, since an event changes specific documents.
842
843 It returns the same writes [`seed`](#custom-seed-implementation) yields:
844
845 - `{ action: "upsert", documents }`: writes the documents into the index, replacing any document already stored under the same ID.
846 - `{ action: "delete", filters }`: removes every document matching the filters.
847
848 Return an empty array for an event that changes nothing the index holds.
849
850 For example:
851
852 ```ts title="src/search/article.ts"
853 export const articleIndex = defineSearchIndex({
854 // ...
855 events: [
856 "article.published",
857 "article.unpublished",
858 ],
859 async consume(event) {
860 if (event.name === "article.unpublished") {
861 return [{
862 action: "delete",
863 filters: { id: [event.data.id] },
864 }]
865 }
866
867 const article = await cms.retrieveArticle(
868 event.data.id
869 )
870
871 return [{
872 action: "upsert",
873 documents: [article],
874 }]
875 },
876 })
877 ```
878
879 `consume` receives two parameters:
880
881 <TypeList
882 types={[
883 {
884 name: "event",
885 type: "`object`",
886 optional: false,
887 description: "The event that triggered the call.",
888 expandable: false,
889 children: [
890 {
891 name: "name",
892 type: "`string`",
893 optional: false,
894 description: "The name of the event, which is one of the names you listed in `events`."
895 },
896 {
897 name: "data",
898 type: "`object`",
899 optional: false,
900 description: "The event's payload. Refer to the [Events Reference](/references/events) for the payload of each event Medusa emits."
901 }
902 ]
903 },
904 {
905 name: "context",
906 type: "`object`",
907 optional: false,
908 description: "The context the Search Module runs the function in.",
909 expandable: false,
910 children: [
911 {
912 name: "container",
913 type: "`object`",
914 optional: false,
915 description: "A limited Medusa container exposing `query`, so you can read data with [Query](!docs!/learn/fundamentals/query), and `logger`, so you can log what the run is doing."
916 },
917 {
918 name: "index",
919 type: "`object`",
920 optional: false,
921 description: "The index definition the event is applied to."
922 }
923 ]
924 }
925 ]}
926 sectionTitle="Custom `consume` Implementation"
927 />
928
929 <Note>
930
931 `context` holds `container` and `index` only. Unlike [`seed`](#custom-seed-implementation), it carries no `filters`, `last_key`, or `catchup`, since an event changes specific documents rather than filling the whole index.
932
933 </Note>
934
935 ---
936
937 ## Point an Index at a Specific Provider
938
939 If you're using multiple [Search Module Providers](../providers/page.mdx), set the `provider` property to the ID of a registered provider.
940
941 For example, you can keep a high-traffic index on a dedicated engine while quieter indexes stay on PostgreSQL.
942
943 ```ts title="src/search/product.ts"
944 export const productIndex = defineSearchIndex({
945 name: "product",
946 entity: "product",
947 provider: "search-postgres",
948 // ...
949 })
950 ```
951
952 When you omit it, the index uses the module's `default_provider`.