Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 33 ยท The APIs

Query: Fields, Filters and Pagination

Read data across Medusa modules with query.graph: entity names, fields, filters, pagination, linked data, query.index, and a runnable cross-module join stand-in.

Medusa keeps each commerce module isolated: the Product Module cannot join onto the Inventory Module's tables, and your own Review module cannot add a foreign key to products. That isolation keeps modules replaceable, but it creates an everyday problem. A storefront page wants "products, with their variants, with their prices and the average review rating" in one response. Where does that data get joined?

The answer is Query, a tool you resolve from the container inside routes, subscribers, jobs and workflow steps. You describe the shape you want (entity, fields, filters, pagination) and Query fetches from each module and stitches the pieces together using module links. This is the same engine behind the fields parameter you used in The Store API and The Admin API. The real Query needs a Medusa server, so those examples are read-only; the runnable stand-ins implement a small version of the same idea so you can see why it works.

Resolving and calling query.graph

TypeScript
import type { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
import { ContainerRegistrationKeys } from "@medusajs/framework/utils"

export async function GET(req: MedusaRequest, res: MedusaResponse) {
  const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)

  const { data: products, metadata } = await query.graph({
    entity: "product",
    fields: ["id", "title", "variants.id", "variants.sku", "variants.prices.*"],
    filters: { status: "published" },
    pagination: { skip: 0, take: 12, order: { created_at: "DESC" } },
  })

  res.json({ products, count: metadata?.count })
}

The result is { data, metadata }. data is an array of plain objects shaped like your fields. metadata holds skip, take and count when you pass pagination. The call is built from four parts.

Entity. entity is the data model's registered name, in snake_case for core models: product, product_variant, order, customer, cart. For your own module, it is the name you gave in model.define("review", ...). Linked data models are reachable from other entities through their link names, as shown below.

Fields. An array of dot paths. "title" is a column, "variants.sku" follows the variants relation and takes one column from it, "variants.*" takes every column of that relation, and "*" takes every column of the entity. Ask for what you use. Selecting variants.prices.* for every product is a real cost: it adds more fetching and more memory, and the next sections explain why.

Filters. An object of conditions on the entity's own fields: { status: "published" }, { id: ["prod_1", "prod_2"] } (an array means "any of"), and operator objects such as { created_at: { $gte: "2025-01-01" } }. Filters on linked data (for example "only products that have a review") follow different rules, covered below.

Pagination. skip and take slice the results and order sorts. Always paginate lists that can grow; an unbounded query.graph on order will eventually load your whole table.

Linked data across modules

Suppose a custom Review module is linked to products with defineLink (see Module Links). Once the link exists, reviews appear as a field on product:

TypeScript
const { data } = await query.graph({
  entity: "product",
  fields: ["id", "title", "reviews.rating", "reviews.comment"],
  filters: { id: productId },
})

Medusa reads the link definition, queries the Product Module for the products, queries the Review Module for the linked reviews, and merges them into one structure. Neither module knows about the other. You can also start from the other end: entity: "review" with fields: ["rating", "product.title"], if the link is defined in both directions.

You can also query the link table itself when you need the link's extra columns or a list of links without loading both sides. Core links have entity names too, such as the product-variant-to-inventory link; check the module reference for the names in your version.

flowchart LR
    Q["query.graph<br/>entity: product"] --> J["Remote joiner"]
    J -->|"1. fetch products"| P["Product Module"]
    J -->|"2. fetch linked ids"| L["Link table"]
    J -->|"3. fetch reviews by ids"| R["Review Module"]
    J --> M["Merge into one result"]

Query asks each module for its slice and merges them; modules never join each other's tables.

The cost model: why fields matter

Because Query combines data from several modules, a deeper fields list means more module calls. The mechanism is often called the remote joiner: it collects the IDs from the first result, then asks the next module for all matching records in one call, rather than one call per parent row. That batching avoids the classic N+1 problem, as the second stand-in below shows. It does not make deep queries free. The rules of thumb:

  • Select only the columns you show ("variants.sku" instead of "variants.*").
  • Keep nesting shallow. Three relations deep is common; six is a smell.
  • Paginate before you decorate: fetch a page of IDs, then request richer fields for that page.
  • Prefer one wide query over a loop that calls query.graph once per product.

