Raw
1 import { Note, TypeList } from "docs-ui"
2
3 export const metadata = {
4 title: `Medusa Search API Settings`,
5 keywords: [
6 "search",
7 "medusa search",
8 "settings",
9 "typo tolerance",
10 "provider options",
11 "search options",
12 ],
13 }
14
15 # {metadata.title}
16
17 In this guide, you'll learn about the settings and options that [Medusa Search](../page.mdx) supports on indexes, fields, and queries.
18
19 Aside from the fields and settings that every [index definition](!resources!/infrastructure-modules/search/index-definitions) declares, Medusa Search supports settings and options of its own.
20
21 <Note title="Tip">
22
23 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).
24
25 </Note>
26
27 ## Index Settings
28
29 Set the `settings` property of an index definition to configure how Medusa Search treats the whole index.
30
31 For example:
32
33 ```ts title="src/search/product.ts"
34 export const productIndex = defineSearchIndex({
35 name: "product",
36 entity: "product",
37 fields: search.define({
38 id: search.keyword().filterable(),
39 title: search.text().searchable(),
40 brand: search.keyword().filterable(),
41 }),
42 settings: {
43 distinct_attribute: "brand",
44 provider_options: {
45 "search-medusa": {
46 distance_metric: "cosine_distance",
47 },
48 },
49 },
50 async *seed({ container }) {
51 // ...
52 },
53 })
54 ```
55
56 The example declares two settings for the `product` index to control result deduplication and provider-specific options.
57
58 Medusa Search accepts the following index settings:
59
60 <TypeList
61 types={[
62 {
63 name: "distinct_attribute",
64 type: "`string`",
65 optional: true,
66 description: `The dotted path of a field that Medusa Search deduplicates hits by, returning at most one hit per distinct value. A query that passes its own \`distinct\` search option overrides it.`,
67 },
68 {
69 name: "provider_options",
70 type: "`object`",
71 optional: true,
72 description: `The settings of a specific search engine, keyed by the provider's identifier. Medusa Search reads the \`search-medusa\` entry and ignores the rest.`,
73 children: [
74 {
75 name: "search-medusa",
76 type: "`object`",
77 optional: true,
78 description: `The settings that only Medusa Search understands.`,
79 children: [
80 {
81 name: "distance_metric",
82 type: "`\"cosine_distance\"` \\| `\"euclidean_squared\"`",
83 optional: true,
84 description: `The metric that vector search uses to compare embeddings. \`cosine_distance\` compares the direction of two embeddings while ignoring their magnitude, which suits normalized embeddings from a text model. \`euclidean_squared\` compares their straight-line distance, so magnitude counts. A [vector field](#field-options) can override it for itself.`,
85 defaultValue: "cosine_distance",
86 },
87 ],
88 },
89 ],
90 },
91 {
92 name: "typo_tolerance",
93 type: "`object`",
94 optional: true,
95 description: `The thresholds Medusa Search applies when it matches a misspelled term, and the fields it must never fuzzy-match. Refer to [Typo Tolerance](#typo-tolerance) for an example.`,
96 children: [
97 {
98 name: "enabled",
99 type: "`boolean`",
100 optional: true,
101 description: `Whether Medusa Search builds a fuzzy index for the index's searchable fields. Set it to \`false\` to keep the index smaller when no query needs typo tolerance.`,
102 defaultValue: "true",
103 },
104 {
105 name: "min_word_size_for_one_typo",
106 type: "`number`",
107 optional: true,
108 description: `The shortest term length that tolerates a single typo.`,
109 defaultValue: "6",
110 },
111 {
112 name: "min_word_size_for_two_typos",
113 type: "`number`",
114 optional: true,
115 description: `The shortest term length that tolerates two typos. It can't be lower than \`min_word_size_for_one_typo\`.`,
116 defaultValue: "9",
117 },
118 {
119 name: "disabled_on_attributes",
120 type: "`string[]`",
121 optional: true,
122 description: `The dotted paths of the fields that must always match exactly, such as a SKU or a serial number where a single character changes the meaning.`,
123 defaultValue: "[]",
124 },
125 ],
126 },
127 ]}
128 sectionTitle="Index Settings"
129 openedLevel={1}
130 />
131
132 The example above sets `distinct_attribute` and `provider_options`. The section below covers `typo_tolerance`, which has a few properties of its own.
133
134 ### Typo Tolerance
135
136 Medusa Search matches misspelled terms with a fuzzy index that it builds on every searchable field by default, so an index tolerates typos without declaring any setting. A query is the opposite: it matches terms exactly until you opt in, as explained in [Opt a Query Into Typo Tolerance](#opt-a-query-into-typo-tolerance).
137
138 Set the `typo_tolerance` index setting to change the thresholds Medusa Search applies, to exempt a field, or to turn the fuzzy index off:
139
140 ```ts title="src/search/product.ts"
141 export const productIndex = defineSearchIndex({
142 name: "product",
143 entity: "product",
144 fields: search.define({
145 title: search.text().searchable(),
146 sku: search.keyword().searchable(),
147 }),
148 settings: {
149 typo_tolerance: {
150 min_word_size_for_one_typo: 6,
151 min_word_size_for_two_typos: 9,
152 disabled_on_attributes: ["sku"],
153 },
154 },
155 async *seed({ container }) {
156 // ...
157 },
158 })
159 ```
160
161 The example tolerates a typo on a term of six characters or more, two typos from nine characters, and never fuzzy-matches `sku`. Refer to [Index Settings](#index-settings) for every property the setting accepts.
162
163 #### Opt a Query Into Typo Tolerance
164
165 The setting only prepares the index. Every query matches terms exactly until you pass the [`typo_tolerance` search option](!docs!/learn/fundamentals/query/search#search-options):
166
167 ```ts
168 const { data } = await query.search({
169 entity: "product",
170 fields: ["id", "title"],
171 filters: { q: "sweatshrit" },
172 search_options: {
173 typo_tolerance: true,
174 },
175 })
176 ```
177
178 Medusa Search ranks a fuzzy match below every exact match, so enabling the option adds results rather than reordering the ones you already had.
179
180 <Note>
181
182 The option only widens a term match, so Medusa Search ignores it when the query passes no `q` filter, or when none of the fields it searches has a fuzzy index.
183
184 </Note>
185
186 ---
187
188 ## Field Options
189
190 Use a field's [`providerOptions()`](!resources!/infrastructure-modules/search/index-definitions/modifiers#provideroptions) modifier to configure how Medusa Search indexes that field.
191
192 For example:
193
194 ```ts title="src/search/product.ts"
195 export const productIndex = defineSearchIndex({
196 fields: search.define({
197 title: search.text().searchable().providerOptions({
198 "search-medusa": {
199 glob: true,
200 },
201 }),
202 // ...
203 }),
204 // ...
205 })
206 ```
207
208 Medusa Search reads the following field options:
209
210 <TypeList
211 types={[
212 {
213 name: "full_text_search",
214 type: "`boolean` \\| `object`",
215 optional: true,
216 description: `The full-text search configuration of a searchable field. Pass \`true\` to keep the defaults, or an object to change how Medusa Search tokenizes the field, such as its language. Refer to [Set a Field's Language](#set-a-fields-language) for an example.`,
217 defaultValue: "true for a searchable field, and unset otherwise",
218 children: [
219 {
220 name: "language",
221 type: "`string`",
222 optional: true,
223 description: `The language Medusa Search analyzes the field with, in lowercase. It decides the stemmer and the stop-word list the field uses, and it applies only when you also enable \`stemming\` or \`remove_stopwords\`. Refer to [Set a Field's Language](#set-a-fields-language) for the languages it accepts.`,
224 defaultValue: "english",
225 },
226 {
227 name: "stemming",
228 type: "`boolean`",
229 optional: true,
230 description: `Whether Medusa Search reduces a term to its stem, so a query for \`banken\` also matches \`bank\`. It stems the field in the language that \`language\` names, so set both together.`,
231 defaultValue: "false",
232 },
233 {
234 name: "remove_stopwords",
235 type: "`boolean`",
236 optional: true,
237 description: `Whether Medusa Search drops the language's common words, such as \`de\` in Dutch, from the field and from a query that searches it. Arabic, Greek, Romanian, Tamil, and Turkish have no stop-word list.`,
238 defaultValue: "false",
239 },
240 {
241 name: "ascii_folding",
242 type: "`boolean`",
243 optional: true,
244 description: `Whether Medusa Search strips accents, so a query for \`muller\` matches \`müller\`. Enable it for a language written in Latin script with diacritics, such as French or Spanish.`,
245 defaultValue: "false",
246 },
247 {
248 name: "case_sensitive",
249 type: "`boolean`",
250 optional: true,
251 description: `Whether Medusa Search keeps the case of a term, so a query only matches a term written the same way.`,
252 defaultValue: "false",
253 },
254 {
255 name: "max_token_length",
256 type: "`number`",
257 optional: true,
258 description: `The longest term Medusa Search indexes from the field, in bytes, between \`1\` and \`254\`. It drops anything longer, which keeps a field of long identifiers from growing the index.`,
259 defaultValue: "39",
260 },
261 ],
262 },
263 {
264 name: "glob",
265 type: "`boolean`",
266 optional: true,
267 description: `Whether Medusa Search can wildcard-match the field's exact value, which the \`$prefix\` and \`$like\` filters need. Medusa Search always omits it on the \`id\` field.`,
268 defaultValue: "true for a filterable, sortable, or facetable keyword field, and false for a text field",
269 },
270 {
271 name: "regex",
272 type: "`boolean`",
273 optional: true,
274 description: `Whether Medusa Search can match the field with a regular expression.`,
275 defaultValue: "false",
276 },
277 {
278 name: "ann",
279 type: "`boolean` \\| `object`",
280 optional: true,
281 description: `The approximate nearest neighbor configuration of a [vector field](!resources!/infrastructure-modules/search/index-definitions/fields#searchvector). Pass \`true\` to keep the defaults, or an object to override the index's metric for this field.`,
282 defaultValue: "true for a vector field, and unset otherwise",
283 children: [
284 {
285 name: "distance_metric",
286 type: "`\"cosine_distance\"` \\| `\"euclidean_squared\"`",
287 optional: true,
288 description: `The metric that vector search uses for this field. \`cosine_distance\` compares the direction of two embeddings while ignoring their magnitude, which suits normalized embeddings from a text model. \`euclidean_squared\` compares their straight-line distance, so magnitude counts.`,
289 defaultValue: "The index's `distance_metric` setting",
290 },
291 ],
292 },
293 ]}
294 sectionTitle="Field Options"
295 />
296
297 ### Set a Field's Language
298
299 Medusa Search matches a searchable field term by term, and it doesn't stem those terms until you ask it to. Set the field's `language` along with `stemming` so a query matches the other forms of a word, which matters for a catalog whose titles and descriptions aren't in English.
300
301 For example, to analyze a Dutch title and a German one:
302
303 ```ts title="src/search/product.ts"
304 export const productIndex = defineSearchIndex({
305 name: "product",
306 entity: "product",
307 fields: search.define({
308 id: search.keyword().filterable(),
309 title_nl: search.text().searchable().providerOptions({
310 "search-medusa": {
311 full_text_search: {
312 language: "dutch",
313 stemming: true,
314 remove_stopwords: true,
315 },
316 },
317 }),
318 title_de: search.text().searchable().providerOptions({
319 "search-medusa": {
320 full_text_search: {
321 language: "german",
322 stemming: true,
323 remove_stopwords: true,
324 },
325 },
326 }),
327 }),
328 async *seed({ container, catchup, last_key: lastKey }) {
329 const batchSize = 200
330 let cursor = lastKey
331
332 while (true) {
333 const { data: products } = await container.query
334 .graph({
335 entity: "product",
336 fields: [
337 "id",
338 "title",
339 "updated_at",
340 "deleted_at",
341 ],
342 filters: {
343 ...(catchup
344 ? { updated_at: { $gte: catchup.since } }
345 : {}),
346 ...(cursor ? { id: { $gt: cursor } } : {}),
347 },
348 pagination: {
349 take: batchSize,
350 order: { id: "ASC" },
351 },
352 withDeleted: !!catchup,
353 })
354
355 if (!products.length) {
356 return
357 }
358
359 const live = products.filter((p) => !p.deleted_at)
360 const gone = products.filter((p) => !!p.deleted_at)
361 const ids = live.map((p) => p.id)
362
363 const [nlTitles, deTitles] = await Promise.all(
364 ["nl-NL", "de-DE"].map(async (locale) => {
365 const { data } = await container.query.graph({
366 entity: "product",
367 fields: ["id", "title"],
368 filters: { id: ids },
369 }, { locale })
370
371 return new Map(
372 data.map((p) => [p.id, p.title])
373 )
374 })
375 )
376
377 yield [
378 ...(live.length
379 ? [{
380 action: "upsert" as const,
381 documents: live.map((product) => ({
382 id: product.id,
383 title_nl:
384 nlTitles.get(product.id) ?? product.title,
385 title_de:
386 deTitles.get(product.id) ?? product.title,
387 })),
388 }]
389 : []),
390 ...(gone.length
391 ? [{
392 action: "delete" as const,
393 filters: { id: gone.map((p) => p.id) },
394 }]
395 : []),
396 ]
397
398 if (products.length < batchSize) {
399 return
400 }
401
402 cursor = products[products.length - 1].id
403 }
404 },
405 })
406 ```
407
408 The `seed` function reads each page of products once per locale with Query's `locale` option, then writes each locale's title to its own field. It falls back to the product's stored title when a locale has no translation. It also pages by ID so an interrupted run resumes, and yields a `delete` write for the products the [catch-up pass](!resources!/infrastructure-modules/search/index-definitions#handle-the-catch-up-pass) finds deleted.
409
410 A Dutch query for `banken` now matches a product whose title holds `bank`, and a German query for `stühle` matches `Stuhl`.
411
412 ### Supported Languages in Medusa Search
413
414 Medusa Search stems the following languages:
415
416 - `arabic` (no stop-word list)
417 - `danish`
418 - `dutch`
419 - `english`
420 - `finnish`
421 - `french`
422 - `german`
423 - `greek` (no stop-word list)
424 - `hungarian`
425 - `italian`
426 - `norwegian`
427 - `portuguese`
428 - `romanian` (no stop-word list)
429 - `russian`
430 - `spanish`
431 - `swedish`
432 - `tamil` (no stop-word list)
433 - `turkish` (no stop-word list)
434
435 `remove_stopwords` has no effect on the languages marked above with `(no stop-word list)`. For a language written in Latin script with diacritics, such as French or Spanish, also set `ascii_folding` so a query without the accents still matches.
436
437 A field holds one language, since it holds one string. To search a catalog in more than one market, declare a field per locale as explained in [Search Text in Multiple Locales](!resources!/infrastructure-modules/search/index-definitions/fields#search-text-in-multiple-locales), then pass the `attributes_to_search_on` search option to search the field of the shopper's locale.
438
439 <Note>
440
441 Configure the language on the index's fields rather than per query. Medusa Search rejects a query that passes the `locales` search option.
442
443 </Note>
444
445 ---
446
447 ## Search Query Options
448
449 Pass `provider_options` to [query.search options](!docs!/learn/fundamentals/query/search#search-options) to change how Medusa Search runs that query.
450
451 For example:
452
453 ```ts
454 const { data } = await query.search({
455 entity: "product",
456 fields: ["id", "title"],
457 filters: { q: "sweatshirt" },
458 search_options: {
459 provider_options: {
460 "search-medusa": {
461 consistency: "eventual",
462 },
463 },
464 },
465 })
466 ```
467
468 Medusa Search reads one query option, `consistency`, which accepts the following values:
469
470 <TypeList
471 types={[
472 {
473 name: "consistency",
474 type: "`\"strong\"` \\| `\"eventual\"`",
475 optional: true,
476 description: `How current the index must be for this query. \`strong\` searches every write made before the query started, so the query reflects a write you made moments ago. \`eventual\` skips that check and can miss the latest writes, which makes the query faster.`,
477 defaultValue: "strong",
478 },
479 ]}
480 sectionTitle="Query Options"
481 />