【问题标题】:GraphQL filters in GatsbyJSGatsbyJS 中的 GraphQL 过滤器
【发布时间】:2019-06-22 04:30:22
【问题描述】:

我无法理解如何在 GatsbyJS 中为 GraphQL 查询编写过滤器。

这行得通:

filter: { contentType: { in: ["post", "page"] }

我基本上需要相反的,比如:

filter: { "post" in: { contentTypes } } // where contentTypes is array

这不起作用,因为“需要 NAME”(在我的示例中是“post”)。

通过 GatsbyJS docs 我发现了这个:

elemMatch: short for element match, this indicates that the field you are filtering will return an array of elements, on which you can apply a filter using the previous operators

filter:{
  packageJson:{
    dependencies:{
      elemMatch:{
        name:{
          eq:"chokidar"
        }
      }
    }
  }
}

太棒了!这就是我需要的!所以我尝试了一下,我得到了:

error GraphQL Error Field "elemMatch" is not defined by type markdownRemarkConnectionFrontmatterTagsQueryList_2.

markdownRemarkConnectionFrontmatterTagsQueryList_2 中定义的关键字是:

  • eq: 字符串 |空;
  • ne: 字符串 |空;
  • 正则表达式:字符串 |空;
  • glob:字符串 |空;
  • 在:数组 |空;

当文档中提到更多关键字(例如elemMatch)时,为什么我仅限于这些关键字?为什么我不允许使用过滤器结构“element in: { array }”?

如何创建此过滤器?

【问题讨论】:

    标签: graphql gatsby


    【解决方案1】:

    按数组中的值过滤

    假设您有一个以categories 作为字符串数组的降价博客,您可以像这样过滤categories 中带有“历史”的帖子:

    {
      allMarkdownRemark(filter:{
        frontmatter:{
          categories: {
           in: ["historical"]
          }
        }
      }) {
        edges {
          node {
            id
            frontmatter {
              categories
            }
          }
        }
      }
    }
    

    您可以在 Gatsby.js docs 的任何 graphiq 块中尝试此查询。


    元素匹配

    我认为elemMatch 仅对具有对象数组的字段“打开”;类似comments: [{ id: "1", content: "" }, { id: "2", content: ""}]。这样,您可以对每个 comment 的字段应用更多过滤器:

    comments: { elemMatch: { id: { eq: "1" } } }
    

    这是一个您可以在 gatsby 文档中的 graphiq 块中试用的示例:

    // only show plugins which have "@babel/runtime" as a dependency
    {
      allSitePlugin (filter:{
        packageJson:{
          dependencies: {
            elemMatch: {
              name: {
                eq: "@babel/runtime"
              }
            }
          }
        }
      }) {
        edges {
          node {
            name
            version
            packageJson {
              dependencies {
                name
              }
            }
          }
        }
      }
    }
    

    【讨论】:

    • 您给出的第一个查询在玩具示例中有效,但在实际案例中无效。我收到错误 GraphQL Error Variable "$tag" of type "String" used in position expecting type "[String]". 我在这里使用的确切过滤器是 filter: { frontmatter: { tags: { in: $tag } } } 看起来与您的查询相同。
    • 嘿@AtteJuvonen!我的错,你试过tags: {in: [$tag] }吗?
    • 谢谢,它有效!这真是令人惊讶。我本来希望“[b] 中的 [a,b]”的过滤器返回 false(当 [a,b] 中的所有元素都未在 [b] 中找到时),但它确实返回 true,就像我想要的那样到。
    • 很高兴它有帮助!我也觉得有点不直观。此外,当您使用查询变量时,似乎对过滤关键字键入更加挑剔。让我编辑答案
    猜你喜欢
    • 2020-10-08
    • 2020-07-28
    • 2018-04-12
    • 2020-07-30
    • 1970-01-01
    • 2020-02-25
    • 1970-01-01
    • 1970-01-01
    • 2020-09-10
    相关资源
    最近更新 更多