A plain query.graph can only filter by columns of the root entity (plus, for some relations, ids it can resolve). The hard question is "list products where a linked record matches", for example "products whose average rating is at least 4" or "products with a variant priced under 20". Joining those in memory after paging gives wrong pages, because filtering happens after slicing.

Medusa's answer is query.index, backed by the Index Module. It keeps a denormalized, queryable copy of selected entities and links, so filters can reach across modules while pagination stays correct:

TypeScript
const { data } = await query.index({
  entity: "product",
  fields: ["id", "title", "variants.sku"],
  filters: { variants: { sku: "TENT-2P" } },
})

The call shape is the same as query.graph; what changes is that the data is read from an index that must be kept in sync (it is populated from events, so it is eventually consistent), and the module must be enabled and configured. At the time of writing this feature is newer than query.graph, so confirm its status and options in the documentation for your Medusa version before depending on it. Use query.graph for the single-record and primary-key reads that make up most code, and consider the index only for listing pages that truly need cross-module filters.

Query versus the module service

You also have each module's own service (listProducts, retrieveProduct...). Choose by the question you are asking:

Need Use
Data from one module only, with that module's filters The module service (productService.listProducts)
Related data from other modules or through links query.graph
Writing data A module service, or better a workflow
Cross-module filter with correct pagination query.index (if enabled) or a purpose-built endpoint

query.graph is read-only. It never creates, updates or deletes.

Stand-in 1: a cross-module join in memory

This stand-in is plain JavaScript, not Medusa. It has three separate "modules" (products, variants, reviews), a link table that the review module does not know about, and a graph() function that understands fields paths, equality and in filters, pagination and a sort order. Run it, then change the fields and filters.

Node.js A tiny query.graph over three modules

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Check the third result: metadata.count still says 2 even though only one row came back. That total is how a storefront draws "page 2 of 2". Note also how reviews.rating appears without the product module ever touching the review table: the join went through the link table, the same way real Medusa uses link definitions.

Stand-in 2: why the joiner batches

The remote-joiner idea is easy to see by counting calls. Below, every access to a "module" increments a counter. The naive version looks up variants once per product. The batched version collects all product ids and asks once, then groups the answer in memory.

Node.js N+1 lookups versus a batched join

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Both versions return the same data, but one makes 21 calls and the other 2. In a real system each call can be a network round trip and a database query, so the difference is large, and it grows with the page size. The lesson for your own code: do not call query.graph inside a loop over results. Collect IDs and make one call with filters: { id: ids }.

Common mistakes

  • Selecting * everywhere. It is convenient and slow. Name the fields.
  • Looping with one query per row. Batch with an id array filter.
  • Treating data as always non-empty. A filter can match nothing; handle an empty array.
  • Expecting writes. Query is read-only; use services or workflows to change data.
  • Filtering linked data after pagination. Counts and pages will be wrong. Use query.index or a different design.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does Medusa need Query to read linked data?

    Isolation keeps modules replaceable. Query asks each module for its slice and joins the pieces in the framework using link definitions.
  2. 2. What does metadata.count contain when you pass pagination?

    count is the total match count, which lets a client compute the number of pages even though data only holds one slice.
  3. 3. Which version of the code avoids the N+1 problem?

    A single call with an array of ids lets Query batch the work. A call per row multiplies module calls with the size of the list.
  4. 4. When is query.index the better tool than query.graph?

    Filtering linked data after slicing gives wrong pages. The index stores a denormalized copy so filters can span modules, at the cost of eventual consistency and extra setup.

Summary

  • query.graph reads data across modules with entity, fields, filters and pagination, and returns { data, metadata }.
  • Field paths such as variants.sku and reviews.* follow relations and links; select only what you use.
  • Links let isolated modules be read together without sharing tables; the joiner batches lookups to avoid N+1.
  • query.index (backed by the Index Module) targets cross-module filtering with correct pagination, but verify availability for your version.
  • Query is read-only: use services and workflows for writes.

Next, add your own endpoints on top of all this in Custom API Routes and Middleware.