如何在 Shopify 中高效地检索一个产品所属的所有集合的列表?

How to efficiently retrieve a list of all collections a product belongs to in Shopify?

我想从 Shopify 商店创建产品数据的 CSV 导出。对于每个产品,我正在导出产品名称、价格、图像 URL 等数据......在这个导出中,我还想为每个产品列出产品所属的所有集合,最好是在层次结构中使产品系列出现在网站的导航菜单中(例如男装 > 衬衫 > 红衬衫)。

如果我对 API 的理解是正确的,对于每个产品,我需要单独调用 Collect API 以获取它所属的集合列表,然后再调用Collections API 获取每个集合的句柄。这听起来像是每个产品都有很多 API 个调用。

不幸的是,正如您所指出的,由于 Shopify API 的结构方式,我认为没有一种有效的方法可以做到这一点。它不允许从产品中查询集合,而只允许从集合中查询产品。即看不到一件商品属于什么集合,但可以看到属于一个集合的商品。

ShopifyAPI::Collect or ShopifyAPI::Collection REST resource does not return Product variant information, which is needed to get the price information as per the requirements. Furthermore, ShopifyAPI::Collect is limited to custom collections only, and would not work for products in ShopifyAPI::SmartCollection's. For this reason I suggest using GraphQL代替REST来获取所需的信息。

query ($collectionCursor: String, $productCursor: String){
  collections(first: 1, after: $collectionCursor) {
    edges {
      cursor
      node {
        id
        handle
        products(first: 8, after: $productCursor){
          edges{
            cursor
            node{
              id
              title
              variants(first: 100){
                edges{
                  node{
                    price
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}
{
  "collectionCursor": null,
  "productCursor": null
}

$productCursor 变量可用于遍历集合中的所有产品,$collectionCursor 可用于遍历所有集合。请注意,只需要查询前 100 个变体,因为 Shopify 对每个产品有 100 个变体的硬性限制。

相同的查询可用于遍历 ShopifyAPI::SmartCollection

或者,使用 REST API 的相同查询在 Ruby 中看起来像这样。

collections = ShopifyAPI::Collection.all # paginate
collection.each do |collection|
    collection.products.each do |product|
      product.title
      # note the extra call the Product API to get varint info
      ShopifyAPI::Product.find(product.id).variants.each do |varaint|
        variant.price
      end
    end
end

我看不出有任何方法可以解决 REST 查询的低效问题,但您可以使用 Shopify 的 GraphQL Bulk Operations.

改进 GraphQL 查询