|
1
|
import { Prerequisites } from "docs-ui" |
|
2
|
|
|
3
|
export const metadata = { |
|
4
|
title: `Product Search Index Examples`, |
|
5
|
} |
|
6
|
|
|
7
|
# {metadata.title} |
|
8
|
|
|
9
|
In this guide, you'll find examples of indexing product data that a storefront's search and browsing experience needs, such as prices in multiple currencies, option values, and categories. |
|
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
|
## Simple Product Index |
|
21
|
|
|
22
|
The following index definition holds a product's basic details, and it's the starting point that the rest of this guide's sections extend. |
|
23
|
|
|
24
|
Create the file `src/search/product.ts` with the following content: |
|
25
|
|
|
26
|
export const simpleHighlights = [ |
|
27
|
["20", "name", "The index name that a search query resolves against."], |
|
28
|
["21", "entity", "The Query entity used to hydrate non-indexed fields."], |
|
29
|
["24", "status", "Lets the Store Search API route scope the index to published products."], |
|
30
|
["38", "events", "The events that change the data the index holds."], |
|
31
|
["43", "consume", "Turn each of those events into document writes."], |
|
32
|
["44", "seed", "Fill the index with every product."], |
|
33
|
] |
|
34
|
|
|
35
|
```ts title="src/search/product.ts" highlights={simpleHighlights} |
|
36
|
import { |
|
37
|
defineSearchIndex, |
|
38
|
graphConsume, |
|
39
|
graphSeed, |
|
40
|
search, |
|
41
|
} from "@medusajs/framework/utils" |
|
42
|
|
|
43
|
const source = { |
|
44
|
fields: [ |
|
45
|
"id", |
|
46
|
"title", |
|
47
|
"description", |
|
48
|
"handle", |
|
49
|
"thumbnail", |
|
50
|
"status", |
|
51
|
], |
|
52
|
} |
|
53
|
|
|
54
|
export default defineSearchIndex({ |
|
55
|
name: "product", |
|
56
|
entity: "product", |
|
57
|
fields: search.define({ |
|
58
|
id: search.keyword().filterable().retrievable(), |
|
59
|
status: search |
|
60
|
.keyword() |
|
61
|
.filterable() |
|
62
|
.retrievable(false), |
|
63
|
title: search |
|
64
|
.text() |
|
65
|
.searchable({ weight: 3 }) |
|
66
|
.sortable() |
|
67
|
.retrievable(), |
|
68
|
description: search.text().searchable(), |
|
69
|
handle: search.keyword().retrievable(), |
|
70
|
thumbnail: search.keyword().retrievable(), |
|
71
|
created_at: search.date().sortable().retrievable(), |
|
72
|
}), |
|
73
|
events: [ |
|
74
|
"product.created", |
|
75
|
"product.updated", |
|
76
|
"product.deleted", |
|
77
|
], |
|
78
|
consume: graphConsume(source), |
|
79
|
seed: graphSeed(source), |
|
80
|
}) |
|
81
|
``` |
|
82
|
|
|
83
|
`source` holds the options that [`graphSeed`](../index-definitions/page.mdx#fill-the-index-from-query-with-graphseed) and [`graphConsume`](../index-definitions/page.mdx#consume-events-from-query-with-graphconsume) share, so a document written by an event matches the one the seed writes. |
|
84
|
|
|
85
|
The index holds draft products too, but the [Store Search API route](../store-search/page.mdx) returns published products only, as long as the index declares a `status` field with the [`filterable` modifier](../index-definitions/modifiers/page.mdx#filterable). The field uses [`retrievable(false)`](../index-definitions/modifiers/page.mdx#retrievable), so the route filters on it without returning it in a hit. Unpublishing a product then drops it from the storefront's results as soon as its `product.updated` event arrives. |
|
86
|
|
|
87
|
--- |
|
88
|
|
|
89
|
## Scope the Index to Published Products and Sales Channels |
|
90
|
|
|
91
|
A storefront must never find a draft product, or a product that isn't in the request's sales channel. So, declare a `status` and a `sales_channel_ids` field with the [`filterable` modifier](../index-definitions/modifiers/page.mdx#filterable), and the [Store Search API route](../store-search/page.mdx) narrows every query to the products a storefront may see. |
|
92
|
|
|
93
|
`sales_channel_ids` isn't a field of the product itself, so select the product's `sales_channels.id` and flatten them onto the document in the `transform`: |
|
94
|
|
|
95
|
export const scopeHighlights = [ |
|
96
|
["5", `"sales_channels.id"`, "Selected to fill `sales_channel_ids`."], |
|
97
|
["22", "status", "Read by `/store/search`, never returned in a hit."], |
|
98
|
["26", "sales_channel_ids", "Read by `/store/search`, never returned in a hit."], |
|
99
|
] |
|
100
|
|
|
101
|
```ts title="src/search/product.ts" highlights={scopeHighlights} |
|
102
|
const source = { |
|
103
|
fields: [ |
|
104
|
// ... |
|
105
|
"status", |
|
106
|
"sales_channels.id", |
|
107
|
], |
|
108
|
transform: (products) => { |
|
109
|
return products.map((product) => ({ |
|
110
|
// ... |
|
111
|
status: product.status, |
|
112
|
sales_channel_ids: ( |
|
113
|
product.sales_channels ?? [] |
|
114
|
).map((salesChannel) => salesChannel.id), |
|
115
|
})) |
|
116
|
}, |
|
117
|
} |
|
118
|
|
|
119
|
export default defineSearchIndex({ |
|
120
|
// ... |
|
121
|
fields: search.define({ |
|
122
|
// ... |
|
123
|
status: search |
|
124
|
.keyword() |
|
125
|
.filterable() |
|
126
|
.retrievable(false), |
|
127
|
sales_channel_ids: search |
|
128
|
.keyword() |
|
129
|
.array() |
|
130
|
.filterable() |
|
131
|
.retrievable(false), |
|
132
|
}), |
|
133
|
consume: graphConsume(source), |
|
134
|
seed: graphSeed(source), |
|
135
|
}) |
|
136
|
``` |
|
137
|
|
|
138
|
Both fields use [`retrievable(false)`](../index-definitions/modifiers/page.mdx#retrievable), so the route filters on them without returning them in a hit. |
|
139
|
|
|
140
|
Refer to the [Store Search API Route guide](../store-search/page.mdx#how-medusa-narrows-a-product-index) for the filters that the route applies, and for how to narrow an index further with filters of your own. |
|
141
|
|
|
142
|
--- |
|
143
|
|
|
144
|
## Index Prices for Multiple Currencies |
|
145
|
|
|
146
|
The Pricing Module calculates a price for one currency per query, and a search engine can't calculate a price at query time. So, the index holds a set of price fields per currency, and each currency's fields are filterable, sortable, and facetable on their own. |
|
147
|
|
|
148
|
### 1. Declare the Price Fields |
|
149
|
|
|
150
|
Declare the currencies the index holds prices in, build a set of fields for each of them, then spread the fields into the index: |
|
151
|
|
|
152
|
export const priceFieldHighlights = [ |
|
153
|
["1", "PRICE_CURRENCIES", "The currencies the index holds prices in."], |
|
154
|
["8", "min_price", "The cheapest variant's calculated price."], |
|
155
|
["17", "max_price", "The most expensive variant's calculated price."], |
|
156
|
["26", "original_price", "The price before a promotion applies."], |
|
157
|
["30", "on_sale", "Whether the product has a reduced price."], |
|
158
|
] |
|
159
|
|
|
160
|
```ts title="src/search/product.ts" highlights={priceFieldHighlights} |
|
161
|
const PRICE_CURRENCIES = ["usd", "eur"] as const |
|
162
|
|
|
163
|
type PriceCurrency = (typeof PRICE_CURRENCIES)[number] |
|
164
|
|
|
165
|
const priceFields = Object.fromEntries( |
|
166
|
PRICE_CURRENCIES.flatMap((currency) => [ |
|
167
|
[ |
|
168
|
`min_price_${currency}`, |
|
169
|
search |
|
170
|
.float() |
|
171
|
.filterable() |
|
172
|
.sortable() |
|
173
|
.facetable({ types: ["stats"] }) |
|
174
|
.retrievable(), |
|
175
|
], |
|
176
|
[ |
|
177
|
`max_price_${currency}`, |
|
178
|
search |
|
179
|
.float() |
|
180
|
.filterable() |
|
181
|
.sortable() |
|
182
|
.facetable({ types: ["stats"] }) |
|
183
|
.retrievable(), |
|
184
|
], |
|
185
|
[ |
|
186
|
`original_price_${currency}`, |
|
187
|
search.float().retrievable(), |
|
188
|
], |
|
189
|
[ |
|
190
|
`on_sale_${currency}`, |
|
191
|
search |
|
192
|
.boolean() |
|
193
|
.filterable() |
|
194
|
.facetable() |
|
195
|
.retrievable(), |
|
196
|
], |
|
197
|
]) |
|
198
|
) |
|
199
|
|
|
200
|
export default defineSearchIndex({ |
|
201
|
// ... |
|
202
|
fields: search.define({ |
|
203
|
// ... |
|
204
|
...priceFields, |
|
205
|
}), |
|
206
|
}) |
|
207
|
``` |
|
208
|
|
|
209
|
The `min_price` and `max_price` fields use the [`stats` facet type](../index-definitions/modifiers/page.mdx#facet-types), which returns the lowest and highest price among the matching products. A storefront uses that to render a price-range slider whose bounds follow the current filters. |
|
210
|
|
|
211
|
<Note> |
|
212
|
|
|
213
|
Adding a currency changes the index's fields, which the Search Module treats as a schema change. It builds a new index version and only serves reads from it once it's filled, as explained in the [Reindexing and Migrations guide](../reindexing/page.mdx). |
|
214
|
|
|
215
|
</Note> |
|
216
|
|
|
217
|
### 2. Read the Prices |
|
218
|
|
|
219
|
`variants.calculated_price` only resolves when `query.graph` receives a [query context](!docs!/learn/fundamentals/query/query-context) with a currency. So, add a function that reads the products once per currency: |
|
220
|
|
|
221
|
export const loadPricingHighlights = [ |
|
222
|
["19", "SearchIngestionContext", "The context that `seed` and `consume` receive."], |
|
223
|
["27", "Promise.all", "One read per currency, however many products there are."], |
|
224
|
["37", "context", "Calculate the prices in this currency."], |
|
225
|
] |
|
226
|
|
|
227
|
```ts title="src/search/product.ts" highlights={loadPricingHighlights} |
|
228
|
import { QueryContext } from "@medusajs/framework/utils" |
|
229
|
import type { SearchTypes } from "@medusajs/framework/types" |
|
230
|
|
|
231
|
// ... |
|
232
|
|
|
233
|
type PricedVariant = { |
|
234
|
calculated_price?: { |
|
235
|
calculated_amount?: number | null |
|
236
|
original_amount?: number | null |
|
237
|
} | null |
|
238
|
} |
|
239
|
|
|
240
|
type ProductPricingRows = Partial< |
|
241
|
Record<PriceCurrency, PricedVariant[] | null> |
|
242
|
> |
|
243
|
|
|
244
|
async function loadPricing( |
|
245
|
ids: string[], |
|
246
|
{ container }: SearchTypes.SearchIngestionContext |
|
247
|
) { |
|
248
|
const pricing = new Map<string, ProductPricingRows>() |
|
249
|
|
|
250
|
if (!ids.length) { |
|
251
|
return pricing |
|
252
|
} |
|
253
|
|
|
254
|
await Promise.all( |
|
255
|
PRICE_CURRENCIES.map(async (currency) => { |
|
256
|
const { data } = await container.query.graph({ |
|
257
|
entity: "product", |
|
258
|
fields: [ |
|
259
|
"id", |
|
260
|
"variants.calculated_price.calculated_amount", |
|
261
|
"variants.calculated_price.original_amount", |
|
262
|
], |
|
263
|
filters: { id: ids }, |
|
264
|
context: { |
|
265
|
variants: { |
|
266
|
calculated_price: QueryContext({ |
|
267
|
currency_code: currency, |
|
268
|
}), |
|
269
|
}, |
|
270
|
}, |
|
271
|
}) |
|
272
|
|
|
273
|
for (const product of data) { |
|
274
|
const rows = pricing.get(product.id) ?? {} |
|
275
|
rows[currency] = product.variants |
|
276
|
pricing.set(product.id, rows) |
|
277
|
} |
|
278
|
}) |
|
279
|
) |
|
280
|
|
|
281
|
return pricing |
|
282
|
} |
|
283
|
``` |
|
284
|
|
|
285
|
`loadPricing` receives the IDs of the products being indexed, then reads each of them once per currency with the currency's pricing context. It returns a map of a product's ID to its priced variants per currency, which the next step turns into the document's price fields. |
|
286
|
|
|
287
|
`transform` receives a whole page of products at a time, so this costs one extra read per currency for the page, rather than one per product. |
|
288
|
|
|
289
|
### 3. Build the Price Fields of a Document |
|
290
|
|
|
291
|
Next, turn a product's variants into the price fields of its document. The cheapest variant provides the calculated and original price as a pair, so the discount a storefront renders describes one real variant instead of mixing two variants' amounts: |
|
292
|
|
|
293
|
export const toPricingHighlights = [ |
|
294
|
["37", "min_price", "The cheapest variant's calculated price."], |
|
295
|
["39", "original_price", "The same variant's price before a promotion."], |
|
296
|
["40", "on_sale", "Written even when `false`, so the facet has both buckets."], |
|
297
|
] |
|
298
|
|
|
299
|
```ts title="src/search/product.ts" highlights={toPricingHighlights} |
|
300
|
function toPricing( |
|
301
|
currency: PriceCurrency, |
|
302
|
variants: PricedVariant[] | null | undefined |
|
303
|
) { |
|
304
|
let cheapest: |
|
305
|
| { calculated: number; original: number } |
|
306
|
| undefined |
|
307
|
let maxPrice: number | undefined |
|
308
|
|
|
309
|
for (const variant of variants ?? []) { |
|
310
|
const price = variant?.calculated_price |
|
311
|
const calculated = price?.calculated_amount |
|
312
|
|
|
313
|
if (typeof calculated !== "number") { |
|
314
|
continue |
|
315
|
} |
|
316
|
|
|
317
|
const original = |
|
318
|
typeof price?.original_amount === "number" |
|
319
|
? price.original_amount |
|
320
|
: calculated |
|
321
|
|
|
322
|
if (maxPrice === undefined || calculated > maxPrice) { |
|
323
|
maxPrice = calculated |
|
324
|
} |
|
325
|
|
|
326
|
if (!cheapest || calculated < cheapest.calculated) { |
|
327
|
cheapest = { calculated, original } |
|
328
|
} |
|
329
|
} |
|
330
|
|
|
331
|
if (!cheapest) { |
|
332
|
return {} |
|
333
|
} |
|
334
|
|
|
335
|
return { |
|
336
|
[`min_price_${currency}`]: cheapest.calculated, |
|
337
|
[`max_price_${currency}`]: maxPrice, |
|
338
|
[`original_price_${currency}`]: cheapest.original, |
|
339
|
[`on_sale_${currency}`]: |
|
340
|
cheapest.original > cheapest.calculated, |
|
341
|
} |
|
342
|
} |
|
343
|
|
|
344
|
function toProductPricing( |
|
345
|
rows: ProductPricingRows | undefined |
|
346
|
) { |
|
347
|
return Object.assign( |
|
348
|
{}, |
|
349
|
...PRICE_CURRENCIES.map((currency) => |
|
350
|
toPricing(currency, rows?.[currency]) |
|
351
|
) |
|
352
|
) |
|
353
|
} |
|
354
|
``` |
|
355
|
|
|
356
|
`toPricing` scans one currency's variants for the cheapest and the most expensive calculated price, then returns that currency's four fields. |
|
357
|
|
|
358
|
`toProductPricing` calls `toPricing` for every currency and merges the results into the fields of one document. |
|
359
|
|
|
360
|
A product without a price in a currency writes none of that currency's fields, so it drops out of that currency's price filter and sort rather than showing up with a price of `0`. |
|
361
|
|
|
362
|
### 4. Write the Prices to the Documents |
|
363
|
|
|
364
|
Finally, call both functions in an asynchronous `transform`: |
|
365
|
|
|
366
|
export const priceIndexHighlights = [ |
|
367
|
["3", "async", "The function can await other reads."], |
|
368
|
["5", "loadPricing", "Read the prices of the whole page at once."], |
|
369
|
["14", "toProductPricing", "Add the product's price fields to its document."], |
|
370
|
] |
|
371
|
|
|
372
|
```ts title="src/search/product.ts" highlights={priceIndexHighlights} |
|
373
|
const source = { |
|
374
|
fields: ["id", "title", "status"], |
|
375
|
transform: async (products, context) => { |
|
376
|
// ... |
|
377
|
const pricing = await loadPricing( |
|
378
|
products.map((product) => product.id), |
|
379
|
context |
|
380
|
) |
|
381
|
|
|
382
|
return products.map((product) => ({ |
|
383
|
id: product.id, |
|
384
|
title: product.title, |
|
385
|
// ... |
|
386
|
...toProductPricing(pricing.get(product.id)), |
|
387
|
})) |
|
388
|
}, |
|
389
|
} |
|
390
|
``` |
|
391
|
|
|
392
|
A storefront then filters on `min_price_usd`, sorts by it, and shows an "On sale" toggle backed by the `on_sale_usd` facet. |
|
393
|
|
|
394
|
--- |
|
395
|
|
|
396
|
## Index Option Values as a Facet |
|
397
|
|
|
398
|
To let a storefront filter products by option values, such as a size or a color, flatten a product's options into one array field of `"{option title}:{value}"` entries. One field keeps the index simple, and the storefront splits each entry on the first `:` to group the facet by option title. |
|
399
|
|
|
400
|
export const optionHighlights = [ |
|
401
|
["3", "toOptionValues", "Flatten a product's options into one array."], |
|
402
|
["33", `"options.title"`, "Selected to fill `option_values`."], |
|
403
|
["51", "searchable", "A query matching an option value matches the product."], |
|
404
|
] |
|
405
|
|
|
406
|
```ts title="src/search/product.ts" highlights={optionHighlights} |
|
407
|
// ... |
|
408
|
|
|
409
|
function toOptionValues( |
|
410
|
options: |
|
411
|
| ({ |
|
412
|
title?: string | null |
|
413
|
values?: ({ value?: string | null } | null)[] |
|
414
|
} | null)[] |
|
415
|
| null |
|
416
|
| undefined |
|
417
|
) { |
|
418
|
const values = (options ?? []).flatMap((option) => { |
|
419
|
const title = option?.title?.trim() |
|
420
|
|
|
421
|
if (!title) { |
|
422
|
return [] |
|
423
|
} |
|
424
|
|
|
425
|
return (option?.values ?? []) |
|
426
|
.map((optionValue) => optionValue?.value?.trim()) |
|
427
|
.filter((value): value is string => Boolean(value)) |
|
428
|
.map((value) => `${title}:${value}`) |
|
429
|
}) |
|
430
|
|
|
431
|
// A value shared by two options is otherwise |
|
432
|
// counted twice in the facet. |
|
433
|
return Array.from(new Set(values)) |
|
434
|
} |
|
435
|
|
|
436
|
const source = { |
|
437
|
fields: [ |
|
438
|
// ... |
|
439
|
"options.title", |
|
440
|
"options.values.value", |
|
441
|
], |
|
442
|
transform: (products) => { |
|
443
|
return products.map((product) => ({ |
|
444
|
// ... |
|
445
|
option_values: toOptionValues(product.options), |
|
446
|
})) |
|
447
|
}, |
|
448
|
} |
|
449
|
|
|
450
|
export default defineSearchIndex({ |
|
451
|
// ... |
|
452
|
fields: search.define({ |
|
453
|
// ... |
|
454
|
option_values: search |
|
455
|
.keyword() |
|
456
|
.array() |
|
457
|
.searchable({ weight: 2 }) |
|
458
|
.filterable() |
|
459
|
.facetable() |
|
460
|
.retrievable(), |
|
461
|
}), |
|
462
|
consume: graphConsume(source), |
|
463
|
seed: graphSeed(source), |
|
464
|
}) |
|
465
|
``` |
|
466
|
|
|
467
|
`toOptionValues` walks a product's options, pairs each option's title with each of its values, and drops duplicates. A product with a Size and a Color option yields entries such as `["Size:S", "Size:M", "Color:Red"]`, which the `transform` writes to the document's `option_values` field. |
|
468
|
|
|
469
|
Since the field is searchable, a customer searching for "red" also matches a product whose color option has a `Red` value. |
|
470
|
|
|
471
|
--- |
|
472
|
|
|
473
|
## Index Categories and Tags as Facets |
|
474
|
|
|
475
|
`query.graph` returns a product's categories and tags as arrays of objects, whereas a facet needs a flat array of values. So, select the field to show from each relation and flatten it in the `transform`: |
|
476
|
|
|
477
|
export const categoryHighlights = [ |
|
478
|
["4", `"categories.name"`, "Select one field from each relation."], |
|
479
|
["10", "category", "Flatten the categories into an array of names."], |
|
480
|
["13", "labels", "Flatten the tags into an array of values."], |
|
481
|
] |
|
482
|
|
|
483
|
```ts title="src/search/product.ts" highlights={categoryHighlights} |
|
484
|
const source = { |
|
485
|
fields: [ |
|
486
|
// ... |
|
487
|
"categories.name", |
|
488
|
"tags.value", |
|
489
|
], |
|
490
|
transform: (products) => { |
|
491
|
return products.map((product) => ({ |
|
492
|
// ... |
|
493
|
category: (product.categories ?? []).map( |
|
494
|
(category) => category.name |
|
495
|
), |
|
496
|
labels: (product.tags ?? []).map( |
|
497
|
(tag) => tag.value |
|
498
|
), |
|
499
|
})) |
|
500
|
}, |
|
501
|
} |
|
502
|
|
|
503
|
export default defineSearchIndex({ |
|
504
|
// ... |
|
505
|
fields: search.define({ |
|
506
|
// ... |
|
507
|
category: search |
|
508
|
.keyword() |
|
509
|
.array() |
|
510
|
.filterable() |
|
511
|
.facetable() |
|
512
|
.retrievable(), |
|
513
|
labels: search |
|
514
|
.keyword() |
|
515
|
.array() |
|
516
|
.filterable() |
|
517
|
.facetable() |
|
518
|
.retrievable(), |
|
519
|
}), |
|
520
|
consume: graphConsume(source), |
|
521
|
seed: graphSeed(source), |
|
522
|
}) |
|
523
|
``` |
|
524
|
|
|
525
|
To index a product's data from a linked module instead, such as a brand you created in a custom module, refer to the [Index Data from a Linked Module guide](../index-definitions/linked-data/page.mdx). |
|
526
|
|
|
527
|
--- |
|
528
|
|
|
529
|
## Re-Index a Product When Related Data Changes |
|
530
|
|
|
531
|
A product's document holds data from its variants, options, tags, categories, and sales channels. So, subscribe to the events of all of them, then map each event back to the products it affects with the [`resolve_ids` option](../index-definitions/page.mdx#graphconsume-options) of `graphConsume`. |
|
532
|
|
|
533
|
Add the following functions to the file: |
|
534
|
|
|
535
|
export const resolveIdsHighlights = [ |
|
536
|
["25", "withDeleted", "A deleted row still leads back to its products."], |
|
537
|
["38", "entity", "The entity the event's name starts with."], |
|
538
|
["46", "product", "A product event names the products directly."], |
|
539
|
["48", "product-variant", "Read the products behind the event's records."], |
|
540
|
] |
|
541
|
|
|
542
|
```ts title="src/search/product.ts" highlights={resolveIdsHighlights} |
|
543
|
import type { |
|
544
|
RemoteQueryFunction, |
|
545
|
} from "@medusajs/framework/types" |
|
546
|
|
|
547
|
// ... |
|
548
|
|
|
549
|
function payloadIds(data: unknown): string[] { |
|
550
|
return (Array.isArray(data) ? data : [data]) |
|
551
|
.map((entry) => (entry as { id?: string })?.id) |
|
552
|
.filter((id): id is string => Boolean(id)) |
|
553
|
} |
|
554
|
|
|
555
|
async function relatedProductIds( |
|
556
|
query: RemoteQueryFunction, |
|
557
|
entity: string, |
|
558
|
fields: string[], |
|
559
|
ids: string[], |
|
560
|
pick: (row: any) => (string | null | undefined)[], |
|
561
|
withDeleted: boolean |
|
562
|
) { |
|
563
|
const { data } = await query.graph({ |
|
564
|
entity, |
|
565
|
fields, |
|
566
|
filters: { id: ids }, |
|
567
|
withDeleted, |
|
568
|
}) |
|
569
|
|
|
570
|
return data |
|
571
|
.flatMap(pick) |
|
572
|
.filter((id): id is string => Boolean(id)) |
|
573
|
} |
|
574
|
|
|
575
|
async function resolveProductIds( |
|
576
|
event: { name: string; data: unknown }, |
|
577
|
{ container }: SearchTypes.SearchIngestionContext |
|
578
|
) { |
|
579
|
const ids = payloadIds(event.data) |
|
580
|
const [entity] = event.name.split(".") |
|
581
|
const deleted = event.name.endsWith(".deleted") |
|
582
|
|
|
583
|
if (!ids.length) { |
|
584
|
return [] |
|
585
|
} |
|
586
|
|
|
587
|
switch (entity) { |
|
588
|
case "product": |
|
589
|
return ids |
|
590
|
case "product-variant": |
|
591
|
return relatedProductIds( |
|
592
|
container.query, |
|
593
|
"product_variant", |
|
594
|
["product_id"], |
|
595
|
ids, |
|
596
|
(row) => [row.product_id], |
|
597
|
deleted |
|
598
|
) |
|
599
|
case "product-tag": |
|
600
|
return relatedProductIds( |
|
601
|
container.query, |
|
602
|
"product_tag", |
|
603
|
["products.id"], |
|
604
|
ids, |
|
605
|
(row) => (row.products ?? []).map((p) => p?.id), |
|
606
|
deleted |
|
607
|
) |
|
608
|
case "product-category": |
|
609
|
return relatedProductIds( |
|
610
|
container.query, |
|
611
|
"product_category", |
|
612
|
["products.id"], |
|
613
|
ids, |
|
614
|
(row) => (row.products ?? []).map((p) => p?.id), |
|
615
|
deleted |
|
616
|
) |
|
617
|
default: |
|
618
|
return [] |
|
619
|
} |
|
620
|
} |
|
621
|
``` |
|
622
|
|
|
623
|
`resolveProductIds` is the function you pass as `resolve_ids` in the next snippet, and `graphConsume` calls it for every event the index subscribes to. It reads the IDs from the event's payload, then decides what they point to based on the entity in the event's name: a product event names the products directly, while any other event's IDs are passed to `relatedProductIds`, which reads the products behind those records through `query.graph`. |
|
624
|
|
|
625
|
Medusa soft-deletes records, so a deleted variant or category is still readable with `withDeleted`, which is how it still leads back to the products to re-index. |
|
626
|
|
|
627
|
Then, add the related entities' events to the index, pass the function to `graphConsume`, and tell it that only `product.deleted` removes documents. Every other event means the product must be read again: |
|
628
|
|
|
629
|
export const consumeHighlights = [ |
|
630
|
["19", "resolve_ids", "Map each event to the products it affects."], |
|
631
|
["20", "is_delete", "Only a deleted product leaves the index."], |
|
632
|
] |
|
633
|
|
|
634
|
```ts title="src/search/product.ts" highlights={consumeHighlights} |
|
635
|
export default defineSearchIndex({ |
|
636
|
// ... |
|
637
|
events: [ |
|
638
|
"product.created", |
|
639
|
"product.updated", |
|
640
|
"product.deleted", |
|
641
|
"product-variant.created", |
|
642
|
"product-variant.updated", |
|
643
|
"product-variant.deleted", |
|
644
|
"product-option.updated", |
|
645
|
"product-option-value.updated", |
|
646
|
"product-tag.updated", |
|
647
|
"product-tag.deleted", |
|
648
|
"product-category.updated", |
|
649
|
"product-category.deleted", |
|
650
|
], |
|
651
|
consume: graphConsume({ |
|
652
|
...source, |
|
653
|
resolve_ids: resolveProductIds, |
|
654
|
is_delete: (event) => |
|
655
|
event.name === "product.deleted", |
|
656
|
}), |
|
657
|
seed: graphSeed(source), |
|
658
|
}) |
|
659
|
``` |
|
660
|
|
|
661
|
### Deleting a Sales Channel |
|
662
|
|
|
663
|
Deleting a sales channel removes its product links, so `query.graph` no longer finds the products that were in it. The index still holds the channel's ID on each document, so search the index itself to find the products to re-index: |
|
664
|
|
|
665
|
```ts title="src/search/product.ts" |
|
666
|
async function productIdsInSalesChannels( |
|
667
|
query: RemoteQueryFunction, |
|
668
|
salesChannelIds: string[] |
|
669
|
) { |
|
670
|
const { search_result } = await query.search({ |
|
671
|
entity: "product", |
|
672
|
fields: ["id"], |
|
673
|
filters: { sales_channel_ids: salesChannelIds }, |
|
674
|
pagination: { take: 200 }, |
|
675
|
}) |
|
676
|
|
|
677
|
return search_result.hits.map((hit) => hit.id) |
|
678
|
} |
|
679
|
``` |
|
680
|
|
|
681
|
Then, call it from a `sales-channel` case in `resolveProductIds`, and add the `sales-channel.deleted` event to the definition's `events`: |
|
682
|
|
|
683
|
```ts title="src/search/product.ts" |
|
684
|
async function resolveProductIds( |
|
685
|
event: { name: string; data: unknown }, |
|
686
|
{ container }: SearchTypes.SearchIngestionContext |
|
687
|
) { |
|
688
|
// ... |
|
689
|
|
|
690
|
switch (entity) { |
|
691
|
// ... |
|
692
|
case "sales-channel": |
|
693
|
return productIdsInSalesChannels( |
|
694
|
container.query, |
|
695
|
ids |
|
696
|
) |
|
697
|
default: |
|
698
|
return [] |
|
699
|
} |
|
700
|
} |
|
701
|
``` |
|
702
|
|
|
703
|
If your store has more than 200 products in a channel, page through the results with the `skip` pagination option. |
|
704
|
|
|
705
|
<Note title="Note"> |
|
706
|
|
|
707
|
Some changes to a product's prices don't emit an event, such as creating a price list or a price list becoming active. For those, reindex the product index on a schedule, or after the change, as explained in the [Reindexing and Migrations guide](../reindexing/page.mdx#seeding-on-demand). |
|
708
|
|
|
709
|
</Note> |
|
710
|
|
|
711
|
--- |
|
712
|
|
|
713
|
## Complete Index Definition |
|
714
|
|
|
715
|
The following file combines the examples of this guide. The pricing and event functions are left out, since they're unchanged from the sections above: |
|
716
|
|
|
717
|
export const completeHighlights = [ |
|
718
|
["14", "status", "Lets the Store Search API route scope the index to published products."], |
|
719
|
["69", "transform", "Reshape each product into the document to index."], |
|
720
|
["106", "settings", "Engine settings, supported by Medusa Search only."], |
|
721
|
["124", "consume", "Turn each event into document writes."], |
|
722
|
] |
|
723
|
|
|
724
|
```ts title="src/search/product.ts" highlights={completeHighlights} |
|
725
|
import type { SearchTypes } from "@medusajs/framework/types" |
|
726
|
import { |
|
727
|
defineSearchIndex, |
|
728
|
graphConsume, |
|
729
|
graphSeed, |
|
730
|
search, |
|
731
|
} from "@medusajs/framework/utils" |
|
732
|
|
|
733
|
// The functions and price fields of the |
|
734
|
// previous sections... |
|
735
|
|
|
736
|
const productFields = search.define({ |
|
737
|
id: search.keyword().filterable().retrievable(), |
|
738
|
status: search |
|
739
|
.keyword() |
|
740
|
.filterable() |
|
741
|
.retrievable(false), |
|
742
|
sales_channel_ids: search |
|
743
|
.keyword() |
|
744
|
.array() |
|
745
|
.filterable() |
|
746
|
.retrievable(false), |
|
747
|
title: search |
|
748
|
.text() |
|
749
|
.searchable({ weight: 3 }) |
|
750
|
.sortable() |
|
751
|
.retrievable(), |
|
752
|
description: search.text().searchable({ weight: 1 }), |
|
753
|
handle: search.keyword().retrievable(), |
|
754
|
thumbnail: search.keyword().retrievable(), |
|
755
|
created_at: search.date().sortable().retrievable(), |
|
756
|
category: search |
|
757
|
.keyword() |
|
758
|
.array() |
|
759
|
.filterable() |
|
760
|
.facetable() |
|
761
|
.retrievable(), |
|
762
|
labels: search |
|
763
|
.keyword() |
|
764
|
.array() |
|
765
|
.filterable() |
|
766
|
.facetable() |
|
767
|
.retrievable(), |
|
768
|
option_values: search |
|
769
|
.keyword() |
|
770
|
.array() |
|
771
|
.searchable({ weight: 2 }) |
|
772
|
.filterable() |
|
773
|
.facetable() |
|
774
|
.retrievable(), |
|
775
|
...priceFields, |
|
776
|
}) |
|
777
|
|
|
778
|
const source = { |
|
779
|
fields: [ |
|
780
|
"id", |
|
781
|
"title", |
|
782
|
"description", |
|
783
|
"handle", |
|
784
|
"thumbnail", |
|
785
|
"status", |
|
786
|
"created_at", |
|
787
|
"sales_channels.id", |
|
788
|
"categories.name", |
|
789
|
"tags.value", |
|
790
|
"options.title", |
|
791
|
"options.values.value", |
|
792
|
], |
|
793
|
transform: async ( |
|
794
|
products, |
|
795
|
context: SearchTypes.SearchIngestionContext |
|
796
|
) => { |
|
797
|
const pricing = await loadPricing( |
|
798
|
products.map((product) => product.id), |
|
799
|
context |
|
800
|
) |
|
801
|
|
|
802
|
return products.map((product) => ({ |
|
803
|
id: product.id, |
|
804
|
status: product.status, |
|
805
|
sales_channel_ids: ( |
|
806
|
product.sales_channels ?? [] |
|
807
|
).map((salesChannel) => salesChannel.id), |
|
808
|
title: product.title, |
|
809
|
description: product.description, |
|
810
|
handle: product.handle, |
|
811
|
thumbnail: product.thumbnail, |
|
812
|
created_at: product.created_at, |
|
813
|
category: (product.categories ?? []).map( |
|
814
|
(category) => category.name |
|
815
|
), |
|
816
|
labels: (product.tags ?? []).map( |
|
817
|
(tag) => tag.value |
|
818
|
), |
|
819
|
option_values: toOptionValues(product.options), |
|
820
|
...toProductPricing(pricing.get(product.id)), |
|
821
|
})) |
|
822
|
}, |
|
823
|
} |
|
824
|
|
|
825
|
export default defineSearchIndex({ |
|
826
|
name: "product", |
|
827
|
entity: "product", |
|
828
|
primary_key: "id", |
|
829
|
fields: productFields, |
|
830
|
settings: { |
|
831
|
typo_tolerance: { enabled: true }, |
|
832
|
}, |
|
833
|
events: [ |
|
834
|
"product.created", |
|
835
|
"product.updated", |
|
836
|
"product.deleted", |
|
837
|
"product-variant.created", |
|
838
|
"product-variant.updated", |
|
839
|
"product-variant.deleted", |
|
840
|
"product-option.updated", |
|
841
|
"product-option-value.updated", |
|
842
|
"product-tag.updated", |
|
843
|
"product-tag.deleted", |
|
844
|
"product-category.updated", |
|
845
|
"product-category.deleted", |
|
846
|
"sales-channel.deleted", |
|
847
|
], |
|
848
|
consume: graphConsume({ |
|
849
|
...source, |
|
850
|
resolve_ids: resolveProductIds, |
|
851
|
is_delete: (event) => |
|
852
|
event.name === "product.deleted", |
|
853
|
}), |
|
854
|
seed: graphSeed(source), |
|
855
|
}) |
|
856
|
``` |
|
857
|
|
|
858
|
After changing the definition, run the migrations command to build the new index version: |
|
859
|
|
|
860
|
```bash npm2yarn |
|
861
|
npx medusa db:migrate |
|
862
|
``` |
|
863
|
|
|
864
|
Then, allow the index on the [Store Search API route](../store-search/page.mdx) to search it from your storefront. |
|
865
|
|
|
866
|
<Note title="Tip"> |
|
867
|
|
|
868
|
To build the search and browsing experience around this index, use the [InstantSearch adapter](../../../instantsearch/page.mdx). Refer to the [Filtering, Sorting, and Pagination example](../../../instantsearch/examples/filtering-sorting-pagination/page.mdx) for the widgets that back the facets in this guide. |
|
869
|
|
|
870
|
</Note> |