Raw
1 import { CardList, Note, Prerequisites, Table } from "docs-ui"
2
3 export const metadata = {
4 title: `Medusa Search`,
5 keywords: [
6 "search",
7 "medusa search",
8 "cloud search",
9 "full-text search",
10 "vector search",
11 "semantic search",
12 "search module",
13 "search provider",
14 ],
15 }
16
17 # {metadata.title}
18
19 In this guide, you'll learn about Medusa Search and how to use it in your Cloud projects.
20
21 <Note title="Not a Cloud user yet?">
22
23 [Sign up for Cloud](../sign-up/page.mdx) to use Medusa Search and other Cloud features.
24
25 </Note>
26
27 ## What is Medusa Search?
28
29 Medusa Search is a managed search service for Cloud projects. It stores your search indexes outside of your database and serves search queries for them.
30
31 Medusa Search gives your commerce application a search engine that serves storefront-grade search at scale, from full-text queries with relevance ranking to semantic search over embeddings. It's a low-cost yet highly performant solution, so you get sub-second search over large catalogs without paying for a dedicated search cluster or maintaining one.
32
33 ---
34
35 ## Set Up Medusa Search with an AI Agent
36
37 If you use an AI agent, such as Claude Code or Codex, ask it to fetch this page:
38
39 ```bash
40 Fetch https://docs.medusajs.com/cloud/search and follow the instructions.
41 ```
42
43 It receives a prompt version of this guide that walks it through confirming your project's setup, verifying your indexes, searching your products, and adding index definitions for your own data models. The agent runs what it can with the [Cloud CLI](../cli/page.mdx) and hands the rest back to you.
44
45 ---
46
47 ## Get Started with Medusa Search on Cloud
48
49 Medusa Search is enabled by default on Cloud for projects using Medusa v2.21.1+ with zero configuration. Medusa provisions the search resources for every Cloud environment and passes the credentials to your application, so it registers the provider and uses it for your indexes.
50
51 <Note title="Large catalogs">
52
53 Writes count toward your search request usage, and every record written to an index counts as one request. So, the first seed of a large catalog can consume a noticeable part of your plan's allowance. Refer to [How Medusa Search Counts Search Requests](#how-medusa-search-counts-search-requests) for more details.
54
55 </Note>
56
57 ### 1. Upgrade Your Medusa Application
58
59 To use Medusa Search, your Medusa application must be running v2.21.1 or later. If it isn't, upgrade it first, then deploy it to Cloud. Refer to the [Update Medusa](../update-medusa/page.mdx) guide for the upgrade steps.
60
61 ### 2. Define the Product Index
62
63 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.
64
65 Create the file `src/search/product.ts` with the following content:
66
67 ```ts title="src/search/product.ts"
68 import {
69 defineSearchIndex,
70 graphConsume,
71 graphSeed,
72 search,
73 } from "@medusajs/framework/utils"
74
75 const source = {
76 fields: [
77 "id",
78 "title",
79 "description",
80 "handle",
81 "thumbnail",
82 "status",
83 "categories.id",
84 "categories.name",
85 "categories.handle",
86 "tags.id",
87 "tags.value",
88 ],
89 }
90
91 export const productIndex = defineSearchIndex({
92 name: "product",
93 entity: "product",
94 fields: search.define({
95 id: search.keyword().filterable(),
96 title: search.text().searchable({ weight: 3 }),
97 description: search.text().searchable(),
98 handle: search.keyword().filterable(),
99 thumbnail: search.keyword(),
100 status: search
101 .keyword()
102 .filterable()
103 .retrievable(false),
104 categories: search
105 .object({
106 id: search.keyword().filterable(),
107 name: search
108 .keyword()
109 .searchable()
110 .facetable(),
111 handle: search.keyword().filterable(),
112 })
113 .array(),
114 tags: search
115 .object({
116 id: search.keyword().filterable(),
117 value: search
118 .keyword()
119 .searchable()
120 .facetable(),
121 })
122 .array(),
123 }),
124 events: [
125 "product.created",
126 "product.updated",
127 "product.deleted",
128 ],
129 consume: graphConsume(source),
130 seed: graphSeed(source),
131 })
132 ```
133
134 The definition names the fields the engine holds, fills the index with [`graphSeed`](!resources!/infrastructure-modules/search/index-definitions#fill-the-index-from-query-with-graphseed), and keeps it current with [`graphConsume`](!resources!/infrastructure-modules/search/index-definitions#consume-events-from-query-with-graphconsume). Add to it any core or custom field that your storefront searches, filters, sorts, or facets on.
135
136 <Note>
137
138 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](!resources!/infrastructure-modules/search/index-definitions/modifiers#filterable), so you don't filter out draft products yourself. The field also uses [`retrievable(false)`](!resources!/infrastructure-modules/search/index-definitions/modifiers#retrievable), so the route filters on it without returning it in a hit.
139
140 </Note>
141
142 <Note title="Tip">
143
144 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](!resources!/infrastructure-modules/search/product-index-examples).
145
146 </Note>
147
148 ### 3. Allow the Index on the Store Search Route
149
150 Medusa exposes the [`POST /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.
151
152 To allow the `product` index, use the `configureStoreSearch` middleware in `src/api/middlewares.ts`:
153
154 ```ts title="src/api/middlewares.ts"
155 import {
156 configureStoreSearch,
157 defineMiddlewares,
158 } from "@medusajs/framework/http"
159
160 export default defineMiddlewares({
161 routes: [
162 {
163 matcher: "/store/search",
164 middlewares: [
165 configureStoreSearch({
166 allowed_indexes: {
167 product: true,
168 },
169 }),
170 ],
171 },
172 ],
173 })
174 ```
175
176 The route narrows a product index to published products in the publishable API key's sales channels, and you can narrow any index further with the middleware's `filters` option. Learn more in the [Store Search API Route guide](!resources!/infrastructure-modules/search/store-search).
177
178 ### 4. Push and Deploy Your Changes
179
180 The index definition and the middleware are part of your Medusa application's code, so Cloud picks them up on the next deployment.
181
182 Commit both files and push them to the branch that your environment tracks.
183
184 Cloud then [creates a deployment](../deployments/page.mdx#how-are-deployments-created) for the commit. Once it finishes, Medusa runs the index migrations, creates the physical `product` index, and fills it with your products.
185
186 You can follow the deployment's progress in the Cloud dashboard, as explained in [Find Environment Deployments](../deployments/page.mdx#find-environment-deployments).
187
188 ### 5. Confirm Products as Indexed
189
190 In your Medusa Admin dashboard, you can track the indexing of your products and other entities with the Search Module.
191
192 To view your indexes, go to Settings -> Search. Each registered index shows as a card with its name, the provider backing it, its status, and the fields it stores. Hover over a field to see its type and whether it's searchable, filterable, sortable, or facetable.
193
194 Find the `product` card and check its status, which is one of the following:
195
196 <Table>
197 <Table.Header>
198 <Table.Row>
199 <Table.HeaderCell>
200 Status
201 </Table.HeaderCell>
202 <Table.HeaderCell>
203 Description
204 </Table.HeaderCell>
205 </Table.Row>
206 </Table.Header>
207 <Table.Body>
208 <Table.Row>
209 <Table.Cell>
210 Pending
211 </Table.Cell>
212 <Table.Cell>
213 Medusa created the index, but nothing has filled it yet.
214 </Table.Cell>
215 </Table.Row>
216 <Table.Row>
217 <Table.Cell>
218 Building
219 </Table.Cell>
220 <Table.Cell>
221 A seed or reindex is in progress. Search results may be incomplete until it finishes.
222 </Table.Cell>
223 </Table.Row>
224 <Table.Row>
225 <Table.Cell>
226 Ready
227 </Table.Cell>
228 <Table.Cell>
229 The index is serving documents, so you can search your products.
230 </Table.Cell>
231 </Table.Row>
232 <Table.Row>
233 <Table.Cell>
234 Error
235 </Table.Cell>
236 <Table.Cell>
237 The last seed or reindex failed.
238 </Table.Cell>
239 </Table.Row>
240 </Table.Body>
241 </Table>
242
243 Once the `product` index is Ready, your products are searchable.
244
245 ### 6. Search Products
246
247 You can search your indexed products by sending a `POST` request to the [Store Search API route](!api!/store/search/search-indexes) with the index to search in the `entity` field.
248
249 For example, to search for products matching `sweatshirt`:
250
251 ```bash
252 MEDUSA_URL=https://your-project.medusajs.app
253
254 curl -X POST "$MEDUSA_URL/store/search" \
255 -H "x-publishable-api-key: pk_01KXR3J9J610DT161E2E4ZS6P1" \
256 -H "Content-Type: application/json" \
257 --data '{
258 "entity": "product",
259 "filters": { "q": "sweatshirt" },
260 "pagination": { "take": 20 }
261 }'
262 ```
263
264 The route accepts the `q` free-text query among the `filters`, along with pagination, sorting, facets, and the other options of a [search query](!docs!/learn/fundamentals/query/search).
265
266 You'll receive a JSON response like the following:
267
268 ```json
269 {
270 "results": [
271 {
272 "hits": [
273 {
274 "id": "prod_01KXR3J9J610DT161E2E4ZS6P1",
275 "score": 1.42,
276 "document": {
277 "id": "prod_01KXR3J9J610DT161E2E4ZS6P1",
278 "title": "Medusa Sweatshirt",
279 "description": "A classic sweatshirt, reimagined.",
280 "handle": "sweatshirt"
281 }
282 },
283 {
284 "id": "prod_01KXR3J9J610DT161E2E4ZS6P3",
285 "score": 1.18,
286 "document": {
287 "id": "prod_01KXR3J9J610DT161E2E4ZS6P3",
288 "title": "Medusa Zip-Up Sweatshirt",
289 "description": "A zip-up take on the classic sweatshirt.",
290 "handle": "zip-up-sweatshirt"
291 }
292 }
293 ],
294 "metadata": {
295 "skip": 0,
296 "take": 20,
297 "count": 2,
298 "query": "sweatshirt",
299 "processing_time_ms": 7
300 }
301 }
302 ]
303 }
304 ```
305
306 The route answers with one result per posted query, each holding the matching `hits` ranked by relevance and the query's `metadata`. You can also post a batch of queries at once in a `queries` array.
307
308 <Note title="Tip">
309
310 To build a full search experience on this endpoint, including facets, filters, and pagination, use the [InstantSearch adapter](!resources!/instantsearch) in your storefront.
311
312 </Note>
313
314 ---
315
316 ## Medusa Search Features
317
318 Medusa Search provides the following features:
319
320 - **[Full-text search](!docs!/learn/fundamentals/query/search)** with relevance ranking that respects the weight you set on each field.
321 - **[Typo tolerance](./settings/page.mdx#typo-tolerance)** on every searchable field, which you opt into per query.
322 - **[Semantic search](./semantic-search/page.mdx)** over embeddings, either ones you compute and store in your index, or ones Medusa Search creates for you from a text field.
323 - **[Flexible filters](!docs!/learn/fundamentals/query/search#apply-filters)** that support every operator the Search Module offers, so you can narrow results down to complex conditions, such as products of two brands that are in stock and priced under a certain amount.
324 - **[Facets](!docs!/learn/fundamentals/query/search#facets)** for values, ranges, and aggregate statistics, so a storefront can show counts per category or price bucket.
325 - **[Highlighting](!docs!/learn/fundamentals/query/search#highlighting)** of the matched terms in a hit's fields, so a storefront can mark what a result matched on.
326 - **[Sorting](!docs!/learn/fundamentals/query/search#sort-hits)** by any number of fields.
327 - **[Isolated indexes per environment](#search-indexes-per-environment)**, so a preview environment never writes to your production indexes.
328 - **[Settings of its own](./settings/page.mdx)** on an index, a field, and a query, such as the distance metric it compares embeddings with, or how current an index must be for a query.
329 - **[Search analytics](./analytics/page.mdx)** that show what customers searched for, how often searches came back empty, and how fast Medusa Search responded.
330
331 ---
332
333 ## Compare Medusa Search to Other Search Engines
334
335 If you're considering or already using another search engine, refer to [Compare Medusa Search to Other Search Engines](./comparison/page.mdx) for a summarized comparison of all of them. The following guides go into detail on one engine each, across setup, integration, search capabilities, and cost:
336
337 <CardList
338 itemsPerRow={3}
339 items={[
340 {
341 title: "PostgreSQL",
342 href: "/search/postgres",
343 },
344 {
345 title: "Algolia",
346 href: "/search/algolia",
347 },
348 {
349 title: "Meilisearch",
350 href: "/search/meilisearch",
351 },
352 ]}
353 />
354
355 ---
356
357 ## Search Indexes per Environment
358
359 Each Cloud environment has its own search indexes, so a change in one environment never affects another. Medusa Search scopes them by the environment's handle. Preview environments are the exception, since they can start from another environment's data.
360
361 ```mermaid
362 %%{init: {"flowchart": {"rankSpacing": 70, "subGraphTitleMargin": {"top": 8, "bottom": 8}}, "themeCSS": ".edgePaths { transform: translateY(-14px); }", "themeVariables": {"lineColor": "#A1A1AA", "clusterBorder": "#A1A1AA", "clusterBkg": "transparent", "nodeBorder": "#18181B", "nodeTextColor": "#52525B", "titleColor": "#52525B"}}}%%
363 flowchart LR
364 subgraph project["Project"]
365 direction LR
366 prod@{ icon: "medusa:terminal", label: "Production Environment", h: 64, w: 64 }
367 prodIndexes@{ icon: "medusa:search", label: "Production Indexes", h: 64, w: 64 }
368 staging@{ icon: "medusa:terminal", label: "Staging Environment", h: 64, w: 64 }
369 stagingIndexes@{ icon: "medusa:search", label: "Staging Indexes", h: 64, w: 64 }
370
371 prod <--> prodIndexes
372 staging <--> stagingIndexes
373 end
374
375 style project stroke-dasharray: 8
376 ```
377
378 ### Indexes in Preview Environments
379
380 A [preview environment](../environments/preview/page.mdx) can start from another environment's indexes. When you set a base environment in the [shared previews settings](../environments/preview/page.mdx#manage-shared-previews-settings), Cloud branches that environment's indexes into every preview it creates afterwards, the same way it replicates the base environment's database. A preview of a catalog with tens of thousands of products is then searchable as soon as it deploys, with no seed or reindex of your own.
381
382 The branch is a copy, so a write in the preview changes only the preview's indexes. Your base environment's indexes stay as they were.
383
384 Without a base environment for search, a preview starts with no indexes, and Medusa creates them as your application first writes to them.
385
386 ### Index Location and Latency
387
388 Medusa Search stores an environment's indexes in the same region as the environment's backend, so a search query never leaves the region. A query your Medusa application sends to Medusa Search takes single-digit milliseconds on the network, and a filtered query that also computes facets and hydrates its hits returns in around 30 milliseconds at the 95th percentile.
389
390 Two choices affect that number the most:
391
392 - The number of facets a query computes. Facets don't add to your search request count, but they do add to a query's latency, as explained in [How Medusa Search Counts Search Requests](#how-medusa-search-counts-search-requests).
393 - The `consistency` [query option](./settings/page.mdx#search-query-options). The default `strong` value waits for every write made before the query started, while `eventual` skips that check and returns faster.
394
395 ---
396
397 ## Start Building with Search
398
399 ### Use Search in Local Development
400
401 In local development, Medusa registers the [PostgreSQL Search Module Provider](!resources!/infrastructure-modules/search/providers/postgres) by default. This is the recommended approach for testing search functionality locally.
402
403 You can also set up your local Medusa instance to connect to Medusa Search with a connection string.
404
405 <Note title="Warning" type="warning">
406
407 The connection string gives you read and write access to your instances, so it's generally not recommended for local development. Only use it for testing purposes.
408
409 </Note>
410
411 To get the connection string for your local Medusa instance:
412
413 1. If you're in a different organization, [switch to the organization](../organizations/page.mdx#switch-organization).
414 2. Click **Projects** in the sidebar and select the project that contains the environment you want to view.
415 3. In the project's dashboard, click on the name of the environment. For example, "Production".
416 4. Click **Search** in the sidebar under the environment's section.
417 5. Toggle the "Search endpoint" setting. If the environment is Production, only the organization owner can toggle it.
418 6. Copy the connection string that appears after toggling the "Search endpoint" setting.
419
420 Set the connection string as the `MEDUSA_SEARCH_ENDPOINT` environment variable in your local project:
421
422 ```bash title=".env"
423 MEDUSA_SEARCH_ENDPOINT=https://env:key@search.medusajs.app
424 ```
425
426 Then, register the Search Module in `medusa-config.ts` with Medusa Search as its default provider, but only in development:
427
428 ```ts title="medusa-config.ts" highlights={[["7", "isDevelopment", "Only register Medusa Search in development."]]}
429 const isDevelopment = process.env.NODE_ENV === "development"
430
431 module.exports = defineConfig({
432 // ...
433 modules: [
434 // ...
435 ...(isDevelopment
436 ? [
437 {
438 resolve: "@medusajs/medusa/search",
439 options: {
440 default_provider: "search-medusa",
441 cloud: {
442 endpoint: process.env.MEDUSA_SEARCH_ENDPOINT,
443 },
444 },
445 },
446 ]
447 : []),
448 ],
449 })
450 ```
451
452 The endpoint carries the API key and the environment handle, so Medusa Search needs no other option. Your indexes then read from and write to your Cloud environment's search resources instead of your local PostgreSQL database.
453
454 <Note type="warning">
455
456 Keep the registration behind the development check. Cloud registers Medusa Search for you in deployed environments, and a registration that also runs there overrides Cloud's configuration.
457
458 </Note>
459
460 ### Search Custom Data Models
461
462 To search data other than products, including the custom data models of your own modules, you can declare an [index definition](!resources!/infrastructure-modules/search/index-definitions), then either allow the index on the `/store/search` API route or add an [API route](!docs!/learn/fundamentals/api-routes) of your own that searches it.
463
464 For example, to index a custom `brand` data model, create the file `src/search/brand.ts` with the following content:
465
466 ```ts title="src/search/brand.ts"
467 import {
468 defineSearchIndex,
469 graphConsume,
470 graphSeed,
471 search,
472 } from "@medusajs/framework/utils"
473
474 const fields = ["id", "name", "country", "created_at"]
475
476 export const brandIndex = defineSearchIndex({
477 name: "brand",
478 entity: "brand",
479 fields: search.define({
480 id: search.keyword().filterable(),
481 name: search.text().searchable({ weight: 3 }),
482 country: search.keyword().filterable().facetable(),
483 created_at: search.date().sortable(),
484 }),
485 events: [
486 "brand.created",
487 "brand.updated",
488 "brand.deleted",
489 ],
490 consume: graphConsume({ fields }),
491 seed: graphSeed({ fields }),
492 })
493 ```
494
495 Refer to the [Search Other Entities](!resources!/infrastructure-modules/search#search-other-entities) guide for more details.
496
497 ---
498
499 ## Monitor Search Analytics
500
501 An environment's **Search** page in the Cloud dashboard shows analytics for each of its indexes, including the searches that ran, the searches that returned no results, how fast Medusa Search responded, and the most searched terms.
502
503 Refer to the [Medusa Search Analytics](./analytics/page.mdx) guide for more details.
504
505 ---
506
507 ## Medusa Search Usage
508
509 Medusa Search is available on all Cloud plans, with the exception of [vector search](./semantic-search/page.mdx), which is available on the Scale and Enterprise plans. The number of search requests your Medusa application makes is a metered resource. Every plan includes an allowance of search requests, and requests beyond it count as [Flex Usage](../usage/page.mdx#what-is-flex-usage).
510
511 Medusa meters full-text and vector search requests separately, so each has its own allowance and price. A search that ranks hits with an embedding counts as a vector search request.
512
513 Refer to the [Usage](../usage/page.mdx) guide to learn how to monitor your organization's usage, and to the [Plans & Pricing](../pricing/page.mdx) guide for the allowance your plan includes.
514
515 ### How Medusa Search Counts Search Requests
516
517 Every `query.search` call counts as one search request, no matter how many [facets](!docs!/learn/fundamentals/query/search#facets) it computes, whether it returns a count, or how many hits it returns. Medusa Search runs the hits, the count, and every facet of a call as one search.
518
519 Writes count toward the same allowance. Every record that Medusa Search writes to an index, whether it's created, updated, or deleted, counts as one search request. So, a seed that indexes 50,000 products costs 50,000 requests, and a [reindex](#reindex-on-medusa-search) costs another one per record.
520
521 ---
522
523 ## Reindex on Medusa Search
524
525 Medusa rebuilds an index when its definition changes, and you can also rebuild one on demand. Admin users rebuild an index from Settings -> Search in the Medusa Admin dashboard, and you can rebuild one [in code with the Search Module's reindex method](!resources!/infrastructure-modules/search/reindexing).
526
527 ---
528
529 ## Frequently Asked Questions
530
531 ### Can I boost a field's value without sorting by it?
532
533 Not yet. Medusa Search ranks hits by the weight you set on each searchable field, so you influence relevance through [field weights](!docs!/learn/fundamentals/query/search#search-example) rather than through the value of an attribute. To put in-stock or fast-delivery products first, [sort](!docs!/learn/fundamentals/query/search#sort-hits) by the field, which overrides the relevance order, or run a second search for the products that don't qualify and append them to the first search's hits.
534
535 ### Which languages does Medusa Search stem?
536
537 Medusa Search stems eighteen languages, including Dutch and German. Stemming is off by default, so set a searchable field's `language` and `stemming` with the [`full_text_search` field option](./settings/page.mdx#set-a-fields-language) to turn it on. Refer to the [list of supported languages](./settings/page.mdx#supported-languages-in-medusa-search) for more details.
538
539 ### Can I query a Cloud environment's indexes from my local project?
540
541 Yes. Copy the environment's search endpoint from the Cloud dashboard and set it in your local project, as explained in [Use Search in Local Development](#use-search-in-local-development). The connection string carries read and write access to that environment's indexes, so use a preview or staging environment rather than production.