GatsbyJS中的GraphQL过滤器
我很难理解如何在GatsbyJS中为GraphQL查询编写过滤器 这项工作:GatsbyJS中的GraphQL过滤器,graphql,gatsby,Graphql,Gatsby,我很难理解如何在GatsbyJS中为GraphQL查询编写过滤器 这项工作: filter: { contentType: { in: ["post", "page"] } 我基本上需要的是相反的,比如: filter: { "post" in: { contentTypes } } // where contentTypes is array 这不起作用,因为“NAME是预期的”(在我的示例中,“post”是) 通过《盖茨比》我发现: elemMatch: short for elemen
filter: { contentType: { in: ["post", "page"] }
我基本上需要的是相反的,比如:
filter: { "post" in: { contentTypes } } // where contentTypes is array
这不起作用,因为“NAME是预期的”(在我的示例中,“post”是)
通过《盖茨比》我发现:
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.
中定义的关键字包括:
- 等式:字符串| null李>
- ne:字符串|空李>
- regex:string | null李>
- glob:string | null李>
- in:数组| null李>
elemMatch
)时,为什么我仅限于这些关键字?为什么不允许我使用过滤器结构“element in:{array}”
如何创建此筛选器?在数组中按值筛选
假设您有一个带有categories
的降价博客,作为字符串数组,您可以在categories
中过滤带有“history”的帖子,如下所示:
{
allMarkdownRemark(filter:{
frontmatter:{
categories: {
in: ["historical"]
}
}
}) {
edges {
node {
id
frontmatter {
categories
}
}
}
}
}
您可以在中的任何graphiq块中尝试此查询
电子竞赛 我认为
elemMatch
仅对具有对象数组的字段“打开”;类似于注释:[{id:“1”,内容:},{id:“2”,内容:}]
。这样,您可以在每个注释的字段上应用进一步的过滤器:
comments: { elemMatch: { id: { eq: "1" } } }
下面是一个示例,您可以在盖茨比文档的图形块中尝试:
// 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错误变量“$tag”,类型为“String”,用于预期类型为“[String]”的位置
我在这里使用的确切过滤器是filter:{frontmatter:{tags:{in:$tag}}}}
,看起来与您的查询相同。嘿@AtteJuvonen!我的错,你试过标签:{in:[$tag]}
?谢谢,它能用!这真是令人惊讶。我希望[b]中“[a,b]的过滤器返回false(当[a,b]中的所有元素都未在[b]中找到时),但它确实返回true,就像我希望的那样。很高兴它有帮助!我也觉得有点不直观。另外,当您使用查询变量时,它似乎更挑剔过滤器关键字的键入。让我编辑一下答案