バージョンごとのドキュメント一覧

67.4. 実装 #

<title>Implementation</title>

This section covers B-Tree index implementation details that may be of use to advanced users. See <filename>src/backend/access/nbtree/README</filename> in the source distribution for a much more detailed, internals-focused description of the B-Tree implementation. 本節では、上級ユーザに役立つかもしれない、B-Treeインデックスの実装の詳細について説明します。 更なる詳細、B-Tree実装の内部に焦点をあてた記述については、ソース配布物のsrc/backend/access/nbtree/READMEを参照してください。

67.4.1. B-Treeの構造 #

<title>B-Tree Structure</title>

<productname>PostgreSQL</productname> B-Tree indexes are multi-level tree structures, where each level of the tree can be used as a doubly-linked list of pages. A single metapage is stored in a fixed position at the start of the first segment file of the index. All other pages are either leaf pages or internal pages. Leaf pages are the pages on the lowest level of the tree. All other levels consist of internal pages. Each leaf page contains tuples that point to table rows. Each internal page contains tuples that point to the next level down in the tree. Typically, over 99% of all pages are leaf pages. Both internal pages and leaf pages use the standard page format described in <xref linkend="storage-page-layout"/>. PostgreSQLのB-Treeインデックスは複数階層のツリー構造で、ツリーの各階層はページの双方向連結リストとして使用できます。 一つのメタページがインデックスの最初のセグメントファイルの固定位置に格納されます。 それ以外の全てのページはリーフページか内部ページのいずれかです。 リーフページはツリーの最下階層にあるページです。 各リーフページはテーブルの行を指すタプルを含みます。 各内部ページはツリーの次の下位層を指すタプルを含みます。 典型的には、全ページの99%以上がリーフページです。 内部ページとリーフページは共に、73.6に記載されている標準のページ書式を使用します。

New leaf pages are added to a B-Tree index when an existing leaf page cannot fit an incoming tuple. A <firstterm>page split</firstterm> operation makes room for items that originally belonged on the overflowing page by moving a portion of the items to a new page. Page splits must also insert a new <firstterm>downlink</firstterm> to the new page in the parent page, which may cause the parent to split in turn. Page splits <quote>cascade upwards</quote> in a recursive fashion. When the root page finally cannot fit a new downlink, a <firstterm>root page split</firstterm> operation takes place. This adds a new level to the tree structure by creating a new root page that is one level above the original root page. 既存リーフページがやってくるタプルをはめ込むことができないとき、新たなリーフページがB-Treeインデックスに追加されます。 ページ分割操作は一部のアイテムを新ページに動かすことで、当初は溢れているページに属していたアイテムのために空間を作ります。 ページ分割は、また、新ページへの新たなダウンリンクを親ページに挿入しなければなりません。これは親ページの分割を同様に引き起こすかもしれません。 ページは分割は再帰的に上向きに連鎖します。 最終的にルートページが新たなダウンリンクをはめ込みできないときには、ルートページ分割が実施されます。 これは元のルートページの一つ上の階層に新たなルートページを作ることで、ツリー構造に新しい階層を加えます。

67.4.2. ボトムアップインデックスの削除 #

<title>Bottom-up Index Deletion</title>

B-Tree indexes are not directly aware that under MVCC, there might be multiple extant versions of the same logical table row; to an index, each tuple is an independent object that needs its own index entry. <quote>Version churn</quote> tuples may sometimes accumulate and adversely affect query latency and throughput. This typically occurs with <command>UPDATE</command>-heavy workloads where most individual updates cannot apply the <link linkend="storage-hot"><acronym>HOT</acronym> optimization.</link> Changing the value of only one column covered by one index during an <command>UPDATE</command> <emphasis>always</emphasis> necessitates a new set of index tuples &mdash; one for <emphasis>each and every</emphasis> index on the table. Note in particular that this includes indexes that were not <quote>logically modified</quote> by the <command>UPDATE</command>. All indexes will need a successor physical index tuple that points to the latest version in the table. Each new tuple within each index will generally need to coexist with the original <quote>updated</quote> tuple for a short period of time (typically until shortly after the <command>UPDATE</command> transaction commits). B-Treeインデックスは、MVCCの下で同じ論理テーブル行の複数の現存するバージョンが存在する可能性があることを直接認識していません。 インデックスに対して、各タプルは独自のインデックスエントリを必要とする独立したオブジェクトです。 バージョンチャーンタプルは蓄積し、クエリ待ち時間とスループットに悪影響を与える可能性があります。 これは通常、個々の更新のほとんどがHOT最適化を適用できないようなUPDATEの重いワークロードで発生します。 UPDATE中にあるインデックスによって、カバーされる一つだけの行の値を変更するには、新しいインデックスタプルのセットをいつも必要とします。 テーブル上にある ありとあらゆるインデックスにつき一つです。 具体的には、UPDATEによって論理的に変更されなかったインデックスが含まれることに注意してください。 すべてのインデックスは、テーブル上で最新バージョンを指す後継の物理的なインデックスタプルを必要とします。 各インデックス中のそれぞれの新しいタプルは通常元の更新されたタプルと短期間共存する必要があります(通常、UPDATEトランザクションのコミットした直後までです)。

