Raw
1 import { Prerequisites } from "docs-ui"
2
3 export const metadata = {
4 title: `Search Index Field Modifiers`,
5 }
6
7 # {metadata.title}
8
9 In this guide, you'll learn about the modifiers you can chain on a field in a [search index definition](../page.mdx).
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>
21
22 To learn about the types a field can hold, refer to the [Search Index Fields guide](../fields/page.mdx).
23
24 </Note>
25
26 <Note title="Tip">
27
28 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](../../product-index-examples/page.mdx).
29
30 </Note>
31
32 ## What is a Field Modifier?
33
34 A modifier declares what the engine can do with a field. For example, `searchable()` includes the field in free-text matching, while `filterable()` allows filtering on it.
35
36 You can chain multiple modifiers to a field. A modifier that doesn't apply to a type isn't available on it, so an invalid combination fails to compile instead of failing when your application starts. Refer to [Search Index Fields](../fields/page.mdx#define-index-fields) for the modifiers each type accepts.
37
38 <Note>
39
40 Adding, removing, or changing a modifier changes the definition's hash, which the Search Module treats as a schema change. Refer to the [Reindexing and Migrations guide](../../reindexing/page.mdx) to learn how it rebuilds the index.
41
42 </Note>
43
44 ---
45
46 ## searchable()
47
48 Includes the field in free-text matching, which is what the `q` filter passed to `query.search` searches against. Available on `keyword` and `text` fields.
49
50 <Note>
51
52 A field with no `searchable` modifier is never matched as free text, even when it holds a string.
53
54 </Note>
55
56 ```ts title="src/search/product.ts"
57 import {
58 defineSearchIndex,
59 search,
60 } from "@medusajs/framework/utils"
61
62 export const productIndex = defineSearchIndex({
63 fields: search.define({
64 title: search.text().searchable(),
65 // ...
66 }),
67 // ...
68 })
69 ```
70
71 Pass a `weight` to boost how much the field contributes to a result's relevance. A field with a higher weight ranks its matches above equally good matches in a lower-weighted field. The weight defaults to `1`, so `searchable()` and `searchable({ weight: 1 })` behave the same.
72
73 ```ts title="src/search/product.ts"
74 import {
75 defineSearchIndex,
76 search,
77 } from "@medusajs/framework/utils"
78
79 export const productIndex = defineSearchIndex({
80 fields: search.define({
81 title: search.text().searchable({ weight: 3 }),
82 description: search.text().searchable({ weight: 1 }),
83 // ...
84 }),
85 // ...
86 })
87 ```
88
89 In this example, a product matching a query in its title outranks one matching only in its description.
90
91 <Note title="How much a weight changes ranking depends on the provider">
92
93 - The [PostgreSQL provider](../../providers/postgres/page.mdx) maps the weight onto PostgreSQL's four relevance labels. A weight of `3` or more is the highest label, `2` the next, anything above `1` the next, and `1` or less the lowest. So there are four tiers, and raising a weight past `3` changes nothing.
94 - The [Medusa Search provider available for Cloud users](!cloud!/search) multiplies the field's relevance by the weight, so a weight of `5` does outrank a weight of `3`.
95
96 Refer to [Medusa Search vs PostgreSQL](!cloud!/search/postgres) for the other features providers treat differently.
97
98 </Note>
99
100 ---
101
102 ## filterable()
103
104 Allows [filters](!docs!/learn/fundamentals/query/search#apply-filters) on the field. Available on every type except `vector`.
105
106 ```ts title="src/search/product.ts"
107 import {
108 defineSearchIndex,
109 search,
110 } from "@medusajs/framework/utils"
111
112 export const productIndex = defineSearchIndex({
113 fields: search.define({
114 status: search.keyword().filterable(),
115 // ...
116 }),
117 // ...
118 })
119 ```
120
121 Filtering on a field without this modifier throws an error, since the Search Module validates the query against the definition before it reaches the provider.
122
123 ---
124
125 ## sortable()
126
127 Allows ordering results by the field through passing `pagination.order` to `query.search`. Available on every type except `vector`.
128
129 ```ts title="src/search/product.ts"
130 import {
131 defineSearchIndex,
132 search,
133 } from "@medusajs/framework/utils"
134
135 export const productIndex = defineSearchIndex({
136 fields: search.define({
137 created_at: search.date().sortable(),
138 // ...
139 }),
140 // ...
141 })
142 ```
143
144 ---
145
146 ## facetable()
147
148 Allows [facets](!docs!/learn/fundamentals/query/search#facets) on the field. A facet summarizes the matched documents by that field, which is what a storefront's filter sidebar shows. Available on every type except `vector`.
149
150 ```ts title="src/search/product.ts"
151 import {
152 defineSearchIndex,
153 search,
154 } from "@medusajs/framework/utils"
155
156 export const productIndex = defineSearchIndex({
157 fields: search.define({
158 brand: search.keyword().facetable(),
159 // ...
160 }),
161 // ...
162 })
163 ```
164
165 A query then requests the facet, and the result carries it in `search_result.facets`, keyed by field name:
166
167 ```ts
168 const { search_result } = await query.search({
169 entity: "product",
170 filters: { q: "shirt" },
171 search_options: { facets: ["brand"] },
172 })
173
174 console.log(search_result.facets)
175 ```
176
177 The shape of each entry depends on the kind of facet, as shown in [Facet Types](#facet-types).
178
179 ### Facet Types
180
181 By default, the facet type depends on the field's type:
182
183 - `integer`, `float`, and `date` fields default to `["range"]`.
184 - `stats` is never a default. Add it explicitly, since it's the least widely supported kind and implying it would make numeric fields unusable on a provider without aggregations.
185 - Every other type defaults to `["value"]`.
186
187 You can also pass `types` to `facetable()` to choose which kinds of facet the field allows. Only `integer`, `float`, and `date` accept the `types` option. For example:
188
189 ```ts title="src/search/product.ts"
190 import {
191 defineSearchIndex,
192 search,
193 } from "@medusajs/framework/utils"
194
195 export const productIndex = defineSearchIndex({
196 fields: search.define({
197 age: search.float().facetable({
198 types: ["value"],
199 }),
200 // ...
201 }),
202 // ...
203 })
204 ```
205
206 Each kind returns a different shape:
207
208 - `value`: the distinct values of the field and how many documents hold each one. It can also return `other_count` for documents falling outside the returned values.
209
210 ```json title="Example Value Facet"
211 {
212 "brand": {
213 "type": "value",
214 "values": [
215 { "value": "acme", "count": 12 },
216 { "value": "borg", "count": 4 }
217 ]
218 }
219 }
220 ```
221
222 - `range`: how many documents fall into each bucket the query defines. The result echoes each bucket's `key`, `from`, and `to` with its `count`. Only available on the `integer`, `float`, and `date` field types.
223
224 ```json title="Example Range Facet"
225 {
226 "min_price": {
227 "type": "range",
228 "ranges": [
229 { "key": "cheap", "to": 50, "count": 9 },
230 { "key": "mid", "from": 50, "to": 200, "count": 21 }
231 ]
232 }
233 }
234 ```
235
236 - `stats`: one aggregate summary of the field across the matched documents, rather than a breakdown. Only available on the `integer`, `float`, and `date` field types.
237
238 ```json title="Example Stats Facet"
239 {
240 "min_price": {
241 "type": "stats",
242 "min": 10,
243 "max": 450,
244 "avg": 92.5,
245 "sum": 3700,
246 "count": 40
247 }
248 }
249 ```
250
251 `avg` and `sum` are optional, since not every engine reports them.
252
253 <Note>
254
255 Requesting a facet kind the field doesn't allow throws an error. Passing a field name as a string, such as `facets: ["min_price"]`, requests a `value` facet, so it fails on a numeric field that only allows `range`.
256
257 </Note>
258
259 ---
260
261 ## retrievable()
262
263 Whether the field comes back on a hit. Most fields are retrievable by default, so you can omit this modifier unless you want to turn it off. Available on every type.
264
265 A `vector` field is the exception: it defaults to not retrievable, since a list of hundreds of numbers is rarely useful to the caller. Chain `retrievable()` on one to get the embedding back on every hit.
266
267 ```ts title="src/search/product.ts"
268 import {
269 defineSearchIndex,
270 search,
271 } from "@medusajs/framework/utils"
272
273 export const productIndex = defineSearchIndex({
274 fields: search.define({
275 search_blob: search.text().searchable().retrievable(false),
276 // ...
277 }),
278 // ...
279 })
280 ```
281
282 <Note title="Tip">
283
284 A field that isn't retrievable still counts toward matching. `query.search` reads this modifier to decide which requested fields the engine can serve, and which it must fetch with `query.graph`.
285
286 </Note>
287
288 <Note>
289
290 An `object` field's container is never retrievable, since the index only stores the sub-fields you declared. Request those sub-fields by their dotted path, such as `brand.name`, rather than requesting `brand`.
291
292 </Note>
293
294 ---
295
296 ## array()
297
298 Marks the field as holding a list of its type, rather than one value. Available on every type except `vector`.
299
300 ```ts title="src/search/product.ts"
301 import {
302 defineSearchIndex,
303 search,
304 } from "@medusajs/framework/utils"
305
306 export const productIndex = defineSearchIndex({
307 fields: search.define({
308 tags: search.keyword().array().filterable().facetable(),
309 // ...
310 }),
311 // ...
312 })
313 ```
314
315 A filter on an array field matches when any element matches. Faceting on one counts a document once per distinct element.
316
317 ---
318
319 ## embed()
320
321 Asks [Medusa Search](!cloud!/search) to create the field's embedding from text your documents pass on that same field, rather than having your documents supply the embedding. Available on a `vector` field only.
322
323 `embed()` takes no arguments:
324
325 ```ts title="src/search/product.ts"
326 import {
327 defineSearchIndex,
328 search,
329 } from "@medusajs/framework/utils"
330
331 export const productIndex = defineSearchIndex({
332 fields: search.define({
333 title: search.text().searchable(),
334 title_embedding: search.vector(1536).embed(),
335 // ...
336 }),
337 // ...
338 })
339 ```
340
341 With `embed`, your documents pass a string on the vector field, and a query can search it by passing raw text as `search_options.vector.query`. Refer to [Let Medusa Search Create the Embedding](../fields/page.mdx#let-medusa-search-create-the-embedding) for the full details.
342
343 <Note>
344
345 `embed` is a [Medusa Search](!cloud!/search/semantic-search) feature, available for Cloud projects on the Enterprise plan.
346
347 </Note>
348
349 ---
350
351 ## providerOptions()
352
353 Pass provider-specific options for one field, keyed by provider identifier. Use it to reach a feature the field definition doesn't model. Available on every type.
354
355 ```ts title="src/search/product.ts"
356 import {
357 defineSearchIndex,
358 search,
359 } from "@medusajs/framework/utils"
360
361 export const productIndex = defineSearchIndex({
362 fields: search.define({
363 title: search.text().searchable().providerOptions({
364 "search-medusa": {
365 glob: true,
366 },
367 }),
368 // ...
369 }),
370 // ...
371 })
372 ```
373
374 The options are passed to the targeted provider only, so you can pass different options to different providers for the same field.
375
376 An option only does something if the provider consumes it. A provider that doesn't read the `providerOptions` modifier ignores whatever you pass, so check the provider's documentation for the options it accepts. Of the providers Medusa ships, the [Medusa Search provider available for Cloud users](!cloud!/search) is the only one that reads them, and its [guide lists the full set](!cloud!/search/settings#field-options).
377
378 <Note title="Tip">
379
380 These options are separate from the options you set for a provider in `medusa-config.ts`. Those configure the provider itself, whereas these travel with the index definition and apply to one field.
381
382 </Note>