1 import { Note } from "docs-ui"
2
3 export const metadata = {
4 title: `Semantic Search with Medusa Search`,
5 keywords: [
6 "search",
7 "medusa search",
8 "semantic search",
9 "vector search",
10 "embeddings",
11 "hybrid search",
12 ],
13 }
14
15 # {metadata.title}
16
17 In this guide, you'll learn how to use semantic search with [Medusa Search](../page.mdx), including how it creates the embeddings for you.
18
19 ## What is Semantic Search?
20
21 [Semantic search](!docs!/learn/fundamentals/query/search#vector-and-hybrid-search) ranks results by meaning rather than by matching terms, which needs an embedding of the text you search over. There are two ways to get those embeddings into your index:
22
23 - You compute them with an embedding model of your choice, such as OpenAI's, and yield them on a [vector field](!resources!/infrastructure-modules/search/index-definitions/fields#searchvector). A query then passes a pre-computed embedding as `search_options.vector.value`.
24 - Medusa Search computes them for you from a text field, which the rest of this guide covers. A query then passes raw text as `search_options.vector.query`.
25
26 <Note>
27
28 Vector search is available on the Scale and Enterprise plans. On the Scale plan, you compute the embeddings yourself, and each embedding can have at most 1536 dimensions. Embeddings that Medusa Search computes for you, which the rest of this guide covers, are available on the Enterprise plan only.
29
30 Refer to the [Plans & Pricing](../../pricing/page.mdx) guide for what your plan includes.
31
32 </Note>
33
34 ---
35
36 ## Add a Vector Field to an Index
37
38 To use semantic search, add a [vector field](!resources!/infrastructure-modules/search/index-definitions/fields#searchvector) to your index definition and chain the [`embed()`](!resources!/infrastructure-modules/search/index-definitions/modifiers#embed) modifier on it:
39
40 <Note title="Tip">
41
42 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](!resources!/infrastructure-modules/search/product-index-examples).
43
44 </Note>
45
46 ```ts title="src/search/product.ts"
47 export const productIndex = defineSearchIndex({
48 fields: search.define({
49 title: search.text().searchable(),
50 title_embedding: search.vector(1536).embed(),
51 // ...
52 }),
53 // ...
54 })
55 ```
56
57 In this example, `title_embedding` is a vector field that holds the embedding Medusa Search computes from the text you index on it, which is the product's title.
58
59 ### Index the Text to Embed
60
61 Your documents pass the text to embed as a string on `title_embedding`, and Medusa Search replaces it with the embedding it computes.
62
63 The [`graphSeed`](!resources!/infrastructure-modules/search/index-definitions#fill-the-index-from-query-with-graphseed) and [`graphConsume`](!resources!/infrastructure-modules/search/index-definitions#consume-events-from-query-with-graphconsume) helpers don't do that for you, since the vector field isn't a field of the entity they read. So, add a `transform` that copies the text onto the vector field, and share it between both helpers:
64
65 ```ts title="src/search/product.ts"
66 import {
67 defineSearchIndex,
68 graphConsume,
69 graphSeed,
70 search,
71 } from "@medusajs/framework/utils"
72
73 const source = {
74 fields: ["id", "title"],
75 transform: (products) => products.map((product) => ({
76 id: product.id,
77 title: product.title,
78 title_embedding: product.title,
79 })),
80 }
81
82 export const productIndex = defineSearchIndex({
83 name: "product",
84 entity: "product",
85 fields: search.define({
86 title: search.text().searchable(),
87 title_embedding: search.vector(1536).embed(),
88 // ...
89 }),
90 events: [
91 "product.created",
92 "product.updated",
93 "product.deleted",
94 ],
95 consume: graphConsume(source),
96 seed: graphSeed(source),
97 })
98 ```
99
100 Every document the index writes now carries the product's title on `title_embedding`, so Medusa Search embeds it both on the first seed and as products change.
101
102 If you write a [`seed` function](!resources!/infrastructure-modules/search/index-definitions#custom-seed-implementation) yourself, set the same field on the documents you yield:
103
104 ```ts title="src/search/product.ts"
105 export const productIndex = defineSearchIndex({
106 name: "product",
107 entity: "product",
108 fields: search.define({
109 title: search.text().searchable(),
110 title_embedding: search.vector(1536).embed(),
111 // ...
112 }),
113 async *seed({ container }) {
114 const { data: products } = await container.query.graph({
115 entity: "product",
116 fields: ["id", "title"],
117 // ...
118 })
119
120 yield [{
121 action: "upsert",
122 documents: products.map((product) => ({
123 id: product.id,
124 title: product.title,
125 title_embedding: product.title,
126 })),
127 }]
128 },
129 // ...
130 })
131 ```
132
133 ---
134
135 ## Run a Semantic Search
136
137 To run a semantic search, pass the text to search for as `search_options.vector.query` in `query.search`, and Medusa Search embeds it at query time:
138
139 ```ts
140 const { data } = await query.search({
141 entity: "product",
142 fields: ["id", "title"],
143 filters: { q: "comfortable running shoe" },
144 search_options: {
145 vector: {
146 field: "title_embedding",
147 query: "comfortable shoes for long runs",
148 semantic_ratio: 0.7,
149 },
150 },
151 })
152 ```
153
154 `semantic_ratio` balances the semantic score against the full-text score, where `0` is full-text only and `1` is semantic only. So this query blends both.
155
156 Without `embed` on the field, a query must pass a pre-computed embedding as `search_options.vector.value` instead, and Medusa Search rejects a query that passes `query`.
157
158 <Note>
159
160 Refer to [Let Medusa Search Create the Embedding](!resources!/infrastructure-modules/search/index-definitions/fields#let-medusa-search-create-the-embedding) for the full details of the modifier, including how it changes the documents your index holds.
161
162 </Note>
163
164 ---
165
166 ## Best Practices for What to Embed
167
168 An embedding only carries the meaning of the text you index on the vector field. So, the `transform` that builds that text decides how well semantic search ranks your results.
169
170 The examples in the previous sections embed the product's title alone, which is the smallest useful starting point. Use the following practices to build richer text to embed. Each example shows the index definition that builds the text, then the text a product ends up with.
171
172 ### Put the Most Defining Information First
173
174 An embedding weighs the start of the text more than its tail, so open with what identifies the entity, such as its name, type, category, and primary description. Leave supporting details, such as tags or materials, for the end, and leave out boilerplate that every product repeats.
175
176 For example:
177
178 ```ts title="src/search/product.ts"
179 const source = {
180 fields: ["id", "title", "type.value", "description"],
181 transform: (products) => products.map((product) => ({
182 id: product.id,
183 content_embedding: [
184 `Product: ${product.title}`,
185 `Type: ${product.type?.value}`,
186 `Description: ${product.description}`,
187 ].join("\n"),
188 // ...
189 })),
190 }
191
192 export const productIndex = defineSearchIndex({
193 name: "product",
194 entity: "product",
195 fields: search.define({
196 id: search.keyword().filterable(),
197 content_embedding: search.vector(1536).embed(),
198 // ...
199 }),
200 consume: graphConsume(source),
201 seed: graphSeed(source),
202 // ...
203 })
204 ```
205
206 In this example, the `transform` function constructs the `content_embedding` by concatenating the product's title, type, and description, ensuring that the most defining information appears first.
207
208 A product then carries the following text on `content_embedding`, which Medusa Search embeds:
209
210 ```text
211 Product: Aurora Lounge Chair
212 Type: Lounge Chair
213 Description: A low-slung lounge chair with a solid
214 oak frame and wool upholstery.
215 ```
216
217 Had the `transform` opened with a shipping notice that every product repeats, the identity of the product would compete with text that carries no meaning of its own.
218
219 ### Flatten Relevant Relations Into the Document
220
221 A shopper searches for a brand, a collection, or a material as readily as for a title, but those live on related entities. So, request the relations in the source's `fields`, then join their values into the text you embed.
222
223 ```ts title="src/search/product.ts"
224 const source = {
225 fields: [
226 "id",
227 "title",
228 "collection.title",
229 "tags.value",
230 "variants.material",
231 // ...
232 ],
233 transform: (products) => products.map((product) => ({
234 id: product.id,
235 content_embedding: [
236 `Product: ${product.title}`,
237 `Collection: ${product.collection?.title}`,
238 `Material: ${product.variants?.[0]?.material}`,
239 `Tags: ${product.tags
240 ?.map((tag) => tag.value)
241 .join(", ")}`,
242 ].join("\n"),
243 // ...
244 })),
245 }
246
247 export const productIndex = defineSearchIndex({
248 name: "product",
249 entity: "product",
250 fields: search.define({
251 id: search.keyword().filterable(),
252 content_embedding: search.vector(1536).embed(),
253 // ...
254 }),
255 consume: graphConsume(source),
256 seed: graphSeed(source),
257 // ...
258 })
259 ```
260
261 A product then carries the following text on `content_embedding`:
262
263 ```text
264 Product: Aurora Lounge Chair
265 Collection: Nordic Winter
266 Material: solid oak
267 Tags: mid-century, handmade
268 ```
269
270 ### Expand Terse Values Into Meaningful Context
271
272 A bare value, such as `oak`, gives the model little to work with. Label it and keep the words around it that a shopper would use.
273
274 ```ts title="src/search/product.ts"
275 const source = {
276 fields: ["id", "title", "variants.material", "length"],
277 transform: (products) => products.map((product) => ({
278 id: product.id,
279 content_embedding: [
280 `Product: ${product.title}`,
281 `Material: solid ${
282 product.variants?.[0]?.material
283 } frame with wool upholstery`,
284 `Dimensions: ${product.length} cm deep`,
285 ].join("\n"),
286 // ...
287 })),
288 }
289
290 export const productIndex = defineSearchIndex({
291 name: "product",
292 entity: "product",
293 fields: search.define({
294 id: search.keyword().filterable(),
295 content_embedding: search.vector(1536).embed(),
296 // ...
297 }),
298 consume: graphConsume(source),
299 seed: graphSeed(source),
300 // ...
301 })
302 ```
303
304 A product then carries the following text on `content_embedding`:
305
306 ```text
307 Product: Aurora Lounge Chair
308 Material: solid oak frame with wool upholstery
309 Dimensions: 82 cm deep
310 ```
311
312 Had the `transform` joined the raw values instead, the text would read `oak, 82`, which matches far fewer of the phrasings a shopper types.
313
314 ### Include Hierarchy
315
316 A category on its own drops the context that a shopper's phrasing carries. Walk the category's parent chain and join the full path, so the embedding holds the broader terms too.
317
318 ```ts title="src/search/product.ts"
319 const toCategoryPath = (category) => {
320 const names = []
321 let current = category
322
323 while (current) {
324 names.unshift(current.name)
325 current = current.parent_category
326 }
327
328 return names.join(" > ")
329 }
330
331 const source = {
332 fields: [
333 "id",
334 "title",
335 "categories.name",
336 "categories.parent_category.name",
337 // ...
338 ],
339 transform: (products) => products.map((product) => ({
340 id: product.id,
341 content_embedding: [
342 `Product: ${product.title}`,
343 `Category: ${product.categories
344 ?.map(toCategoryPath)
345 .join(", ")}`,
346 ].join("\n"),
347 // ...
348 })),
349 }
350
351 export const productIndex = defineSearchIndex({
352 name: "product",
353 entity: "product",
354 fields: search.define({
355 id: search.keyword().filterable(),
356 content_embedding: search.vector(1536).embed(),
357 // ...
358 }),
359 consume: graphConsume(source),
360 seed: graphSeed(source),
361 // ...
362 })
363 ```
364
365 A product then carries the following text on `content_embedding`:
366
367 ```text
368 Product: Aurora Lounge Chair
369 Category: Furniture > Seating > Lounge Chairs
370 ```
371
372 The path matches a shopper searching for seating, which the leaf category alone wouldn't.
373
374 ### Include User-Facing Attributes Only
375
376 An ID, a timestamp, or an internal status carries no meaning that a shopper would ever search for, and it dilutes the rest of the text. So, keep those out of the `transform`'s embedded text, and index them as their own fields when you filter on them.
377
378 ```ts title="src/search/product.ts"
379 const source = {
380 fields: ["id", "title", "status", "collection.title"],
381 transform: (products) => products.map((product) => ({
382 id: product.id,
383 status: product.status,
384 content_embedding: [
385 `Product: ${product.title}`,
386 `Collection: ${product.collection?.title}`,
387 ].join("\n"),
388 // ...
389 })),
390 }
391
392 export const productIndex = defineSearchIndex({
393 name: "product",
394 entity: "product",
395 fields: search.define({
396 id: search.keyword().filterable(),
397 status: search.keyword().filterable(),
398 content_embedding: search.vector(1536).embed(),
399 // ...
400 }),
401 consume: graphConsume(source),
402 seed: graphSeed(source),
403 // ...
404 })
405 ```
406
407 A product then carries the following text on `content_embedding`, while its ID and status stay on their own fields:
408
409 ```text
410 Product: Aurora Lounge Chair
411 Collection: Nordic Winter
412 ```
413
414 ### Keep Filters Outside the Embedding
415
416 A price range, an inventory count, a region, a permission, or a category ID is an exact constraint, and an embedding can't enforce it. So, keep those as structured fields with the [`filterable`](!resources!/infrastructure-modules/search/index-definitions/modifiers#filterable) modifier, and leave them out of the embedded text.
417
418 ```ts title="src/search/product.ts"
419 const source = {
420 fields: [
421 "id",
422 "title",
423 "categories.id",
424 "variants.calculated_price.calculated_amount",
425 "variants.inventory_quantity",
426 // ...
427 ],
428 transform: (products) => products.map((product) => ({
429 id: product.id,
430 price:
431 product.variants?.[0]?.calculated_price
432 ?.calculated_amount,
433 inventory_quantity:
434 product.variants?.[0]?.inventory_quantity,
435 category_ids: product.categories?.map(
436 (category) => category.id
437 ),
438 content_embedding: `Product: ${product.title}`,
439 // ...
440 })),
441 }
442
443 export const productIndex = defineSearchIndex({
444 name: "product",
445 entity: "product",
446 fields: search.define({
447 id: search.keyword().filterable(),
448 price: search.integer().filterable().sortable(),
449 inventory_quantity: search.integer().filterable(),
450 category_ids: search.keyword().array().filterable(),
451 content_embedding: search.vector(1536).embed(),
452 // ...
453 }),
454 consume: graphConsume(source),
455 seed: graphSeed(source),
456 // ...
457 })
458 ```
459
460 Your query then narrows the candidates with the filters and ranks what remains by meaning:
461
462 ```ts
463 const { data } = await query.search({
464 entity: "product",
465 fields: ["id", "title"],
466 filters: {
467 category_ids: ["pcat_01J8Z"],
468 price: { $lte: 50000 },
469 },
470 search_options: {
471 vector: {
472 field: "content_embedding",
473 query: "cozy chair for a reading corner",
474 semantic_ratio: 0.7,
475 },
476 },
477 })
478 ```
479
480 ### Keep Exact-Search Fields Alongside the Embedding
481
482 A shopper who types a SKU, a barcode, a model number, or an exact brand name expects that one record, and a semantic ranking dilutes it. So, keep those fields [`searchable`](!resources!/infrastructure-modules/search/index-definitions/modifiers#searchable) next to the vector field, and keep `semantic_ratio` below `1` so the full-text score still counts.
483
484 ```ts title="src/search/product.ts"
485 const source = {
486 fields: [
487 "id",
488 "title",
489 "variants.sku",
490 "variants.barcode",
491 // ...
492 ],
493 transform: (products) => products.map((product) => ({
494 id: product.id,
495 title: product.title,
496 sku: product.variants?.[0]?.sku,
497 barcode: product.variants?.[0]?.barcode,
498 content_embedding: `Product: ${product.title}`,
499 // ...
500 })),
501 }
502
503 export const productIndex = defineSearchIndex({
504 name: "product",
505 entity: "product",
506 fields: search.define({
507 id: search.keyword().filterable(),
508 title: search.text().searchable({ weight: 3 }),
509 status: search
510 .keyword()
511 .filterable()
512 .retrievable(false),
513 sku: search.keyword().searchable(),
514 barcode: search.keyword().searchable(),
515 content_embedding: search.vector(1536).embed(),
516 // ...
517 }),
518 consume: graphConsume(source),
519 seed: graphSeed(source),
520 // ...
521 })
522 ```
523
524 A shopper who types `AUR-LC-OAK-01` then matches that variant's SKU through the full-text score, while the same index still answers "cozy chair for a reading corner" through the embedding.
525
526 ### Full Example of Semantic Search Best Practices
527
528 The following index definition builds the embedded text from the relations it resolves, keeps the filters structured, and keeps the exact-search fields full-text:
529
530 ```ts title="src/search/product.ts"
531 import {
532 defineSearchIndex,
533 graphConsume,
534 graphSeed,
535 search,
536 } from "@medusajs/framework/utils"
537
538 const toCategoryPath = (category) => {
539 const names = []
540 let current = category
541
542 while (current) {
543 names.unshift(current.name)
544 current = current.parent_category
545 }
546
547 return names.join(" > ")
548 }
549
550 const buildEmbeddingText = (product) => {
551 const categories = product.categories?.map(toCategoryPath)
552 const materials = [
553 ...new Set(
554 product.variants
555 ?.map((variant) => variant.material)
556 .filter(Boolean)
557 ),
558 ]
559 const tags = product.tags?.map((tag) => tag.value)
560
561 return [
562 `Product: ${product.title}`,
563 product.type?.value && `Type: ${product.type.value}`,
564 categories?.length &&
565 `Category: ${categories.join(", ")}`,
566 product.collection?.title &&
567 `Collection: ${product.collection.title}`,
568 product.description &&
569 `Description: ${product.description}`,
570 materials.length &&
571 `Material: solid ${materials.join(", ")} frame`,
572 tags?.length && `Tags: ${tags.join(", ")}`,
573 ]
574 .filter(Boolean)
575 .join("\n")
576 }
577
578 const source = {
579 fields: [
580 "id",
581 "title",
582 "description",
583 "status",
584 "type.value",
585 "categories.id",
586 "categories.name",
587 "categories.parent_category.name",
588 "collection.title",
589 "tags.value",
590 "variants.sku",
591 "variants.barcode",
592 "variants.material",
593 ],
594 transform: (products) => {
595 return products.map((product) => ({
596 id: product.id,
597 title: product.title,
598 status: product.status,
599 sku: product.variants?.[0]?.sku,
600 barcode: product.variants?.[0]?.barcode,
601 category_ids: product.categories?.map(
602 (category) => category.id
603 ),
604 content_embedding: buildEmbeddingText(product),
605 }))
606 },
607 }
608
609 export const productIndex = defineSearchIndex({
610 name: "product",
611 entity: "product",
612 fields: search.define({
613 id: search.keyword().filterable(),
614 title: search.text().searchable({ weight: 3 }),
615 status: search
616 .keyword()
617 .filterable()
618 .retrievable(false),
619 sku: search.keyword().searchable(),
620 barcode: search.keyword().searchable(),
621 category_ids: search.keyword().array().filterable(),
622 content_embedding: search.vector(1536).embed(),
623 }),
624 events: [
625 "product.created",
626 "product.updated",
627 "product.deleted",
628 ],
629 consume: graphConsume(source),
630 seed: graphSeed(source),
631 })
632 ```
633
634 A product then carries the following text on `content_embedding`:
635
636 ```text
637 Product: Aurora Lounge Chair
638 Type: Lounge Chair
639 Category: Furniture > Seating > Lounge Chairs
640 Collection: Nordic Winter
641 Description: A low-slung lounge chair with a solid
642 oak frame and wool upholstery.
643 Material: solid oak frame
644 Tags: mid-century, handmade
645 ```
646
647 ---
648
649
650 ## Example: Build an AI Search Assistant
651
652 A chat-style assistant that answers a shopper in natural language and shows the products it found is two layers, and Medusa Search is the second one:
653
654 1. **The conversational layer.** A large language model of your choice turns the shopper's message into a search string, and writes the answer around the results it gets back. Medusa Search doesn't run this layer, so you call the model from your own API route with the provider and prompt you want.
655 2. **The retrieval layer.** Your API route passes the string the model produced to `query.search` as `search_options.vector.query`, and Medusa Search embeds it and ranks your products by meaning.
656
657 For example, create the API route `src/api/store/assistant/route.ts` with the following content:
658
659 export const assistantHighlights = [
660 ["22", "toSearchQuery", "Turn the shopper's message into a search string with your model."],
661 ["24", "search", "Search the products with the string the model produced."],
662 ["34", "query", "Medusa Search embeds the string at query time."],
663 ["35", "semantic_ratio", "Blend the semantic score with the full-text score."],
664 ]
665
666 ```ts title="src/api/store/assistant/route.ts" highlights={assistantHighlights} collapsibleLines="1-8" expandButtonLabel="Show Imports"
667 import {
668 MedusaRequest,
669 MedusaResponse,
670 } from "@medusajs/framework/http"
671 import {
672 ContainerRegistrationKeys,
673 } from "@medusajs/framework/utils"
674 import { toSearchQuery } from "../../../lib/assistant"
675
676 type AssistantRequest = {
677 message: string
678 }
679
680 export const POST = async (
681 req: MedusaRequest<AssistantRequest>,
682 res: MedusaResponse
683 ) => {
684 const query = req.scope.resolve(
685 ContainerRegistrationKeys.QUERY
686 )
687
688 const searchQuery = await toSearchQuery(req.body.message)
689
690 const { data } = await query.search({
691 entity: "product",
692 fields: ["id", "title", "handle", "thumbnail"],
693 filters: {
694 q: searchQuery,
695 status: "published",
696 },
697 search_options: {
698 vector: {
699 field: "title_embedding",
700 query: searchQuery,
701 semantic_ratio: 0.7,
702 },
703 },
704 })
705
706 res.json({
707 query: searchQuery,
708 products: data,
709 })
710 }
711 ```
712
713 `toSearchQuery` is the conversational layer, which you write yourself with your model provider's SDK. It receives the shopper's message, such as "something warm for a winter hike", and returns the string to search for, such as "insulated winter hiking jacket".
714
715 The route then returns the products Medusa Search ranked, so your storefront renders them next to the model's answer.
716
717 Keep the `semantic_ratio` below `1` so the search still respects the terms the shopper typed, such as a brand or a model number that a purely semantic ranking dilutes.
718
719 You can then call this API route from your storefront whenever a shopper sends a message to the assistant, ensuring that the conversational and retrieval layers work together seamlessly.