GraphQL での結果の並べ替え (orderBy)

順序付けは、返されるレコードのシーケンスを定義し、安定した改ページ位置を支えます。 GraphQL では、データ API ビルダー (DAB) は、firstまたはafterを適用する前に、orderBy引数を使用して結果を並べ替えます。 orderByを省略すると、DAB は既定で主キーによる並べ替え (昇順) に設定されます。

注

複合主キーは、データベース列の順序で並べ替えられます。

このドキュメントの REST バージョンに移動します。

概要

概念 Description
Argument orderBy
方向の値 ASC、DESC
既定の順序 主キーの昇順
複数フィールドの順序 宣言されたオブジェクト プロパティの順序で並べ替え
タイブレーク 残りの主キー フィールドが自動的に追加される

使用パターン

query {
  books(orderBy: { year: DESC, title: ASC }, first: 5) {
    items {
      id
      title
      year
    }
  }
}

概念 SQL

SELECT TOP (5)
  id,
  sku_title AS title,
  year
FROM dbo.books
ORDER BY year DESC, sku_title ASC, id ASC;

サンプル応答

{
  "data": {
    "books": {
      "items": [
        { "id": 7, "title": "Dune Messiah", "year": 1969 },
        { "id": 6, "title": "Dune", "year": 1965 },
        { "id": 3, "title": "Foundation", "year": 1951 },
        { "id": 1, "title": "I, Robot", "year": 1950 },
        { "id": 8, "title": "The Martian Chronicles", "year": 1950 }
      ]
    }
  }
}

フィールドの動作

特徴 行動
入力の種類 スカラー フィールドを列挙する生成*OrderByInput
方向列挙型 ASC、DESC
複合順序 優先順位は宣言の順序に従う
Null 方向 フィールドを並べ替えから除外します (title: null)
不明なフィールド GraphQL 検証エラーを生成します

フィールドを無視する例

query {
  books(orderBy: { title: null, id: DESC }) {
    items { id title }
  }
}

無効な構造体

GraphQL は、orderBy内の論理演算子 (and、or) を禁止します。 たとえば、次の例では検証エラーが発生します。

books(orderBy: { or: { id: ASC } })

変数の使用例

query ($dir: OrderBy) {
  books(orderBy: { id: $dir }, first: 4) {
    items { id title }
  }
}

Variables

{ "dir": "DESC" }

関連する構成

{
  "entities": {
    "Book": {
      "source": {
        "object": "dbo.books",
        "type": "table"
      },
      "mappings": {
        "sku_title": "title"
      }
    }
  }
}

構成例

{
  "runtime": {
    "pagination": {
      "default-page-size": 100,
      "max-page-size": 100000
    }
  },
  "entities": {
    "Book": {
      "source": {
        "type": "table",
        "object": "dbo.books"
      },
      "mappings": {
        "sku_title": "title",
        "sku_price": "price"
      },
      "relationships": {
        "book_category": {
          "cardinality": "one",
          "target.entity": "Category",
          "source.fields": [ "category_id" ],
          "target.fields": [ "id" ]
        }
      }
    },
    "Category": {
      "source": {
        "type": "table",
        "object": "dbo.categories"
      },
      "relationships": {
        "category_books": {
          "cardinality": "many",
          "target.entity": "Book",
          "source.fields": [ "id" ],
          "target.fields": [ "category_id" ]
        }
      }
    }
  }
}

こちらも参照ください

概念 REST GraphQL 目的
Projection $select 品目 返すフィールドを選択する
フィルタリング $filter フィルター 条件で行を制限する
並べ替え $orderby orderBy 並べ替え順序を定義する
ページ サイズ $first first ページあたりのアイテム数を制限する
継続 $after 後 カーソルを使用して最後のページから続行する

注

REST キーワードは、OData 規則に従って、 $で始まります。