GatsbyJS 中的 GraphQL 过滤器

Att*_*nen 4 graphql gatsby

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

这有效:

filter: { contentType: { in: ["post", "page"] }
Run Code Online (Sandbox Code Playgroud)

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

filter: { "post" in: { contentTypes } } // where contentTypes is array
Run Code Online (Sandbox Code Playgroud)

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

通过 GatsbyJS文档后,我发现了这一点:

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"
        }
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

伟大的!这就是我需要的!所以我尝试这样做,我得到:

error GraphQL Error Field "elemMatch" is not defined by type markdownRemarkConnectionFrontmatterTagsQueryList_2.
Run Code Online (Sandbox Code Playgroud)

markdownRemarkConnectionFrontmatterTagsQueryList_2中定义的关键字是:

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

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

如何创建此过滤器?

Der*_*yen 6

按数组中的值过滤

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

{
  allMarkdownRemark(filter:{
    frontmatter:{
      categories: {
       in: ["historical"]
      }
    }
  }) {
    edges {
      node {
        id
        frontmatter {
          categories
        }
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

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


元素匹配

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

comments: { elemMatch: { id: { eq: "1" } } }
Run Code Online (Sandbox Code Playgroud)

这是您可以在 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
          }
        }
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 嘿@AtteJuvonen!我的错,你试过 `tags: {in: [$tag] }` 吗? (2认同)