B-Tree indexes incrementally delete version churn index tuples by performing <firstterm>bottom-up index deletion</firstterm> passes. Each deletion pass is triggered in reaction to an anticipated <quote>version churn page split</quote>. This only happens with indexes that are not logically modified by <command>UPDATE</command> statements, where concentrated build up of obsolete versions in particular pages would occur otherwise. A page split will usually be avoided, though it's possible that certain implementation-level heuristics will fail to identify and delete even one garbage index tuple (in which case a page split or deduplication pass resolves the issue of an incoming new tuple not fitting on a leaf page). The worst-case number of versions that any index scan must traverse (for any single logical row) is an important contributor to overall system responsiveness and throughput. A bottom-up index deletion pass targets suspected garbage tuples in a single leaf page based on <emphasis>qualitative</emphasis> distinctions involving logical rows and versions. This contrasts with the <quote>top-down</quote> index cleanup performed by autovacuum workers, which is triggered when certain <emphasis>quantitative</emphasis> table-level thresholds are exceeded (see <xref linkend="autovacuum"/>). B-Treeインデックスは、ボトムアップインデックスの削除パスの実行によって、バージョンチャーンのインデックスタプルを徐々に削除します。 各削除パスは、予期されたバージョンチャーンのページ分割に対してトリガーされます。 これは、UPDATE文によって論理的に変更されてないインデックスだけで発生します。 さもないと、特定のページで使われなくなったバージョンが集中的に蓄積されます。 ある種の実装レベルの発見的手法は、均一のごみインデックスタプルの特定及び削除に失敗する可能がありますが、ページの分割は通常避けることができます(ページ分割もしくは重複排除パスの場合に、リーフページ上の収まらない新しいタプルが入ることの問題が解決します)。 インデックススキャンが(単一の論理行に対して)通過しなければならない最悪の場合のバージョン数は、システム全体の応答性やスループットに重要な影響があります。 ボトムアップインデックス削除パスは、論理行とバージョンを含む定性的な特徴に基づいた単一のリーフページ内の疑わしいごみタプルを対象としています。 これは、一定の定量的なテーブルレベルの閾値が超えられたとき(25.1.6参照)に起動されるautovacuumワーカーによって実行されたトップダウンインデックスのクリーンアップと対照的です。

注記

