> For the complete documentation index, see [llms.txt](https://docs.postgresql.tw/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.postgresql.tw/19/internals/indexam/index-locking.md). Agents can also search and read this documentation through its [MCP server](https://docs.postgresql.tw/~gitbook/mcp).

# 63.4. 索引鎖定的考量 \#

### 63.4. 索引鎖定的考量 [#](#index-locking) <a href="#index-locking" id="index-locking"></a>

索引存取方法必須處理多個程序對索引的並行更新。PostgreSQL 核心系統在索引掃描期間會對索引取得 `AccessShareLock`，在更新索引時（包括一般的 `VACUUM`）則取得 `RowExclusiveLock`。由於這些鎖定類型彼此不衝突，存取方法要負責處理它可能需要的任何細粒度鎖定。只有在建立、移除索引或執行 `REINDEX` 時，才會對整個索引取得 `ACCESS EXCLUSIVE` 鎖定（使用 `CONCURRENTLY` 時則改為取得 `SHARE UPDATE EXCLUSIVE`）。

建構支援並行更新的索引類型，通常需要對所需行為進行廣泛而細緻的分析。關於 b-tree 與雜湊索引類型所涉及的設計決策，你可以閱讀 `src/backend/access/nbtree/README` 與 `src/backend/access/hash/README`。

除了索引本身的內部一致性要求之外，並行更新也會造成父資料表（*堆積*）與索引之間的一致性問題。由於 PostgreSQL 將堆積的存取與更新和索引的存取與更新分開進行，因此會有一些時間窗口，在其中索引可能與堆積不一致。我們以下列規則處理這個問題：

* 新的堆積項目會在建立其索引項目之前建立。（因此並行的索引掃描很可能看不到該堆積項目。這沒有問題，因為索引讀取者本來就不會關心未提交的資料列。但請參閱[第 63.5 節](https://docs.postgresql.tw/19/internals/indexam/index-unique-checks.md)。）
* 當某個堆積項目要被刪除（由 `VACUUM`）時，必須先移除它所有的索引項目。
* 索引掃描必須對存放 `amgettuple` 最後傳回之項目的索引頁面維持釘住（pin），而 `ambulkdelete` 不能從被其他後端釘住的頁面中刪除項目。這條規則的必要性將在下文說明。

若沒有第三條規則，索引讀取者就可能在某個索引項目被 `VACUUM` 移除之前看到它，然後在對應的堆積項目被 `VACUUM` 移除之後才到達該堆積項目。如果讀取者到達時該項目編號仍未被使用，這不會造成嚴重問題，因為 `heap_fetch()` 會忽略空的項目槽。但如果第三個後端已經把該項目槽重新用於其他東西呢？使用符合 MVCC 的快照時不會有問題，因為該槽的新佔用者一定太新而無法通過快照測試。然而，若使用不符合 MVCC 的快照（例如 `SnapshotAny`），就可能接受並傳回一個實際上並不符合掃描鍵的資料列。我們可以藉由要求在所有情況下都對堆積資料列重新檢查掃描鍵來防範這種情境，但這樣代價太高。因此，我們改用索引頁面上的釘住作為代理指標，表示讀取者可能仍處於從索引項目前往對應堆積項目的「途中」。讓 `ambulkdelete` 因這種釘住而阻塞，就能確保 `VACUUM` 無法在讀取者處理完該堆積項目之前將其刪除。這個解法的執行時期成本很低，而且只有在真的發生衝突的少數情況下才會增加阻塞的額外負擔。

這個解法要求索引掃描必須是「同步」的：我們必須在掃描對應的索引項目後，立即擷取每一個堆積元組。基於許多原因，這樣做的代價很高。「非同步」掃描是先從索引收集許多 TID，稍後才去存取堆積元組；這種掃描所需的索引鎖定負擔小得多，而且可以採用更有效率的堆積存取模式。依據上述分析，對於不符合 MVCC 的快照，我們必須使用同步的方式，但對於使用 MVCC 快照的查詢，非同步掃描是可行的。

在 `amgetbitmap` 索引掃描中，存取方法不會對任何傳回的元組保留索引釘住。因此，只有搭配符合 MVCC 的快照時，使用這種掃描才是安全的。

若未設定 `ampredlocks` 旗標，則在可序列化交易中使用該索引存取方法的任何掃描，都會對整個索引取得非阻塞的謂詞鎖。這會與並行的可序列化交易將任何元組插入該索引的動作產生讀寫衝突。如果在一組並行的可序列化交易之間偵測到特定模式的讀寫衝突，可能會取消其中一個交易以保護資料完整性。設定此旗標時，表示該索引存取方法實作了更細粒度的謂詞鎖定，這往往會降低此類交易被取消的頻率。

***

原文：[PostgreSQL 18.6 Documentation](https://www.postgresql.org/docs/18/index-locking.html)（原文版本：18.6；核對日期：2026-10-17）


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.postgresql.tw/19/internals/indexam/index-locking.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
