GraphQL: How to get Orders having a particular Product (by ID or Handle)

Have an issue with GraphQL query.

I need list of orders which contains a particular product. How can we do that.

Any help would be much appreciated.

Hey @RanaPartap

There doesn’t appear to be a way to list orders which contain a specific product. As a workaround you could scan all orders and look through their line items, or use something like Flow to tag (new) orders which contain specific products and then use the API to filter orders by that tag.

Thanks for response.

But how can we get all orders and iterate thro’ each item? As I know using GraphQL there is a maximum query cost is 1000. If I pull 25 recent records with 5 lineitems it turns to a query cost of 872 as following. actualQueryCost does not make any sense in query bcs we have to keep query cost under requestedQueryCost

So how can we loop through all orders and filter it for particular product bcs there could be very few orders for a selected product in 30 orders. Also we may skip some lineitems too as we specify 5 lineitems only?

Example Query:

{
  orders(
    first: 30
    reverse: true
    query: "financial_status:paid OR financial_status:pending"
  ) {
    edges {
      node {
        id
        createdAt
        customer {
          firstName
          lastName
        }
        lineItems(first: 5) {
          edges {
            node {
              product {
                handle
                title
                small_image: images(first: 1, maxWidth: 150) {
                  edges {
                    node {
                      url
                    }
                  }
                }
                id
              }
            }
          }
        }
      }
    }
  }
}

Query Cost:

"cost": {
      "requestedQueryCost": 872,
      "actualQueryCost": 253,
      "throttleStatus": {
        "maximumAvailable": 1000,
        "currentlyAvailable": 747,
        "restoreRate": 50
      }

I am stuck due to this limit.

Hey @RanaPartap

You’ll want to paginate the results - here’s how: https://shopify.dev/docs/api/usage/pagination-graphql

1 Like

Hmmm Thanks. I am also using this method now.

1 Like

Hi @RanaPartap

Though not by Id or Handle, it is possible to find orders with a certain product using the SKU field:

query {

orders(first: 10, reverse: true, query: “sku:product_sku_here”) {

edges {

node {

id

name

}

}

}

}