Loving Tina? us on GitHub0.0k

文档

学习

v.Latest
Documentation
排序查询结果
目录

要通过集合字段对集合结果进行排序,请将 sort 参数传递给 <collection>Connection 查询,值对应于要排序的集合字段。结果将按升序返回。

请参阅反向分页以了解如何以降序检索结果。

多字段排序

要通过多个字段对集合结果进行排序,我们需要在模式中定义一个多字段“索引”。索引定义决定了集合中哪些字段包含在索引中以及排序结果时字段的顺序。

除了决定查询结果的排序顺序外,索引还会影响查询的性能

以下是我们的帖子集合的索引定义示例:

{
collections: [
{
label: "博客文章",
name: "post",
path: "content/posts",
format: "mdx",
fields: [...],
indexes: [{
name: "category-date",
fields: [
{ name:"category" },
{ name:"date" }
]
}]
}
]
}

索引定义中的 name 属性在 sort 参数中引用时使用。fields 属性是集合中应被索引的字段的有序列表,通过字段 name 标识。使用此示例的关联排序返回的结果将首先按 category 排序,然后按 date 排序。

默认排序顺序

如果查询中未指定 sort 参数,结果将根据默认文件名顺序返回。

示例

按单个字段排序

在这里,我们将使用 postConnection 查询我们的 post 集合,并按 date 字段对结果进行排序:

{
postConnection(sort: "date") {
edges {
node {
id
title
date
}
}
}
}
{
"data": {
"postConnection": {
"edges": [
{
"node": {
"id": "content/posts/voteForPedro.json",
"title": "Vote For Pedro",
"date": "2022-06-15T07:00:00.000Z"
}
},
{
"node": {
"id": "content/posts/anotherPost.json",
"title": "Just Another Blog Post",
"date": "2022-07-15T07:00:00.000Z"
}
},
{
"node": {
"id": "content/posts/nested/anotherPost.json",
"title": "Just Another Blog Post",
"date": "2022-07-15T07:00:00.000Z"
}
}
]
}
}
}

按多个字段排序

在这里,我们将使用 postConnection 查询我们的 post 集合,并使用名为 category-date 的多字段索引首先按 category 然后按 date 对结果进行排序:

{
postConnection(sort: "category-date") {
edges {
node {
id
title
category
date
}
}
}
}
{
"data": {
"postConnection": {
"edges": [
{
"node": {
"id": "content/posts/anotherPost.json",
"title": "Just Another Blog Post",
"category": "lifestyle",
"date": "2022-07-15T07:00:00.000Z"
}
},
{
"node": {
"id": "content/posts/nested/anotherPost.json",
"title": "Just Another Blog Post",
"category": "lifestyle",
"date": "2022-07-15T07:00:00.000Z"
}
},
{
"node": {
"id": "content/posts/voteForPedro.json",
"title": "Vote For Pedro",
"category": "politics",
"date": "2022-06-15T07:00:00.000Z"
}
}
]
}
}
}
上次编辑: March 26, 2025