You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Shopify GraphQL查询:如何返回商品匹配的OR过滤条件?

解决方案

Shopify GraphQL API本身不支持直接返回商品匹配的具体OR过滤条件——因为query参数是作为整体执行过滤的,API不会追踪单个商品命中了哪条子条件。不过可以通过两种替代方案实现需求:

1. 拆分查询,逐个验证子条件

把my_query里的多个OR子条件拆成独立查询,分别获取每个条件下的商品handle,之后关联每个handle对应的匹配条件。举个例子:

假设你的my_query是"title:'shirt' OR tag:'sale' OR vendor:'Nike'",可以这么改代码:

# 拆分出所有子查询
sub_queries = [
    "title:'shirt'",
    "tag:'sale'",
    "vendor:'Nike'"
]

product_matches = {}
# 逐个发送查询
for sub_q in sub_queries:
    data = {
        "query": f"""
            {{
              products(first: {MAX_SIZE}, query: "{sub_q}" ) {{
                edges {{
                  node {{
                    handle
                  }}
                }}
              }}
            }}
            """
    }
    # 替换成你实际的请求逻辑
    response = your_shopify_request_function(data)
    for edge in response['data']['products']['edges']:
        handle = edge['node']['handle']
        if handle not in product_matches:
            product_matches[handle] = []
        product_matches[handle].append(sub_q)

# 最终每个handle对应它匹配的子条件
print(product_matches)

这种方式逻辑简单,容易实现,但子条件多的话会增加API请求次数,要注意Shopify的API速率限制。

2. 获取完整字段,本地匹配子条件

一次性拉取商品的所有相关字段(比如title、tags、vendor这些你用来过滤的字段),之后在本地检查每个商品匹配哪些子条件:

# 修改查询,获取过滤需要的字段
data = {
    "query": f"""
        {{
          products(first: {MAX_SIZE}, query: {my_query} ) {{
            edges {{
              node {{
                handle
                title
                tags
                vendor
                # 加上其他你过滤用到的字段
              }}
            }}
          }}
        }}
        """
}

# 发送请求拿数据
response = your_shopify_request_function(data)
product_matches = {}

# 定义你的子条件规则,和原query对应
sub_conditions = [
    {"type": "title", "value": "shirt"},
    {"type": "tag", "value": "sale"},
    {"type": "vendor", "value": "Nike"}
]

# 本地逐个验证匹配
for edge in response['data']['products']['edges']:
    product = edge['node']
    handle = product['handle']
    matches = []
    for cond in sub_conditions:
        if cond['type'] == 'title' and cond['value'].lower() in product['title'].lower():
            matches.append(f"title:'{cond['value']}'")
        elif cond['type'] == 'tag' and cond['value'] in product['tags']:
            matches.append(f"tag:'{cond['value']}'")
        elif cond['type'] == 'vendor' and product['vendor'].lower() == cond['value'].lower():
            matches.append(f"vendor:'{cond['value']}'")
    product_matches[handle] = matches

# 输出结果
print(product_matches)

这种方法只需要一次API请求,避免多次调用的限流问题,但要注意本地的匹配逻辑必须和Shopify的查询规则对齐(比如大小写处理、模糊匹配规则),否则会出现结果不一致的情况。

额外提醒

  • 如果用了Shopify的高级查询语法(比如范围、精确匹配),一定要确保本地逻辑和Shopify的规则完全一致。
  • 拆分查询时,要控制请求频率,Shopify GraphQL API默认每分钟限制1000点查询,别超了。

内容的提问来源于stack exchange,提问作者LordNikon27

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 00:55:07