|
1
|
import { Table, Prerequisites } from "docs-ui" |
|
2
|
|
|
3
|
export const metadata = { |
|
4
|
title: `Search Module`, |
|
5
|
} |
|
6
|
|
|
7
|
# {metadata.title} |
|
8
|
|
|
9
|
In this guide, you'll learn about the Search Module, its providers, and its index definitions. |
|
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
|
<Note title="Easier setup with Cloud"> |
|
21
|
|
|
22
|
Cloud provides pre-configured search infrastructure for your Medusa application. You can use it to set up without configuring and managing your own search engine. Learn more in the [Medusa Search](!cloud!/search) documentation. |
|
23
|
|
|
24
|
</Note> |
|
25
|
|
|
26
|
## What is the Search Module? |
|
27
|
|
|
28
|
The Search Module provides full-text search functionality in your Medusa application. It indexes your data in a search engine, then serves queries with relevance ranking, filters, facets, highlighting, and vector search. |
|
29
|
|
|
30
|
For example, you can use the Search Module to power a storefront's product search with typo tolerance and category facets, or to let admin users find orders by customer name. |
|
31
|
|
|
32
|
The Search Module writes to and reads from the search engine you integrate, such as [PostgreSQL](./providers/postgres/page.mdx) or [Medusa Search](!cloud!/search) for Cloud users. This gives you flexibility in choosing the search infrastructure that matches your performance and scalability requirements. |
|
33
|
|
|
34
|
### How the Search Module Works |
|
35
|
|
|
36
|
The Search Module has two parts that you control: |
|
37
|
|
|
38
|
- **[Search Module Providers](./providers/page.mdx)**: they implement the logic of talking to a search engine. |
|
39
|
- **[Search index definitions](./index-definitions/page.mdx)**: you declare which entity to index, which fields the engine holds, and how to fill the index. |
|
40
|
|
|
41
|
The Search Module handles everything between the two. It creates and migrates the physical indexes, fills them when they are empty, applies events to keep them current, and compiles a search query into whatever the provider's engine understands. |
|
42
|
|
|
43
|
It also keeps a version per physical index it builds, so a definition change builds a new version alongside the one serving reads and only makes it active once it's filled. Every provider rebuilds an index that way, so a schema change costs no downtime whichever one you use. |
|
44
|
|
|
45
|
--- |
|
46
|
|
|
47
|
## Configure the Search Module |
|
48
|
|
|
49
|
As of v2.21.1, the Search Module is registered by default in your Medusa application with the [PostgreSQL Search Module Provider](./providers/postgres/page.mdx), so you only declare the indexes to search. The module itself needs no extra configuration. |
|
50
|
|
|
51
|
On Cloud, [Medusa Search](!cloud!/search) is registered by default for all plans, unless you explicitly configure a different provider. |
|
52
|
|
|
53
|
### Change Default Search Configuration |
|
54
|
|
|
55
|
To change the Search Module's configuration or use a different provider, add the Search Module to the `modules` property of the exported object in `medusa-config.ts`: |
|
56
|
|
|
57
|
```ts title="medusa-config.ts" |
|
58
|
// To register only for development. This is necessary to use Medusa Search in Cloud |
|
59
|
const isDev = process.env.NODE_ENV !== "production" |
|
60
|
|
|
61
|
module.exports = defineConfig({ |
|
62
|
// ... |
|
63
|
modules: [ |
|
64
|
isDev && { |
|
65
|
resolve: "@medusajs/medusa/search", |
|
66
|
options: { |
|
67
|
index_prefix: "prod_", |
|
68
|
providers: [ |
|
69
|
{ |
|
70
|
resolve: "@medusajs/medusa/search-postgres", |
|
71
|
id: "search-postgres", |
|
72
|
}, |
|
73
|
], |
|
74
|
}, |
|
75
|
}, |
|
76
|
].filter(Boolean), |
|
77
|
}) |
|
78
|
``` |
|
79
|
|
|
80
|
### Run Migrations |
|
81
|
|
|
82
|
If you upgraded an existing Medusa application to v2.21.1, run the following command to create the necessary database tables for the Search Module and its configured provider: |
|
83
|
|
|
84
|
```bash npm2yarn |
|
85
|
npx medusa db:migrate |
|
86
|
``` |
|
87
|
|
|
88
|
### Search Module Options |
|
89
|
|
|
90
|
<Table> |
|
91
|
<Table.Header> |
|
92
|
<Table.Row> |
|
93
|
<Table.HeaderCell> |
|
94
|
Option |
|
95
|
</Table.HeaderCell> |
|
96
|
<Table.HeaderCell> |
|
97
|
Description |
|
98
|
</Table.HeaderCell> |
|
99
|
<Table.HeaderCell> |
|
100
|
Default |
|
101
|
</Table.HeaderCell> |
|
102
|
</Table.Row> |
|
103
|
</Table.Header> |
|
104
|
<Table.Body> |
|
105
|
<Table.Row> |
|
106
|
<Table.Cell> |
|
107
|
`providers` |
|
108
|
</Table.Cell> |
|
109
|
<Table.Cell> |
|
110
|
An array of Search Module Providers to register. You can register more than one provider and point each index at a different engine. |
|
111
|
</Table.Cell> |
|
112
|
<Table.Cell> |
|
113
|
The PostgreSQL provider, whose identifier is `search-postgres`. |
|
114
|
</Table.Cell> |
|
115
|
</Table.Row> |
|
116
|
<Table.Row> |
|
117
|
<Table.Cell> |
|
118
|
`default_provider` |
|
119
|
</Table.Cell> |
|
120
|
<Table.Cell> |
|
121
|
The identifier of the provider to use for index definitions that don't name one. Required when you register more than one provider. Its value is the `identifier` property defined in the provider's service. |
|
122
|
</Table.Cell> |
|
123
|
<Table.Cell> |
|
124
|
If only one provider is registered, the module uses it as the default. Otherwise, an error is thrown while the module initializes. |
|
125
|
</Table.Cell> |
|
126
|
</Table.Row> |
|
127
|
<Table.Row> |
|
128
|
<Table.Cell> |
|
129
|
`index_prefix` |
|
130
|
</Table.Cell> |
|
131
|
<Table.Cell> |
|
132
|
A string prepended to every physical index name. Use it when multiple applications share a search engine. |
|
133
|
</Table.Cell> |
|
134
|
<Table.Cell> |
|
135
|
No prefix. |
|
136
|
</Table.Cell> |
|
137
|
</Table.Row> |
|
138
|
<Table.Row> |
|
139
|
<Table.Cell> |
|
140
|
`reindex.batch_size` |
|
141
|
</Table.Cell> |
|
142
|
<Table.Cell> |
|
143
|
The number of documents the module writes to the engine per request while filling an index. |
|
144
|
</Table.Cell> |
|
145
|
<Table.Cell> |
|
146
|
`100` |
|
147
|
</Table.Cell> |
|
148
|
</Table.Row> |
|
149
|
</Table.Body> |
|
150
|
</Table> |
|
151
|
|
|
152
|
## Search Module Providers |
|
153
|
|
|
154
|
A Search Module Provider implements the logic of indexing and searching documents in a search engine. The Search Module uses the provider that each index definition resolves to. |
|
155
|
|
|
156
|
Medusa ships the [PostgreSQL Search Module Provider](./providers/postgres/page.mdx), and [Medusa Search](!cloud!/search) that's available for Cloud users only. You can also create your own. |
|
157
|
|
|
158
|
Refer to the [Search Module Providers guide](./providers/page.mdx) to learn how to register providers, choose a default, and point an index at a specific provider. |
|
159
|
|
|
160
|
<Note title="Tip"> |
|
161
|
|
|
162
|
Providers don't back the same set of features, so the provider you pick decides which index definitions you can declare and which query features you can pass. Refer to the [Comparison guide](!cloud!/search/comparison) for what each provider does with every feature they treat differently. |
|
163
|
|
|
164
|
</Note> |
|
165
|
|
|
166
|
--- |
|
167
|
|
|
168
|
## Search Products |
|
169
|
|
|
170
|
Medusa doesn't declare any search index by default. If you installed your Medusa application after v2.21.1, it already has a `product` index definition. Otherwise, you need to define a `product` index in your Medusa application to make your products searchable. Then, you need to make it searchable on the [Store Search API route](!api!/store/search/search-indexes). |
|
171
|
|
|
172
|
### 1. Define the Product Index |
|
173
|
|
|
174
|
An index definition names the entity to index, the fields the engine holds, a `seed` that fills the index, and the events that keep it up-to-date. |
|
175
|
|
|
176
|
Define the product index in the file `src/search/product.ts`: |
|
177
|
|
|
178
|
export const productIndexHighlights = [ |
|
179
|
["25", "name", "The index name that a search query resolves against."], |
|
180
|
["26", "entity", "The Query entity used to hydrate non-indexed fields."], |
|
181
|
["27", "fields", "The fields the search engine holds."], |
|
182
|
["33", "status", "Lets the Store Search API route scope the index to published products."], |
|
183
|
["57", "events", "The events that change the data the index holds."], |
|
184
|
["62", "consume", "Turns each of those events into document writes."], |
|
185
|
["63", "seed", "Fills the index with every product."], |
|
186
|
] |
|
187
|
|
|
188
|
{/* TODO: the fields of the default product index aren't final yet. Update this snippet once they are. */} |
|
189
|
|
|
190
|
```ts title="src/search/product.ts" highlights={productIndexHighlights} |
|
191
|
import { |
|
192
|
defineSearchIndex, |
|
193
|
graphConsume, |
|
194
|
graphSeed, |
|
195
|
search, |
|
196
|
} from "@medusajs/framework/utils" |
|
197
|
|
|
198
|
const source = { |
|
199
|
fields: [ |
|
200
|
"id", |
|
201
|
"title", |
|
202
|
"description", |
|
203
|
"handle", |
|
204
|
"thumbnail", |
|
205
|
"status", |
|
206
|
"categories.id", |
|
207
|
"categories.name", |
|
208
|
"categories.handle", |
|
209
|
"tags.id", |
|
210
|
"tags.value", |
|
211
|
], |
|
212
|
} |
|
213
|
|
|
214
|
export const productIndex = defineSearchIndex({ |
|
215
|
name: "product", |
|
216
|
entity: "product", |
|
217
|
fields: search.define({ |
|
218
|
id: search.keyword().filterable(), |
|
219
|
title: search.text().searchable({ weight: 3 }), |
|
220
|
description: search.text().searchable(), |
|
221
|
handle: search.keyword().filterable(), |
|
222
|
thumbnail: search.keyword(), |
|
223
|
status: search |
|
224
|
.keyword() |
|
225
|
.filterable() |
|
226
|
.retrievable(false), |
|
227
|
categories: search |
|
228
|
.object({ |
|
229
|
id: search.keyword().filterable(), |
|
230
|
name: search |
|
231
|
.keyword() |
|
232
|
.searchable() |
|
233
|
.facetable(), |
|
234
|
handle: search.keyword().filterable(), |
|
235
|
}) |
|
236
|
.array(), |
|
237
|
tags: search |
|
238
|
.object({ |
|
239
|
id: search.keyword().filterable(), |
|
240
|
value: search |
|
241
|
.keyword() |
|
242
|
.searchable() |
|
243
|
.facetable(), |
|
244
|
}) |
|
245
|
.array(), |
|
246
|
}), |
|
247
|
events: [ |
|
248
|
"product.created", |
|
249
|
"product.updated", |
|
250
|
"product.deleted", |
|
251
|
], |
|
252
|
consume: graphConsume(source), |
|
253
|
seed: graphSeed(source), |
|
254
|
}) |
|
255
|
``` |
|
256
|
|
|
257
|
<Note> |
|
258
|
|
|
259
|
The [Store Search API route](!api!/store/search/search-indexes) returns published products only when the index declares a `status` field with the [`filterable` modifier](./index-definitions/modifiers/page.mdx#filterable), so you don't filter out draft products yourself. The field also uses [`retrievable(false)`](./index-definitions/modifiers/page.mdx#retrievable), so the route filters on it without returning it in a hit. |
|
260
|
|
|
261
|
</Note> |
|
262
|
|
|
263
|
`seed` fills the index in full when Medusa creates or rebuilds it, and Medusa routes each of the workflow events in `events` to `consume`, so the index reflects changes as they happen. |
|
264
|
|
|
265
|
[`graphSeed`](./index-definitions/page.mdx#graphseed-options) and [`graphConsume`](./index-definitions/page.mdx#graphconsume-options) are helpers that read the data with [Query](!docs!/learn/fundamentals/query). `graphSeed` reads the entity's records to fill the index for the first time, and `graphConsume` provides the index changes, such as creating or deleting records, as the events in `events` arrive. |
|
266
|
|
|
267
|
Add to the definition any core or custom field that your storefront searches, filters, sorts, or facets on. Learn more about the available field types and modifiers in the [Search Index Definitions guide](./index-definitions/page.mdx). |
|
268
|
|
|
269
|
<Note title="Tip"> |
|
270
|
|
|
271
|
The index in this snippet 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](./product-index-examples/page.mdx). |
|
272
|
|
|
273
|
</Note> |
|
274
|
|
|
275
|
### 2. Run Migrations |
|
276
|
|
|
277
|
Next, run the migrations command to create the physical index: |
|
278
|
|
|
279
|
```bash npm2yarn |
|
280
|
npx medusa db:migrate |
|
281
|
``` |
|
282
|
|
|
283
|
Medusa then fills the index with your products. Learn more about index migrations in the [Reindexing and Migrations guide](./reindexing/page.mdx). |
|
284
|
|
|
285
|
### 3. Allow the Index on the Store Search Route |
|
286
|
|
|
287
|
Medusa exposes the [Store Search API route](!api!/store/search/search-indexes), which searches any index of your application. However, an index isn't searchable through it until a middleware allows it, so a storefront never reaches an index you didn't expose. |
|
288
|
|
|
289
|
To allow the `product` index, use the `configureStoreSearch` middleware in `src/api/middlewares.ts`: |
|
290
|
|
|
291
|
export const middlewareHighlights = [ |
|
292
|
["9", "matcher", "Apply the middleware to the Store Search API route."], |
|
293
|
["12", "allowed_indexes", "Allow the `product` index only."], |
|
294
|
] |
|
295
|
|
|
296
|
```ts title="src/api/middlewares.ts" highlights={middlewareHighlights} |
|
297
|
import { |
|
298
|
configureStoreSearch, |
|
299
|
defineMiddlewares, |
|
300
|
} from "@medusajs/framework/http" |
|
301
|
|
|
302
|
export default defineMiddlewares({ |
|
303
|
routes: [ |
|
304
|
{ |
|
305
|
matcher: "/store/search", |
|
306
|
middlewares: [ |
|
307
|
configureStoreSearch({ |
|
308
|
allowed_indexes: { |
|
309
|
product: true, |
|
310
|
}, |
|
311
|
}), |
|
312
|
], |
|
313
|
}, |
|
314
|
], |
|
315
|
}) |
|
316
|
``` |
|
317
|
|
|
318
|
You can allow more than one index, and you can add the middleware more than once, so a plugin exposes its own index without discarding what your application allowed. |
|
319
|
|
|
320
|
The route also narrows a product index to the products a storefront may see, and you can narrow any index further with a filter of your own. Learn more in the [Store Search Route guide](./store-search/page.mdx). |
|
321
|
|
|
322
|
### 4. Search Products |
|
323
|
|
|
324
|
Finally, send a `POST` request to `/store/search` with the index to search in the `entity` field: |
|
325
|
|
|
326
|
```bash |
|
327
|
curl -X POST "http://localhost:9000/store/search" \ |
|
328
|
-H "x-publishable-api-key: pk_123" \ |
|
329
|
-H "Content-Type: application/json" \ |
|
330
|
--data '{ |
|
331
|
"entity": "product", |
|
332
|
"filters": { "q": "shirt" }, |
|
333
|
"pagination": { "take": 20 } |
|
334
|
}' |
|
335
|
``` |
|
336
|
|
|
337
|
You'll receive a JSON response like the following: |
|
338
|
|
|
339
|
```json |
|
340
|
{ |
|
341
|
"results": [ |
|
342
|
{ |
|
343
|
"hits": [ |
|
344
|
{ |
|
345
|
"id": "prod_01KXR3J9J610DT161E2E4ZS6P1", |
|
346
|
"score": 1.23, |
|
347
|
"document": { |
|
348
|
"id": "prod_01KXR3J9J610DT161E2E4ZS6P1", |
|
349
|
"title": "Medusa T-Shirt", |
|
350
|
"handle": "t-shirt" |
|
351
|
} |
|
352
|
} |
|
353
|
], |
|
354
|
"metadata": { |
|
355
|
"skip": 0, |
|
356
|
"take": 20, |
|
357
|
"count": 1, |
|
358
|
"query": "shirt", |
|
359
|
"processing_time_ms": 9 |
|
360
|
} |
|
361
|
} |
|
362
|
] |
|
363
|
} |
|
364
|
``` |
|
365
|
|
|
366
|
The route answers with one result per posted query, each holding the matching `hits` ranked by relevance, any facets you asked for, and the query's `metadata`. |
|
367
|
|
|
368
|
You can also post a batch of queries at once in a `queries` array, and each of them runs against the index it names in one round-trip to the search engine. |
|
369
|
|
|
370
|
<Note title="Tip"> |
|
371
|
|
|
372
|
To build the search experience in your storefront, use the [InstantSearch adapter](../../instantsearch/page.mdx). It turns InstantSearch widgets, such as a search box, facet filters, and pagination, into requests to this route. |
|
373
|
|
|
374
|
</Note> |
|
375
|
|
|
376
|
--- |
|
377
|
|
|
378
|
## Search Other Entities |
|
379
|
|
|
380
|
To search data other than products, such as the custom data models of your own modules, declare an index definition for it in a file under the `src/search` directory, then run the migrations command. |
|
381
|
|
|
382
|
For example, to index a custom `brand` data model, create the file `src/search/brand.ts`: |
|
383
|
|
|
384
|
export const definitionHighlights = [ |
|
385
|
["11", "name", "The index name that a search query resolves against."], |
|
386
|
["12", "entity", "The Query entity used to hydrate non-indexed fields."], |
|
387
|
["13", "fields", "The fields the search engine holds."], |
|
388
|
["19", "events", "The events that change the data the index holds."], |
|
389
|
["24", "consume", "Turns each of those events into document writes."], |
|
390
|
["25", "seed", "Fills the index with every brand."], |
|
391
|
] |
|
392
|
|
|
393
|
```ts title="src/search/brand.ts" highlights={definitionHighlights} |
|
394
|
import { |
|
395
|
defineSearchIndex, |
|
396
|
graphConsume, |
|
397
|
graphSeed, |
|
398
|
search, |
|
399
|
} from "@medusajs/framework/utils" |
|
400
|
|
|
401
|
const fields = ["id", "name", "country", "created_at"] |
|
402
|
|
|
403
|
export const brandIndex = defineSearchIndex({ |
|
404
|
name: "brand", |
|
405
|
entity: "brand", |
|
406
|
fields: search.define({ |
|
407
|
id: search.keyword().filterable(), |
|
408
|
name: search.text().searchable({ weight: 3 }), |
|
409
|
country: search.keyword().filterable().facetable(), |
|
410
|
created_at: search.date().sortable(), |
|
411
|
}), |
|
412
|
events: [ |
|
413
|
"brand.created", |
|
414
|
"brand.updated", |
|
415
|
"brand.deleted", |
|
416
|
], |
|
417
|
consume: graphConsume({ fields }), |
|
418
|
seed: graphSeed({ fields }), |
|
419
|
}) |
|
420
|
``` |
|
421
|
|
|
422
|
Then, choose how to search it: |
|
423
|
|
|
424
|
- To search it from your storefront, add `brand` to the `configureStoreSearch` middleware, as explained in [Allow the Index on the Store Search Route](#3-allow-the-index-on-the-store-search-route), then post a query with `"entity": "brand"`. |
|
425
|
- To search it in your own [API route](!docs!/learn/fundamentals/api-routes) or [workflow](!docs!/learn/fundamentals/workflows), use the [`search` method of Query](!docs!/learn/fundamentals/query/search). |
|
426
|
|
|
427
|
For example, to search brands in a custom API route, create the file `src/api/store/brands/search/route.ts` with the following content: |
|
428
|
|
|
429
|
export const searchHighlights = [ |
|
430
|
["11", "query", "Resolve Query from the Medusa container."], |
|
431
|
["15", "search", "Returns the hydrated entities and the engine's result."], |
|
432
|
["16", "entity", "The name of the index to search."], |
|
433
|
["17", "fields", "The fields to return on every result."], |
|
434
|
["19", "q", "The free-text query, passed among the filters."], |
|
435
|
] |
|
436
|
|
|
437
|
```ts title="src/api/store/brands/search/route.ts" highlights={searchHighlights} |
|
438
|
import { |
|
439
|
MedusaRequest, |
|
440
|
MedusaResponse, |
|
441
|
ContainerRegistrationKeys, |
|
442
|
} from "@medusajs/framework/http" |
|
443
|
|
|
444
|
export const GET = async ( |
|
445
|
req: MedusaRequest, |
|
446
|
res: MedusaResponse |
|
447
|
) => { |
|
448
|
const query = req.scope.resolve( |
|
449
|
ContainerRegistrationKeys.QUERY |
|
450
|
) |
|
451
|
|
|
452
|
const { data, search_result } = await query.search({ |
|
453
|
entity: "brand", |
|
454
|
fields: ["id", "name", "country"], |
|
455
|
filters: { |
|
456
|
q: req.query.q as string, |
|
457
|
}, |
|
458
|
pagination: { take: 20 }, |
|
459
|
}) |
|
460
|
|
|
461
|
res.json({ |
|
462
|
brands: data, |
|
463
|
metadata: search_result.metadata, |
|
464
|
}) |
|
465
|
} |
|
466
|
``` |
|
467
|
|
|
468
|
Then, send a `GET` request to the route: |
|
469
|
|
|
470
|
```bash |
|
471
|
curl "http://localhost:9000/store/brands/search?q=acme" |
|
472
|
-H "x-publishable-api-key: pk_123" |
|
473
|
``` |
|
474
|
|
|
475
|
You'll receive a JSON response like the following: |
|
476
|
|
|
477
|
```json |
|
478
|
{ |
|
479
|
"brands": [ |
|
480
|
{ |
|
481
|
"id": "brand_01KXR3J9J610DT161E2E4ZS6P1", |
|
482
|
"name": "Acme", |
|
483
|
"country": "us" |
|
484
|
} |
|
485
|
], |
|
486
|
"metadata": { |
|
487
|
"skip": 0, |
|
488
|
"take": 20, |
|
489
|
"count": 1, |
|
490
|
"query": "acme", |
|
491
|
"processing_time_ms": 9 |
|
492
|
} |
|
493
|
} |
|
494
|
``` |
|
495
|
|
|
496
|
Learn about filters, facets, highlighting, and vector search in the [Search Queries guide](!docs!/learn/fundamentals/query/search). |