Not all deletion operations that are performed within B-Tree indexes are bottom-up deletion operations. There is a distinct category of index tuple deletion: <firstterm>simple index tuple deletion</firstterm>. This is a deferred maintenance operation that deletes index tuples that are known to be safe to delete (those whose item identifier's <literal>LP_DEAD</literal> bit is already set). Like bottom-up index deletion, simple index deletion takes place at the point that a page split is anticipated as a way of avoiding the split. B-Treeインデックス内で実行されたすべての削除操作がボトムアップ削除操作とは限りません。 インデックスタプルの削除の異なる分類があります。 それは、単純なインデックスのタプル削除です。 これは、削除が安全であると分かるインデックスタプル(アイテム識別子のLP_DEADビットが既に設定されているタプル)を削除する遅延メンテナンス操作です。 ボトムアップインデックス削除と同様に、単純インデックス削除は分割を回避する方法としてページ分割が予測された時点で実行されます。

Simple deletion is opportunistic in the sense that it can only take place when recent index scans set the <literal>LP_DEAD</literal> bits of affected items in passing. Prior to <productname>PostgreSQL</productname> 14, the only category of B-Tree deletion was simple deletion. The main differences between it and bottom-up deletion are that only the former is opportunistically driven by the activity of passing index scans, while only the latter specifically targets version churn from <command>UPDATE</command>s that do not logically modify indexed columns. 単純削除は、最近のインデックススキャンでは影響があるアイテムにLP_DEADビットをセットする際に、ついでに実行できる機会の場合のみに実行されるという意味で、機会主義と言えます。 PostgreSQL 14より前では、B-Treeの削除の種類は単純な削除のみでした。 単純な削除とボトムアップ削除の主な違いは、前者だけがインデックススキャンの動きによって機会を狙って駆動されることに対して、後者だけがインデックスカラムが論理的に変更されないUPDATEからのバージョンチャーンを具体的に対象とすることです。

Bottom-up index deletion performs the vast majority of all garbage index tuple cleanup for particular indexes with certain workloads. This is expected with any B-Tree index that is subject to significant version churn from <command>UPDATE</command>s that rarely or never logically modify the columns that the index covers. The average and worst-case number of versions per logical row can be kept low purely through targeted incremental deletion passes. It's quite possible that the on-disk size of certain indexes will never increase by even one single page/block despite <emphasis>constant</emphasis> version churn from <command>UPDATE</command>s. Even then, an exhaustive <quote>clean sweep</quote> by a <command>VACUUM</command> operation (typically run in an autovacuum worker process) will eventually be required as a part of <emphasis>collective</emphasis> cleanup of the table and each of its indexes. ボトムアップインデックス削除は、明確なワークロードによる特定インデックスのすべてのゴミインデックスタプルの掃除の大多数を実行します。 これは、インデックスがカバーするカラムを論理的に変更することが滅多にまたは決してないUPDATEからの有意なバージョンチャーンに依存するB-Treeインデックスで予想されます。 論理行ごとのバージョン数の平均と最も悪いケースは、対象とされた増分削除パスによって純粋に低く維持することができます。 特定インデックスのディスク上のサイズは、UPDATEからの一定のバージョンチャーンがあるにも関わらず、ページやブロックが一つも増加することがない可能性が十分にあります。 そのような場合でも、VACUUM操作(通常、自動バキュームワーカープロセスで実行します)による、徹底的な一掃が、テーブルとその各インデックスの共通のクリーンアップの一部として最終的に要求されます。

Unlike <command>VACUUM</command>, bottom-up index deletion does not provide any strong guarantees about how old the oldest garbage index tuple may be. No index can be permitted to retain <quote>floating garbage</quote> index tuples that became dead prior to a conservative cutoff point shared by the table and all of its indexes collectively. This fundamental table-level invariant makes it safe to recycle table <acronym>TID</acronym>s. This is how it is possible for distinct logical rows to reuse the same table <acronym>TID</acronym> over time (though this can never happen with two logical rows whose lifetimes span the same <command>VACUUM</command> cycle). VACUUMとは異なり、ボトムアップインデックス削除は最も古いゴミのインデックスタプルがどのくらい経過しているかについて強い保証を提供しません。 テーブルと全てのインデックスの合計によって共通する保守的な切り捨て点より前に、不要になる浮いているゴミインデックスタプルの維持を許可することはできません。 この基本的なテーブルレベルの不変条件は、テーブルのTIDを安全にリサイクルします。 これにより、時間の経過と共に異なる論理行が同じテーブルTIDを再利用することが可能です(ただし、これは存続期間が同じVACUUMサイクルにまたがる、二つの論理行に同時には発生しません)。

67.4.3. 重複排除 #

<title>Deduplication</title>

A duplicate is a leaf page tuple (a tuple that points to a table row) where <emphasis>all</emphasis> indexed key columns have values that match corresponding column values from at least one other leaf page tuple in the same index. Duplicate tuples are quite common in practice. B-Tree indexes can use a special, space-efficient representation for duplicates when an optional technique is enabled: <firstterm>deduplication</firstterm>. 重複とは、同じインデックスで全てのインデックスキー列が少なくとも一つの他のリーフページタプルの該当する列の値と一致する値をもっている、リーフページタプル(テーブルの行を指すタプル)です。 重複タプルは実際によくあります。 オプションの技法「重複排除」が有効にされているとき、B-Treeインデックスは、特別な重複に対する空間効率の良い表現方法を使用できます。

Deduplication works by periodically merging groups of duplicate tuples together, forming a single <firstterm>posting list</firstterm> tuple for each group. The column key value(s) only appear once in this representation. This is followed by a sorted array of <acronym>TID</acronym>s that point to rows in the table. This significantly reduces the storage size of indexes where each value (or each distinct combination of column values) appears several times on average. The latency of queries can be reduced significantly. Overall query throughput may increase significantly. The overhead of routine index vacuuming may also be reduced significantly. 重複排除は重複タプルのグループを定期的に合併して、各グループに対する単一のポスティングリストタプルを形成することで機能します。 この表現方法では列のキー値は一度だけ現れます。 テーブルの行を指すTIDのソートされた配列がこれに続きます。 概して各値(あるいは列値の異なる組み合わせ)が複数回出現する場合に、これは顕著にインデックスの格納サイズを減らします。 問い合わせの遅延も顕著に削減できます。 全体的な問い合わせのスループットも顕著に増加するかもしれません。 インデックスのバキューム処理のオーバーヘッドも顕著に削減されるかもしれません。

注記

B-Tree deduplication is just as effective with <quote>duplicates</quote> that contain a NULL value, even though NULL values are never equal to each other according to the <literal>=</literal> member of any B-Tree operator class. As far as any part of the implementation that understands the on-disk B-Tree structure is concerned, NULL is just another value from the domain of indexed values. B-Tree重複排除は、B-Tree演算子クラスの=項に従ってNULL値が決して互いに等しくならないとしても、NULL値を含む重複に効果的です。 ディスク上のB-Tree構造を解するいかなる実装部分に関しても、NULLはまさにインデックス値の定義域以外の一つの値です。

The deduplication process occurs lazily, when a new item is inserted that cannot fit on an existing leaf page, though only when index tuple deletion could not free sufficient space for the new item (typically deletion is briefly considered and then skipped over). Unlike GIN posting list tuples, B-Tree posting list tuples do not need to expand every time a new duplicate is inserted; they are merely an alternative physical representation of the original logical contents of the leaf page. This design prioritizes consistent performance with mixed read-write workloads. Most client applications will at least see a moderate performance benefit from using deduplication. Deduplication is enabled by default. 既存のリーフページに収まらない新たな要素が挿入されたとき、重複排除の処理は怠惰に実行されますが、インデックスタプルの削除は新しいアイテムのための十分なスペースを解放できなかった場合に限ります(通常、削除は簡易に検討した上で無視されます)。 GINのポスティングリストのタプルと違って、B-Treeのポスティングリストのタプルは新たな重複が挿入される度に拡張する必要がありません。それらはリーフページの元の論理内容に対する単なる代替の物理表現にすぎません。 この設計は読み書き混合のワークロードでの性能の一貫性を重視しています。 ほとんどのクライアントアプリケーションは重複排除を使うことで少なくとも控えめな性能の恩恵を確認することができるでしょう。

<command>CREATE INDEX</command> and <command>REINDEX</command> apply deduplication to create posting list tuples, though the strategy they use is slightly different. Each group of duplicate ordinary tuples encountered in the sorted input taken from the table is merged into a posting list tuple <emphasis>before</emphasis> being added to the current pending leaf page. Individual posting list tuples are packed with as many <acronym>TID</acronym>s as possible. Leaf pages are written out in the usual way, without any separate deduplication pass. This strategy is well-suited to <command>CREATE INDEX</command> and <command>REINDEX</command> because they are once-off batch operations. CREATE INDEXREINDEXは、使用する手順が若干異なりますが、ポスティングリストタプルを作って重複排除を適用します。 テーブルから取得されてソートされた入力で遭遇した重複した通常タプルの各グループは、現在のペンディングリーフページに追加される前に、ポスティングリストタプルにマージされます。 個別のポスティングリストタプルには、可能な限り多数のTIDが詰め込まれます。 リーフページは、重複排除用の別パスではなく、通常の方法で書き出されます。 この戦略はCREATE INDEXREINDEXに良く適合します。これらは1回で終わるバッチ操作であるからです。

Write-heavy workloads that don't benefit from deduplication due to having few or no duplicate values in indexes will incur a small, fixed performance penalty (unless deduplication is explicitly disabled). The <literal>deduplicate_items</literal> storage parameter can be used to disable deduplication within individual indexes. There is never any performance penalty with read-only workloads, since reading posting list tuples is at least as efficient as reading the standard tuple representation. Disabling deduplication isn't usually helpful. インデックスの値に重複が無いか殆ど無いために重複排除から利益を得られない、書き込みの多いワークロードには、(重複排除が明示的に無効化されて居ない限り)固定のペナルティによる小さい負荷増があります。 deduplicate_items格納パラメータは個別のインデックス内で重複排除を無効化するのに使うことができます。 ポスティングリストタプルの読み込みは少なくとも通常タプル表現の読み込み程度に効率的であるため、読み込みのみのワークロードで性能ペナルティは一切ありません 通常は重複排除を無効化することは有益ではありません。

It is sometimes possible for unique indexes (as well as unique constraints) to use deduplication. This allows leaf pages to temporarily <quote>absorb</quote> extra version churn duplicates. Deduplication in unique indexes augments bottom-up index deletion, especially in cases where a long-running transaction holds a snapshot that blocks garbage collection. The goal is to buy time for the bottom-up index deletion strategy to become effective again. Delaying page splits until a single long-running transaction naturally goes away can allow a bottom-up deletion pass to succeed where an earlier deletion pass failed. 一意性インデックス(や一意制約)が重複排除に使用できる場合があります。 これにより、リーフページは余分なバージョンチャーンの重複を一時的に吸収することができます。 一意性インデックス内の重複排除は、特に時間のかかるトランザクションがガベージコレクションを妨げるスナップショットを保持している場合にボトムアップインデックス削除を増強します。 目的は、ボトムアップインデックス削除の戦略が再び有効になるための時間を稼ぐことです。 一つの時間のかかるトランザクションが自然に消えるまでページ分割を遅らせることで、以前の削除パスが失敗した場所でボトムアップ削除パスを成功することができます。

ヒント

A special heuristic is applied to determine whether a deduplication pass in a unique index should take place. It can often skip straight to splitting a leaf page, avoiding a performance penalty from wasting cycles on unhelpful deduplication passes. If you're concerned about the overhead of deduplication, consider setting <literal>deduplicate_items = off</literal> selectively. Leaving deduplication enabled in unique indexes has little downside. 一意性インデックスで重複排除パスを実行すべきかどうかの判断には、特別なヒューリスティックが適用されます。 これは、しばしばリーフページ分割まで連続してスキップして、無益な重複排除パスでの無駄なサイクルによる性能ペナルティを回避できます。 重複排除のオーバーヘッドを懸念するなら、選択的に設定deduplicate_items = offを検討してください。 一意性インデックスでは重複排除を無効にすることに不都合はありません。

Deduplication cannot be used in all cases due to implementation-level restrictions. Deduplication safety is determined when <command>CREATE INDEX</command> or <command>REINDEX</command> is run. 実装レベルの制限により、重複排除は全ての場合に使えるわけではありません。 重複排除の安全性はCREATE INDEXあるいはREINDEXが実行されたときに決定されます。

Note that deduplication is deemed unsafe and cannot be used in the following cases involving semantically significant differences among equal datums: 等しいデータの間で意味的に明らかな違いを伴う以下の場合には、重複排除は安全でないと見做されて使用できないことに注意してください。

  • <type>text</type>, <type>varchar</type>, and <type>char</type> cannot use deduplication when a <emphasis>nondeterministic</emphasis> collation is used. Case and accent differences must be preserved among equal datums. 非決定的な照合順序が使われているときtextvarchar、および、charは重複排除を使えません。 等しいデータの間で大文字小文字やアクセントの違いが維持されなければなりません。

  • <type>numeric</type> cannot use deduplication. Numeric display scale must be preserved among equal datums. numericは重複排除を使えません。 等しいデータの間で数の表示スケールが維持されなければなりません。

  • <type>jsonb</type> cannot use deduplication, since the <type>jsonb</type> B-Tree operator class uses <type>numeric</type> internally. jsonbのB-Tree演算子クラスは内部的にnumericを使っているため、jsonbは重複排除を使えません。

  • <type>float4</type> and <type>float8</type> cannot use deduplication. These types have distinct representations for <literal>-0</literal> and <literal>0</literal>, which are nevertheless considered equal. This difference must be preserved. float4およびfloat8は重複排除を使えません。 これらの型は-00に異なる表現を持ち、にもかかわらずこれらは等しいと見做されます。 この違いは維持されなければなりません。

There is one further implementation-level restriction that may be lifted in a future version of <productname>PostgreSQL</productname>: さらに以下の実装レベルの制限があります。これはPostgreSQLの将来バージョンで解消されるかもしれません。

  • Container types (such as composite types, arrays, or range types) cannot use deduplication. コンテナ型(複合型、配列型、あるいは、範囲型など)は、重複排除を使えません。

There is one further implementation-level restriction that applies regardless of the operator class or collation used: さらに以下の実装レベルの制限があります。これは使われている演算子クラスや照合順序にかかわりなく該当します。

  • <literal>INCLUDE</literal> indexes can never use deduplication. INCLUDEインデックスには重複排除は使えません。