1 import { Prerequisites, TypeList } from "docs-ui"
2
3 export const metadata = {
4 title: `${pageNumber} Index Module`,
5 }
6
7 # {metadata.title}
8
9 In this chapter, you'll learn about the Index Module and how you can use it.
10
11 <Note type="soon" title="Experimental">
12
13 The Index Module is experimental and still in development, so it is subject to change. However, it's being actively used in the Medusa Admin dashboard and is increasingly stable for production use. Consider your application's tolerance for minor issues when deciding to implement it.
14
15 For multi-vendor setups with sales channel filtering needs, the Index Module provides the most efficient approach for filtering products by sales channels and other linked data models.
16
17 </Note>
18
19 ## What is the Index Module?
20
21 The Index Module is a tool to perform high-performance queries across modules, for example, to filter linked modules.
22
23 While modules share the same database by default, Medusa [isolates modules](../../modules/isolation/page.mdx) to allow using external data sources or different database types.
24
25 So, when you retrieve data across modules using Query, Medusa aggregates the data coming from different modules to create the end result. This approach limits your ability to filter data by linked modules. For example, you can't filter products (created in the Product Module) by their brand (created in the Brand Module).
26
27 The Index Module solves this problem by ingesting data into a central data store on application startup. The data store has a relational structure that enables efficient filtering of data ingested from different modules (and their data stores). So, when you retrieve data with the Index Module, you're retrieving it from the Index Module's data store, not the original data source.
28
29 ![Diagram showcasing how data is retrieved from the Index Module's data store](https://res.cloudinary.com/dza7lstvk/image/upload/v1747988533/Medusa%20Book/index-module_epurmt.jpg)
30
31 ### Ingested Data Models
32
33 By default, Medusa only ingests the `Product`, `ProductVariant`, `Price`, `PriceSet`, and `SalesChannel` data models into the Index Module's data store.
34
35 You can also ingest custom data models into the Index Module, as explained in the [How to Ingest Custom Data Models](#how-to-ingest-custom-data-models) section. Medusa will then ingest the custom and core data models into the Index Module's data store.
36
37 ---
38
39 ## How to Install the Index Module
40
41 To install the Index Module, run the following command in your Medusa project to install its package:
42
43 ```bash npm2yarn
44 npm install @medusajs/index
45 ```
46
47 Then, add the Index Module to your Medusa configuration in `medusa-config.ts`:
48
49 ```ts title="medusa-config.ts"
50 module.exports = defineConfig({
51 // ...
52 modules: [
53 // ...
54 {
55 resolve: "@medusajs/index",
56 },
57 ],
58 })
59 ```
60
61 Finally, run the migrations to create the necessary tables for the Index Module in your database:
62
63 ```bash npx2yarn
64 npx medusa db:migrate
65 ```
66
67 ### Ingest Data
68
69 The Index Module only ingests data when you start your Medusa server. So, to [ingest data models](#ingested-data-models), start the Medusa application:
70
71 ```bash npm2yarn
72 npm run dev
73 ```
74
75 The ingestion process may take a while if your product catalog is large. You'll see the following messages in the logs:
76
77 ```bash
78 info: [Index engine] Checking for index changes
79 info: [Index engine] Found 7 index changes that are either pending or processing
80 info: [Index engine] syncing entity 'ProductVariant'
81 info: [Index engine] syncing entity 'ProductVariant' done (+38.73ms)
82 info: [Index engine] syncing entity 'Product'
83 info: [Index engine] syncing entity 'Product' done (+18.21ms)
84 info: [Index engine] syncing entity 'LinkProductVariantPriceSet'
85 info: [Index engine] syncing entity 'LinkProductVariantPriceSet' done (+33.87ms)
86 info: [Index engine] syncing entity 'Price'
87 info: [Index engine] syncing entity 'Price' done (+22.79ms)
88 info: [Index engine] syncing entity 'PriceSet'
89 info: [Index engine] syncing entity 'PriceSet' done (+10.72ms)
90 info: [Index engine] syncing entity 'LinkProductSalesChannel'
91 info: [Index engine] syncing entity 'LinkProductSalesChannel' done (+11.45ms)
92 info: [Index engine] syncing entity 'SalesChannel'
93 info: [Index engine] syncing entity 'SalesChannel' done (+7.00ms)
94 ```
95
96 ### Update Index on Data Changes
97
98 The Index Module automatically updates its data store when data in the ingested data models change. So, you don't need to do anything to keep the data in sync.
99
100 <Note type="warning">
101
102 Incremental sync requires a Redis-based event bus. If you're using the in-memory event bus (the default when no `event-bus-redis` module is configured), the Index Module will not receive change events and the data store will only be updated on the next server startup. To enable incremental sync, configure the [Redis Event Module](!resources!/infrastructure-modules/event/redis).
103
104 </Note>
105
106 For example, if you create a new product, the Index Module will ingest it into its data store.
107
108 ### Enable Index Module Feature Flag
109
110 Since the Index Module is still experimental, the `/store/products` and `/admin/products` API routes will use the Index Module to retrieve products only if the Index Module's feature flag is enabled. By enabling the feature flag, you can filter products by their linked data models in these API routes.
111
112 To enable the Index Module's feature flag, add the following line to your `.env` file:
113
114 ```env
115 MEDUSA_FF_INDEX_ENGINE=true
116 ```
117
118 If you send a request to the `/store/products` or `/admin/products` API routes, you'll receive the following response:
119
120 ```json
121 {
122 "products": [
123 // ...
124 ],
125 "count": 2,
126 "estimate_count": 2,
127 "offset": 0,
128 "limit": 50
129 }
130 ```
131
132 Notice the `estimate_count` property, which is the estimated total number of products in the database. You'll learn more about it in the [Pagination](#apply-pagination-with-the-index-module) section.
133
134 ---
135
136 ## How to Use the Index Module
137
138 The Index Module adds a new `index` method to [Query](../page.mdx) and it has the same API as the `graph` method.
139
140 For example, to filter products by a sales channel ID:
141
142 export const basicHighlights = [
143 ["22", "id", "Filter products by their linked sales channel ID."]
144 ]
145
146 ```ts title="src/api/custom/products/route.ts" highlights={basicHighlights}
147 import {
148 MedusaRequest,
149 MedusaResponse,
150 } from "@medusajs/framework/http"
151 import {
152 ContainerRegistrationKeys,
153 } from "@medusajs/framework/utils"
154
155 export const GET = async (
156 req: MedusaRequest,
157 res: MedusaResponse
158 ) => {
159 const query = req.scope.resolve(
160 ContainerRegistrationKeys.QUERY
161 )
162
163 const { data: products } = await query.index({
164 entity: "product",
165 fields: ["id", "title", "sales_channels.id"],
166 filters: {
167 sales_channels: {
168 id: "sc_123",
169 },
170 },
171 })
172
173 res.json({ products })
174 }
175 ```
176
177 This will return all products that are linked to the sales channel with the ID `sc_123`.
178
179 The `index` method accepts an object with the same properties as the `graph` method's parameter:
180
181 - `entity`: The data model's name, as specified in the first parameter of the `model.define` method used for the data model's definition.
182 - `fields`: An array of the data model’s properties, relations, and linked data models to retrieve in the result.
183 - `filters`: An object with the filters to apply on the data model's properties, relations, and linked data models that are ingested.
184
185 ---
186
187 ## Select Specific Fields
188
189 Always list in `fields` the properties you need, rather than passing `*` or `{relation}.*` to retrieve every property.
190
191 Selecting specific fields keeps the query cheaper, the response smaller, and the cached result easier to invalidate. Retrieving all properties also loads relations and computed properties that you may not use.
192
193 For example, instead of retrieving all properties of a product and its brand:
194
195 ```ts title="Avoid"
196 const { data: products } = await query.index({
197 entity: "product",
198 fields: ["*", "brand.*"],
199 })
200 ```
201
202 Retrieve only the properties you use:
203
204 ```ts title="Prefer"
205 const { data: products } = await query.index({
206 entity: "product",
207 fields: [
208 "id",
209 "title",
210 "brand.id",
211 "brand.name",
212 ],
213 })
214 ```
215
216 ### Avoid Retrieving All Fields of Carts and Orders
217
218 Selecting specific fields matters most for the `cart` and `order` data models, along with their related data models, such as `return` and `order_change`.
219
220 These data models have computed total properties, such as `total`, `subtotal`, and `tax_total`. Medusa calculates these totals in the application, not the database, and it only calculates them when you request at least one total property, or when you pass `*`. Calculating them also loads relations, such as `items` and `shipping_methods` with their tax lines and adjustments, even if you don't use them.
221
222 So, whenever you retrieve carts or orders, either with the `index` method or with [Query's `graph` method](../page.mdx#select-specific-fields), request total properties only when you display them:
223
224 ```ts title="Prefer"
225 const { data: orders } = await query.index({
226 entity: "order",
227 fields: [
228 "id",
229 "display_id",
230 "status",
231 "currency_code",
232 // request totals only if you use them:
233 "total",
234 ],
235 })
236 ```
237
238 ---
239
240 ## How to Ingest Custom Data Models
241
242 You can ingest core and custom data models into the Index Module by defining a link between them and setting the `filterable` property in the link definition.
243
244 <Note>
245
246 Read-only links are not supported by the Index Module.
247
248 </Note>
249
250 For example, assuming you have a Brand Module with a Brand data model (as explained in the [Customizations](../../../customization/custom-features/module/page.mdx)), you can ingest it into the Index Module using the `filterable` property in its link definition to the `Product` data model:
251
252 export const filterableHighlights = [
253 ["12", "filterable", "Ingest Brand by setting its filterable properties."]
254 ]
255
256 ```ts title="src/links/product-brand.ts" highlights={filterableHighlights}
257 import BrandModule from "../modules/brand"
258 import ProductModule from "@medusajs/medusa/product"
259 import { defineLink } from "@medusajs/framework/utils"
260
261 export default defineLink(
262 {
263 linkable: ProductModule.linkable.product,
264 isList: true,
265 },
266 {
267 linkable: BrandModule.linkable.brand,
268 filterable: ["id", "name"],
269 }
270 )
271 ```
272
273 The `filterable` property is an array of property names in the data model that can be filtered using the `index` method. When the `filterable` property is set, the Index Module will ingest into its data store the custom data model.
274
275 But first, you must run the migrations to sync the link:
276
277 ```bash npx2yarn
278 npx medusa db:migrate
279 ```
280
281 Then, start the Medusa application:
282
283 ```bash npm2yarn
284 npm run dev
285 ```
286
287 You'll then see the following message in the logs:
288
289 ```bash
290 info: [Index engine] syncing entity 'LinkProductProductBrandBrand'
291 info: [Index engine] syncing entity 'LinkProductProductBrandBrand' done (+3.64ms)
292 info: [Index engine] syncing entity 'Brand'
293 info: [Index engine] syncing entity 'Brand' done (+0.99ms)
294 ```
295
296 You can now filter products by their brand, and vice versa. For example:
297
298 ```ts title="src/api/custom/products/route.ts"
299 import {
300 MedusaRequest,
301 MedusaResponse,
302 } from "@medusajs/framework/http"
303 import {
304 ContainerRegistrationKeys,
305 } from "@medusajs/framework/utils"
306
307 export const GET = async (
308 req: MedusaRequest,
309 res: MedusaResponse
310 ) => {
311 const query = req.scope.resolve(
312 ContainerRegistrationKeys.QUERY
313 )
314
315 const { data: products } = await query.index({
316 entity: "product",
317 fields: ["id", "title", "brand.id", "brand.name"],
318 filters: {
319 brand: {
320 name: "Acme",
321 },
322 },
323 })
324
325 res.json({ products })
326 }
327 ```
328
329 This will return all products that are linked to the brand with the name `Acme`. For example:
330
331 ```json title="Example Response"
332 {
333 "products": [
334 {
335 "id": "prod_123",
336 "title": "Shirt",
337 "brand": {
338 "id": "brand_123",
339 "name": "Acme"
340 }
341 }
342 ]
343 }
344 ```
345
346 ---
347
348 ## Trigger Index Reingestion
349
350 <Note>
351
352 The Index API routes are available from [Medusa v2.11.2](https://github.com/medusajs/medusa/releases/tag/v2.11.2).
353
354 </Note>
355
356 Medusa provides API routes to view and trigger index reingestion or syncing. This is useful if you want to reingest data manually, for example, after a large data import.
357
358 Refer to the [Index API Reference](!api!/admin/index) for more information about the available API routes and how to use them.
359
360 ---
361
362 ## Apply Pagination with the Index Module
363
364 Similar to Query's `graph` method, the Index Module accepts a `pagination` object to paginate the results.
365
366 For example, to paginate the products and retrieve `10` products per page:
367
368 export const paginationHighlights = [
369 ["19", "metadata", "Pagination details."],
370 ["28", "pagination", "Apply pagination to the retrieved records."]
371 ]
372
373 ```ts title="src/api/custom/products/route.ts" highlights={paginationHighlights}
374 import {
375 MedusaRequest,
376 MedusaResponse,
377 } from "@medusajs/framework/http"
378 import {
379 ContainerRegistrationKeys,
380 } from "@medusajs/framework/utils"
381
382 export const GET = async (
383 req: MedusaRequest,
384 res: MedusaResponse
385 ) => {
386 const query = req.scope.resolve(
387 ContainerRegistrationKeys.QUERY
388 )
389
390 const {
391 data: products,
392 metadata,
393 } = await query.index({
394 entity: "product",
395 fields: ["id", "title", "brand.id", "brand.name"],
396 filters: {
397 brand: {
398 name: "Acme",
399 },
400 },
401 pagination: {
402 take: 10,
403 skip: 0,
404 },
405 })
406
407 res.json({ products, ...metadata })
408 }
409 ```
410
411 The `pagination` object accepts the following properties:
412
413 - `take`: The number of items to retrieve per page.
414 - `skip`: The number of items to skip before retrieving the items.
415
416 When the `pagination` property is set, the `index` method will also return a `metadata` property. `metadata` is an object with the following properties:
417
418 - `skip`: The number of items skipped.
419 - `take`: The number of items retrieved.
420 - `estimate_count`: The estimated total number of items in the database matching the query. This value is retrieved from the PostgreSQL query planner rather than using a `COUNT` query, so it may not be accurate for smaller data sets.
421
422 For example, this is the response returned by the above API route:
423
424 ```json title="Example Response"
425 {
426 "products": [
427 // ...
428 ],
429 "skip": 0,
430 "take": 10,
431 "estimate_count": 100
432 }
433 ```
434
435 ---
436
437 ## Cache Index Module Results
438
439 <Prerequisites
440 items={[
441 {
442 text: "Caching Module installed with a provider.",
443 link: "!resources!/infrastructure-modules/caching#install-the-caching-module"
444 }
445 ]}
446 />
447
448 <Note>
449
450 Caching options are available from [Medusa v2.11.0](https://github.com/medusajs/medusa/releases/tag/v2.11.0).
451
452 </Note>
453
454 You can cache Index Module results to improve performance and reduce database load. To do that, you can pass a `cache` property in the second parameter of the `query.index` method.
455
456 For example, to enable caching for a query:
457
458 ```ts highlights={[["6", "enable", "Enable caching for this query."]]}
459 const { data: products } = await query.index({
460 entity: "product",
461 fields: ["id", "title"],
462 }, {
463 cache: {
464 enable: true,
465 },
466 })
467 ```
468
469 In this example, you enable caching of the query's results. The next time the same query is executed, the results are returned from the cache instead of querying the database.
470
471 <Note title="Tip">
472
473 Refer to the [Caching Module documentation](!resources!/infrastructure-modules/caching/concepts#caching-best-practices) for best practices on caching.
474
475 </Note>
476
477 ### Cache Properties
478
479 `cache` is an object that accepts the following properties:
480
481 <TypeList
482 types={[
483 {
484 type: "`boolean` \| `((args: any[]) => boolean \| undefined)`",
485 name: "enable",
486 description: "Whether to enable caching of query results. If a function is passed, it receives as a parameter the `query.index` parameters, and returns a boolean indicating whether caching is enabled.",
487 defaultValue: "false"
488 },
489 {
490 type: "`string` \| `((args: any[], cachingModule: ICachingModuleService) => string \| Promise<string>)`",
491 name: "key",
492 description: "The key to cache the query results with. If no key is provided, the Caching Module will generate the key from the `query.index` parameters.\n\nIf a function is passed, it receives the following properties:\n\n1. The parameters passed to `query.index`.\n\n2. The [Caching Module's service](!resources!/references/caching-service), which you can use to perform caching operations.\n\nThe function must return a string indicating the cache key.",
493 },
494 {
495 type: "`string[]` \| `((args: any[]) => string[] \| undefined)`",
496 name: "tags",
497 description: "The tags to associate with the cached results. Tags are useful to group related items. If no tag is provided, the Caching Module will generate relevant tags based on the entity and its retrieved relations. If tags are provided, they replace the automatically computed tags unless `computeAutomaticTags` is also set.\n\nIf a function is passed, it receives as a parameter the `query.index` parameters, and returns an array of strings indicating the cache tags."
498 },
499 {
500 type: "`boolean`",
501 name: "computeAutomaticTags",
502 description: "Whether the automatically computed tags should be applied alongside the ones given in `tags`, rather than `tags` replacing them. Pass custom tags for what the automatic computation cannot see, such as link table rows, relations selected without their `id`, or entities that affect the result without appearing in it, and enable this option to avoid restating every entity the result already exposes.\n\nHas no effect when `tags` is omitted, since tags are computed automatically in that case.",
503 defaultValue: "`false`"
504 },
505 {
506 type: "`number` \| `((args: any[]) => number \| undefined)`",
507 name: "ttl",
508 description: "The time-to-live (TTL) for the cached results, in seconds. If no TTL is provided, the Caching Module Provider will receive the [configured TTL of the Caching Module](!resources!/infrastructure-modules/caching#caching-module-options), or it will use its own default value.\n\nIf a function is passed, it receives as a parameter the `query.index` parameters, and returns a number indicating the TTL.",
509 },
510 {
511 type: "`boolean` \| `((args: any[]) => boolean \| undefined)`",
512 name: "autoInvalidate",
513 description: "Whether to automatically invalidate the cached data when it expires.\n\nIf a function is passed, it receives as a parameter the `query.index` parameters, and returns a boolean indicating whether to automatically invalidate the cache.",
514 defaultValue: "`true`"
515 },
516 {
517 type: "`string[]` \| `((args: any[]) => string[] \| undefined)`",
518 name: "providers",
519 description: "The IDs of the providers to use for caching. If not provided, the [default Caching Module Provider](!resources!/infrastructure-modules/caching/providers#default-caching-module-provider) is used. If multiple providers are passed, the cache is stored and retrieved in those providers in order.\n\nIf a function is passed, it receives as a parameter the `query.index` parameters, and return an array of strings indicating the providers to use."
520 }
521 ]}
522 sectionTitle="Cache Properties"
523 />
524
525 ### Set Cache Key
526
527 By default, the Caching Module generates a cache key for a query based on the arguments passed to `query.index`. The cache key is a unique key that the cached result is stored with.
528
529 Alternatively, you can set a custom cache key for a query. This is useful if you want to manage invalidating the cache manually.
530
531 To set the cache key of a query, pass the `cache.key` option:
532
533 ```ts highlights={[["7"]]}
534 const { data: products } = await query.index({
535 entity: "product",
536 fields: ["id", "title"],
537 }, {
538 cache: {
539 enable: true,
540 key: "products-123456",
541 // to disable auto invalidation:
542 // autoInvalidate: false,
543 },
544 })
545 ```
546
547 In the example above, you cache the query results with the `products-123456` key.
548
549 <Note>
550
551 You should generate cache keys with the Caching Module service's [computeKey method](!resources!/references/caching-service#computeKey) to ensure that the key is unique and follows best practices.
552
553 </Note>
554
555 You can also pass a function as the value of `cache.key`:
556
557 ```ts highlights={[["7"], ["8"], ["9"], ["10"], ["11"]]}
558 const { data: products } = await query.index({
559 entity: "product",
560 fields: ["id", "title"],
561 }, {
562 cache: {
563 enable: true,
564 key: async (args, cachingModuleService) => {
565 return await cachingModuleService.computeKey({
566 ...args,
567 prefix: "products",
568 })
569 },
570 },
571 })
572 ```
573
574 In the example above, you pass a function to `key`. It accepts two parameters:
575
576 1. The arguments of `query.index` passed as an array.
577 2. The [Caching Module's service](!resources!/references/caching-service).
578
579 You generate the key using the [computeKey method of the Caching Module's service](!resources!/references/caching-service#computeKey). The query results will be cached with that key.
580
581 ### Set Cache Tags
582
583 By default, the Caching Module generates relevant tags for a query based on the entity and its retrieved relations. Cache tags are useful to group related items together, allowing you to [retrieve](!resources!/references/caching-service#get) or [invalidate](!resources!/references/caching-service#clear) items by common tags.
584
585 Alternatively, you can set the cache tags of a query manually. This is useful if you want to manage invalidating the cache manually, or you want to group related cached items with custom tags.
586
587 To set the cache tags of a query, pass the `cache.tags` option:
588
589 ```ts highlights={[["7"]]}
590 const { data: products } = await query.index({
591 entity: "product",
592 fields: ["id", "title"],
593 }, {
594 cache: {
595 enable: true,
596 tags: ["Product:list:*"],
597 },
598 })
599 ```
600
601 In the example above, you cache the query results with the `Product:list:*` tag.
602
603 <Note>
604
605 The cache tag must follow the [Caching Tags Convention](!resources!/infrastructure-modules/caching/concepts#caching-tags-convention) to be automatically invalidated.
606
607 </Note>
608
609 You can also pass a function as the value of `cache.tags`:
610
611 ```ts highlights={[["7"], ["8"], ["9"], ["10"], ["11"], ["12"], ["13"]]}
612 const { data: products } = await query.index({
613 entity: "product",
614 fields: ["id", "title"],
615 }, {
616 cache: {
617 enable: true,
618 tags: (args) => {
619 const collectionId = args[0].filter?.collection_id
620 return [
621 ...args,
622 collectionId ? `ProductCollection:${collectionId}` : undefined,
623 ]
624 },
625 },
626 })
627 ```
628
629 In the example above, you use a function to determine the cache tags. The function accepts the arguments passed to `query.index` as an array.
630
631 Then, you add the `ProductCollection:id` tag if `collection_id` is passed in the query filters.
632
633 ### Set TTL
634
635 By default, the Caching Module will pass the [configured time-to-live (TTL)](!resources!/infrastructure-modules/caching#caching-module-options) to the Caching Module Provider when caching data. The Caching Module Provider may also have its own default TTL. The cache isn't invalidated until the configured TTL passes.
636
637 Alternatively, you can set a custom TTL for a query. This is useful if you want the cached data to be invalidated sooner or later than the default TTL.
638
639 To set the TTL of the cached query results to a custom value, use the `cache.ttl` option:
640
641 ```ts highlights={[["7"]]}
642 const { data: products } = await query.index({
643 entity: "product",
644 fields: ["id", "title"],
645 }, {
646 cache: {
647 enable: true,
648 ttl: 100, // 100 seconds
649 },
650 })
651 ```
652
653 In the example above, you set the TTL of the cached query result to `100` seconds. It will be invalidated after that time.
654
655 You can also pass a function as the value of `cache.ttl`:
656
657 ```ts highlights={[["10"], ["11"], ["12"]]}
658 const { data: products } = await query.index({
659 entity: "product",
660 fields: ["id", "title"],
661 filters: {
662 id: "prod_123",
663 },
664 }, {
665 cache: {
666 enable: true,
667 ttl: (args) => {
668 return args[0].filters.id === "test" ? 10 : 100
669 },
670 },
671 })
672 ```
673
674 In the example above, you use a function to determine the TTL. The function accepts the arguments passed to `query.index` as an array.
675
676 Then, you set the TTL based on the ID of the product passed in the filters.
677
678 ### Set Auto Invalidation
679
680 By default, the Caching Module automatically invalidates cached query results when the data changes.
681
682 Alternatively, you can disable auto invalidation of cached query results. This is useful if you want to manage invalidating the cache manually.
683
684 To configure invalidation behavior, use the `cache.autoInvalidate` option:
685
686 ```ts highlights={[["7"]]}
687 const { data: products } = await query.index({
688 entity: "product",
689 fields: ["id", "title"],
690 }, {
691 cache: {
692 enable: true,
693 autoInvalidate: false,
694 },
695 })
696 ```
697
698 In this example, you disable auto invalidation of the query result. You must [invalidate](!resources!/references/caching-service#clear) the cached data manually.
699
700 You can also pass a function as the value of `cache.autoInvalidate`:
701
702 ```ts highlights={[["7"], ["8"], ["9"]]}
703 const { data: products } = await query.index({
704 entity: "product",
705 fields: ["id", "title"],
706 }, {
707 cache: {
708 enable: true,
709 autoInvalidate: (args) => {
710 return !args[0].fields.includes("custom_field")
711 },
712 },
713 })
714 ```
715
716 In the example above, you use a function to determine whether to invalidate the cached query result automatically. The function accepts the arguments passed to `query.index` as an array.
717
718 Then, you enable auto-invalidation only if the `fields` passed to `query.index` don't include `custom_fields`. If this disables auto-invalidation, you must [invalidate](!resources!/references/caching-service#clear) the cached data manually.
719
720 <Note title="Tip">
721
722 Learn more about automatic invalidation in the [Caching Module documentation](!resources!/infrastructure-modules/caching/concepts#automatic-cache-invalidation).
723
724 </Note>
725
726 ### Set Caching Provider
727
728 By default, the Caching Module uses the [default Caching Module Provider](!resources!/infrastructure-modules/caching/providers#default-caching-module-provider) to cache a query.
729
730 Alternatively, you can set the caching provider to use for a query. This is useful if you have multiple caching providers configured, and you want to use a specific one for a query, or you want to specify a fallback provider.
731
732 To configure the caching providers, use the `cache.providers` option:
733
734 ```ts highlights={[["7"]]}
735 const { data: products } = await query.index({
736 entity: "product",
737 fields: ["id", "title"],
738 }, {
739 cache: {
740 enable: true,
741 providers: ["caching-redis", "caching-memcached"],
742 },
743 })
744 ```
745
746 In the example above, you specify the providers with ID `caching-redis` and `caching-memcached` to cache the query results. These IDs must match the IDs of the providers in `medusa-config.ts`.
747
748 When you pass multiple providers, the cache is stored and retrieved in those providers in order.
749
750 You can also pass a function as the value of `cache.providers`:
751
752 ```ts highlights={[["10"], ["11"], ["12"]]}
753 const { data: products } = await query.index({
754 entity: "product",
755 fields: ["id", "title"],
756 filters: {
757 id: "prod_123",
758 },
759 }, {
760 cache: {
761 enable: true,
762 providers: (args) => {
763 return args[0].filters.id === "test" ? ["caching-redis"] : ["caching-memcached"]
764 },
765 },
766 })
767 ```
768
769 In the example above, you use a function to determine the caching providers. The function accepts the arguments passed to `query.index` as an array.
770
771 Then, you set the providers based on the ID of the product passed in the filters.
772
773 ---
774
775 ## index Method Usage Examples
776
777 The following sections show examples of how to use the `index` method in different scenarios.
778
779 ### Retrieve Linked Data Models
780
781 Retrieve the records of a linked data model by passing in `fields` the data model's name suffixed with the `.{field}` notation, where `{field}` is the property of the linked data model you want to retrieve.
782
783 For example:
784
785 ```ts title="src/api/custom/products/route.ts" highlights={[["3"]]}
786 const { data: products } = await query.index({
787 entity: "product",
788 fields: ["id", "title", "brand.id", "brand.name"],
789 })
790 ```
791
792 This will return all products with their linked brand data model.
793
794 ### Use Advanced Filters
795
796 When setting filters on properties, you can use advanced filters like `$ne` and `$gt`. These are the same advanced filters accepted by the [listing methods generated by the Service Factory](!resources!/service-factory-reference/tips/filtering).
797
798 For example, to only retrieve products linked to a brand:
799
800 ```ts title="src/api/custom/products/route.ts" highlights={[["9"]]}
801 const {
802 data: products,
803 } = await query.index({
804 entity: "product",
805 fields: ["id", "title", "brand.id", "brand.name"],
806 filters: {
807 brand: {
808 id: {
809 $ne: null,
810 },
811 },
812 },
813 })
814 ```
815
816 You use the `$ne` operator to filter products that are linked to a brand.
817
818 Another example is to retrieve products whose brand name starts with `Acme`:
819
820 ```ts title="src/api/custom/products/route.ts" highlights={[["9"]]}
821 const {
822 data: products,
823 } = await query.index({
824 entity: "product",
825 fields: ["id", "title", "brand.id", "brand.name"],
826 filters: {
827 brand: {
828 name: {
829 $like: "Acme%",
830 },
831 },
832 },
833 })
834 ```
835
836 This will return all products whose brand name starts with `Acme`.
837
838 ### Use Request Query Configurations
839
840 API routes using the `graph` method can configure default [query configurations](../page.mdx#request-query-configurations), such as which fields to retrieve, while also allowing clients to override them using query parameters.
841
842 The `index` method supports the same configurations. For example, if you add the request query configuration as explained in the [Query documentation](../page.mdx#request-query-configurations), you can use those configurations in the `index` method:
843
844 ```ts title="src/api/custom/products/route.ts" highlights={[["22"]]}
845 import {
846 MedusaRequest,
847 MedusaResponse,
848 } from "@medusajs/framework/http"
849 import {
850 ContainerRegistrationKeys,
851 } from "@medusajs/framework/utils"
852
853 export const GET = async (
854 req: MedusaRequest,
855 res: MedusaResponse
856 ) => {
857 const query = req.scope.resolve(
858 ContainerRegistrationKeys.QUERY
859 )
860
861 const {
862 data: products,
863 metadata,
864 } = await query.index({
865 entity: "product",
866 ...req.queryConfig,
867 filters: {
868 brand: {
869 name: "Acme",
870 },
871 },
872 })
873
874 res.json({ products, ...metadata })
875 }
876 ```
877
878 You pass the `req.queryConfig` object to the `index` method, which will contain the fields and pagination properties to use in the query.
879
880 ### Use Index Module in Workflows
881
882 In a workflow's step, you can resolve `query` and use its `index` method to retrieve data using the Index Module.
883
884 For example:
885
886 export const workflowHighlights = [
887 ["14", "query", "Resolve query in a workflow step."],
888 ["18", "index", "Use the `index` method to retrieve data."],
889 ]
890
891 ```ts title="src/workflows/custom-workflow.ts" highlights={workflowHighlights}
892 import {
893 createStep,
894 createWorkflow,
895 StepResponse,
896 WorkflowResponse,
897 } from "@medusajs/framework/workflows-sdk"
898 import {
899 ContainerRegistrationKeys,
900 } from "@medusajs/framework/utils"
901
902 const retrieveBrandsStep = createStep(
903 "retrieve-brands",
904 async ({}, { container }) => {
905 const query = container.resolve(
906 ContainerRegistrationKeys.QUERY
907 )
908
909 const { data: brands } = await query.index({
910 entity: "brand",
911 fields: ["id", "name", "products.id"],
912 filters: {
913 products: {
914 id: {
915 $ne: null,
916 },
917 },
918 },
919 })
920
921 return new StepResponse(brands)
922 }
923 )
924
925 export const retrieveBrandsWorkflow = createWorkflow(
926 "retrieve-brands",
927 () => {
928 const retrieveBrands = retrieveBrandsStep()
929
930 return new WorkflowResponse(retrieveBrands)
931 }
932 )
933 ```
934
935 This will retrieve all brands that are linked to at least one product.
936
937 ### Sales Channel Filtering for Multi-Vendor Setups
938
939 For multi-vendor marketplaces where you need to filter products based on sales channels, the Index Module provides the most efficient solution. Unlike Query which has limitations with cross-module filtering, the Index Module enables complex filtering across linked data models.
940
941 For example, to filter vendor products by multiple sales channels:
942
943 ```ts title="src/api/custom/vendor-products/route.ts"
944 const { data: products } = await query.index({
945 entity: "product",
946 fields: ["id", "sales_channels.id", "vendor.id"],
947 filters: {
948 sales_channels: {
949 id: ["sc_vendor_1", "sc_vendor_2"],
950 },
951 vendor: {
952 id: "vendor_123",
953 },
954 },
955 })
956 ```
957
958 This query efficiently filters products by both vendor and sales channels in a single operation.
959
960 ### Retrieve Localized Data
961
962 <Prerequisites
963 items={[
964 {
965 text: "Medusa v2.12.4 or later",
966 link: "https://github.com/medusajs/medusa/releases/tag/v2.12.4"
967 },
968 {
969 text: "Translation Module Configured",
970 link: "!resources!/commerce-modules/translation#configure-translation-module",
971 },
972 ]}
973 />
974
975 To retrieve localized data for data models that have translations, pass a `locale` property in the second parameter object of the `query.index` method.
976
977 ```ts highlights={[["7", "locale", "Pass the locale to retrieve localized data."]]}
978 const { data: products } = await query.index(
979 {
980 entity: "product",
981 fields: ["id", "title", "description"],
982 },
983 {
984 locale: "fr-FR",
985 }
986 )
987 ```
988
989 The `locale` property is a string representing the locale code following the [IETF BCP 47 standard](https://gist.github.com/typpo/b2b828a35e683b9bf8db91b5404f1bd1).
990
991 The returned products will have their `title` and `description` properties in French (`fr-FR`), if translations are available.
992
993 Learn more in the [Translation Module](!resources!/commerce-modules/translation) documentation.