1 import { Prerequisites } from "docs-ui"
2
3 export const metadata = {
4 title: `Index Data from a Linked Module`,
5 }
6
7 # {metadata.title}
8
9 In this guide, you'll learn how to include a linked module's data 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 An index isn't limited to the fields of its own `entity`. [Query](!docs!/learn/fundamentals/query) resolves [module links](!docs!/learn/fundamentals/module-links), so `graphSeed` and `graphConsume` can select a linked module's fields with the same dotted paths that `query.graph` accepts.
21
22 The examples in this section index products along with the brand each product is linked to, using the [custom Brand Module](!docs!/learn/customization/custom-features/module) and the [product-brand link](!docs!/learn/customization/extend-features/define-link) from the Medusa documentation.
23
24 <Note title="Tip">
25
26 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).
27
28 </Note>
29
30 ## Select and Declare the Linked Fields
31
32 To hold a linked module's data in the index:
33
34 1. Select the linked fields in `graphSeed` and `graphConsume`, the way you'd select them in `query.graph`. For example, `brand.name`.
35 2. Declare them in the index's `fields` with `search.object`, mirroring the shape `query.graph` returns.
36
37 For example, create the file `src/search/product.ts` with the following content:
38
39 export const linkedHighlights = [
40 ["13", `"brand.name"`, "Select the linked brand's name through Query."],
41 ["23", "brand", "Declare the linked data as an object field."],
42 ["25", "name", "Each leaf carries its own modifiers."],
43 ]
44
45 ```ts title="src/search/product.ts" highlights={linkedHighlights}
46 import {
47 defineSearchIndex,
48 graphConsume,
49 graphSeed,
50 search,
51 } from "@medusajs/framework/utils"
52
53 const fields = [
54 "id",
55 "title",
56 "status",
57 "brand.id",
58 "brand.name",
59 ]
60
61 export const productIndex = defineSearchIndex({
62 name: "product",
63 entity: "product",
64 fields: search.define({
65 id: search.keyword().filterable(),
66 title: search.text().searchable({ weight: 3 }),
67 status: search.keyword().filterable(),
68 brand: search.object({
69 id: search.keyword().filterable(),
70 name: search
71 .keyword()
72 .searchable()
73 .filterable()
74 .facetable(),
75 }),
76 }),
77 events: [
78 "product.created",
79 "product.updated",
80 "product.deleted",
81 ],
82 consume: graphConsume({ fields }),
83 seed: graphSeed({ fields }),
84 })
85 ```
86
87 `query.graph` returns a linked brand as a nested object, so an indexed document has the following shape:
88
89 ```json
90 {
91 "id": "1",
92 "title": "Product Title",
93 "status": "active",
94 "brand": {
95 "id": "10",
96 "name": "Acme",
97 },
98 }
99 ```
100
101 Refer to [Search Index Fields](../fields/page.mdx) for every field type and modifier.
102
103 The [Store Search API route](!api!/store/search/search-indexes) resolves the index by the `entity` a query names, so the fields you add to your `product` index become available to storefront searches. Refer to [Search Products](../../page.mdx#search-products) for how to query it.
104
105 ---
106
107 ## Reference Nested Fields by Their Full Path
108
109 The search engine flattens an object field into its leaves, each keyed by its dotted path, such as `brand.name`. Filters, facets, and sorting take that path as a string key.
110
111 For example, to filter and facet products by their linked brand's name:
112
113 ```ts
114 const { data: products } = await query.search({
115 entity: "product",
116 fields: ["id", "title", "brand.name"],
117 filters: {
118 q: "shirt",
119 "brand.name": "Acme",
120 },
121 search_options: {
122 facets: ["brand.name"],
123 },
124 })
125 ```
126
127 Keep the following in mind when you filter, facet, or sort on nested fields:
128
129 - The object itself isn't a field. Only the leaves are indexed, so `brand` is not something you can filter on. A filter on it throws `Unknown filter field "brand"`.
130 - Put the full path in the filter's key, not in its value. `{ "brand.name": "Acme" }` works, whereas `{ brand: { name: "Acme" } }` throws the same error, since the provider reads a nested object as an operator map.
131 - A leaf must be declared, and it must carry the modifier for what you're doing with it. Filtering on `brand.name` requires `filterable()` on that leaf, faceting requires `facetable()`, and sorting requires `sortable()`.
132
133 ---
134
135 ## Keep the Index Current When Linked Data Changes
136
137 Changing a brand doesn't emit a product event, so a product's document keeps the brand name it was indexed with until something re-ingests that product. The same is true when a link is created or removed, which emits no event at all.
138
139 You can ensure the index stays current when a brand is updated by:
140
141 1. [Emit the brand update event in the workflow updating it](!docs!/learn/fundamentals/events-and-subscribers/emit-event#emit-event-in-a-workflow).
142 2. Pass the brand update event to the product index's `events` array so it can trigger the `consume` function and re-ingest the affected products.
143 3. Implement the `consume` function to handle the brand update event, resolve the affected products, and re-ingest them.
144
145 For example, to pass the brand update event to the product index and handle it in the `consume` function:
146
147 export const linkedConsumeHighlights = [
148 ["8", "consumeProducts", "The helper still handles product events."],
149 ["19", "startsWith", "Route a product event to the helper as-is."],
150 ["24", "graph", "Read the products linked to the changed brand."],
151 ["35", `"product.updated"`, "Re-ingest them as if each had changed."],
152 ]
153
154 ```ts title="src/search/product.ts" highlights={linkedConsumeHighlights}
155 import {
156 defineSearchIndex,
157 graphConsume,
158 graphSeed,
159 search,
160 } from "@medusajs/framework/utils"
161
162 const consumeProducts = graphConsume({ fields })
163
164 export const productIndex = defineSearchIndex({
165 // ...
166 events: [
167 "product.created",
168 "product.updated",
169 "product.deleted",
170 "brand.updated",
171 ],
172 async consume(event, context) {
173 if (event.name.startsWith("product.")) {
174 return await consumeProducts(event, context)
175 }
176
177 const { data: brands } = await context.container
178 .query.graph({
179 entity: "brand",
180 fields: ["products.id"],
181 filters: { id: event.data.id },
182 })
183
184 const ids = brands[0]?.products?.map(
185 (product) => product.id
186 ) ?? []
187
188 return await consumeProducts(
189 { name: "product.updated", data: { id: ids } },
190 context
191 )
192 },
193 seed: graphSeed({ fields }),
194 })
195 ```
196
197 You use `graphConsume` to handle product events. For brand updates, you manually resolve the affected products and re-ingest them as `product.updated` events.
198
199 ### Re-Ingest a Product After a Link Change
200
201 Creating or removing a link doesn't emit an event either, so nothing tells the index that a product's brand changed. To keep the index current, [emit your own event in the workflow that changes the link](!docs!/learn/fundamentals/events-and-subscribers/emit-event#emit-event-in-a-workflow), then handle it in `consume` as you do the brand update event.
202
203 For example, , add the event to the index's `events` array and handle it in `consume`:
204
205 export const linkConsumeHighlights = [
206 ["8", `"product-brand.linked"`, "Receive the event you emit in the workflow."],
207 ["17", "product_id", "Re-ingest the product the link changed for."],
208 ]
209
210 ```ts title="src/search/product.ts" highlights={linkConsumeHighlights}
211 export const productIndex = defineSearchIndex({
212 // ...
213 events: [
214 "product.created",
215 "product.updated",
216 "product.deleted",
217 "brand.updated",
218 "product-brand.linked",
219 ],
220 async consume(event, context) {
221 // ...
222
223 if (event.name === "product-brand.linked") {
224 return await consumeProducts(
225 {
226 name: "product.updated",
227 data: { id: event.data.product_id },
228 },
229 context
230 )
231 }
232
233 // ... handle brand.updated
234 },
235 })
236 ```
237
238 This example assumes the event carries the product's ID. You re-ingest it as a `product.updated` event, which rebuilds the document with the brand it's now linked to.