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

如何通过GraphQL搜索或过滤数组类型数据?

针对GraphQL字符串数组的过滤解决方案

首先,你遇到的问题在现代GraphQL后端中大多已有成熟的服务端过滤方案,无需在客户端全量拉取数据后再处理,下面分几种常见场景给出具体实现:

1. 基于Hasura的实现(你的示例语法高度匹配Hasura)

Hasura针对数组类型提供了专门的过滤操作符,对于字符串数组,使用_contains可检查数组是否包含指定元素:

query MyQuery {  
  employee_info(limit: 10, where: {employee_names: {_contains: "mark_tom"}}) {     
    account_name   
  } 
}

如果需要模糊匹配数组中的元素(比如包含"mark"的所有姓名),可结合_like操作符:

query MyQuery {  
  employee_info(limit: 10, where: {employee_names: {_like: "%mark%"}}) {     
    account_name   
  } 
}

2. 基于Prisma的实现

Prisma针对字符串数组提供了has操作符,用于判断数组是否包含指定值:

query MyQuery {
  employee_info(
    take: 10
    where: { employee_names: { has: "mark_tom" } }
  ) {
    account_name
  }
}

若需模糊匹配,可结合some操作符配合字符串匹配规则:

query MyQuery {
  employee_info(
    take: 10
    where: { employee_names: { some: { contains: "mark" } } }
  ) {
    account_name
  }
}

3. 自定义GraphQL Resolver的实现

如果是自主开发的GraphQL后端,只需在Resolver的查询逻辑中添加数组包含判断即可。以JavaScript为例:

// 假设数据源为数组
const employeeData = [
  { account_name: "acme_co", employee_names: ["john_smith", "mark_tom", "kelly_clark"] },
  // 其他数据...
];

const resolvers = {
  Query: {
    employee_info: (_, { limit, where }) => {
      const targetName = where.employee_name._eq;
      // 过滤出包含目标姓名的记录
      const filtered = employeeData.filter(item => 
        item.employee_names.includes(targetName)
      );
      // 应用数量限制
      return filtered.slice(0, limit);
    }
  }
};

前端查询可保持你最初的写法,或根据Resolver定义调整参数格式。

总结

现在主流GraphQL后端均已支持数组类型的过滤操作,优先选择服务端过滤可减少网络传输数据量、提升查询性能。仅当后端确实不支持这类操作时,再考虑客户端过滤作为临时方案。

内容的提问来源于stack exchange,提问作者data-in-mix

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 05:52:56