

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 屬性圖表結構描述
<a name="access-graph-pg-schema"></a>

`neptune.graph.pg_schema()` 此程序提供 屬性圖形結構的完整概觀。它會傳回所有節點標籤、邊緣標籤、屬性及其資料類型，以及標籤三元組 (`{~from, ~type, ~to}`描述節點類型如何透過邊緣類型連線的模式）。

此程序目前只能透過 openCypher 端點使用，並探索所有屬性圖形資料的結構描述。

針對下列任務使用此程序：
+ **AI 和 LLM 查詢產生** – 為 LLMs提供從自然語言 (Text-to-Cypher 查詢所需的圖形結構。 GraphRAG 
+ **圖形視覺化和探索** – [Graph Explorer](visualization-graph-explorer.md) 等工具使用結構描述資訊來呈現圖形資料的互動式視覺化呈現，而無需掃描整個資料庫。
+ **應用程式結構描述探索** – 在啟動時需要了解圖形結構的應用程式，例如 GraphQL 結構描述產生器或資料驗證工具。

## 與 Neptune Analytics 的比較
<a name="access-graph-pg-schema-comparison-analytics"></a>

在 Neptune Analytics 中， [`neptune.graph.pg_schema()`](https://docs.aws.amazon.com/neptune-analytics/latest/userguide/custom-algorithms-property-graph-schema.html) 是同步的。它會計算每次呼叫的結構描述。

在 Neptune 資料庫，您可以透過呼叫 明確觸發非同步結構描述運算`neptune.graph.pg_schema.compute()`，這會立即傳回。當您使用 輪詢完成時，運算會在背景執行`neptune.graph.pg_schema()`。計算後，Neptune 會保留結構描述，並在後續讀取時立即傳回結構描述，而無需重新計算。運算仍在進行中時，也提供部分結果。您也可以停止執行中的運算，稍後再繼續。

## 與圖形摘要 API 的比較
<a name="access-graph-pg-schema-comparison-summary"></a>

[圖形摘要 API](neptune-graph-summary.md) 不提供標籤三元組或屬性資料類型。屬性圖表結構描述程序會填滿此間隙。標籤三元組會顯示圖形中的特定關係模式。例如， `Company`會透過`worksAt`邊緣`Person`連線至 。此資訊對於 LLMs 產生語義正確的查詢至關重要。

## 先決條件
<a name="access-graph-pg-schema-prerequisites"></a>

### 引擎版本
<a name="access-graph-pg-schema-engine-version"></a>

屬性圖表結構描述程序需要 Neptune 引擎 1.4.8.0 版或更新版本。

### IAM 許可
<a name="access-graph-pg-schema-iam"></a>

每個結構描述操作都需要下列 IAM 動作：
+ `CALL neptune.graph.pg_schema()` – 需要 `neptune-db:ReadDataViaQuery`。
+ `CALL neptune.graph.pg_schema.compute()` – 需要 `neptune-db:ReadDataViaQuery`和 `neptune-db:WriteDataViaQuery`。
+ `CALL neptune.graph.pg_schema.stop()` – 需要 `neptune-db:ReadDataViaQuery`和 `neptune-db:WriteDataViaQuery`。

`compute()` 和 `stop()`操作需要寫入許可，因為它們會修改用來快取和保留結構描述的內部狀態。

**Example IAM 政策範例**  
下列政策會授予所有結構描述操作所需的最低許可：  

```
{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Action": [
      "neptune-db:ReadDataViaQuery",
      "neptune-db:WriteDataViaQuery"
    ],
    "Resource": "arn:aws:neptune-db:us-east-1:123456789012:cluster-resource-id/*"
  }]
}
```

若要授予結構描述的唯讀存取權 （無法觸發運算），請僅使用 `neptune-db:ReadDataViaQuery`。

### 寫入器和讀取器執行個體
<a name="access-graph-pg-schema-writer-reader"></a>

您只能在寫入器執行個體上觸發結構描述運算。僅供讀取複本執行個體可以讀取結構描述 （從寫入器複寫），但無法執行 `compute()`或 `stop()`。

## API 參考
<a name="access-graph-pg-schema-api"></a>

### 讀取結構描述
<a name="access-graph-pg-schema-read"></a>

擷取目前的結構描述和運算狀態。

**語法:**

------
#### [ AWS CLI ]

```
aws neptunedata execute-open-cypher-query \
  --endpoint-url https://{{your-neptune-endpoint}}:{{port}} \
  --open-cypher-query "CALL neptune.graph.pg_schema()"
```

------
#### [ SDK ]

```
import boto3
from botocore.config import Config

client = boto3.client(
    'neptunedata',
    endpoint_url='https://{{your-neptune-endpoint}}:{{port}}',
    config=Config(read_timeout=None, retries={'total_max_attempts': 1})
)

response = client.execute_open_cypher_query(
    openCypherQuery='CALL neptune.graph.pg_schema()'
)

print(response)
```

------
#### [ awscurl ]

```
awscurl -X POST https://{{your-neptune-endpoint}}:{{port}}/openCypher \
  -H "Content-Type: application/x-www-form-urlencoded" \
  --region {{us-east-1}} --service neptune-db \
  -d 'query=CALL neptune.graph.pg_schema()'
```

------

**行為：**立即傳回目前的結構描述和狀態。一律非封鎖。如果尚未計算結構描述， 會傳回狀態： `"NotStarted"`與空白結構描述欄位。如果運算正在進行中， 會傳回狀態為 的部分結果`"InProgress"`。

**回應格式：**

回應包含具有下列欄位的結構描述物件：

**狀態物件：**
+ `state` （字串） – 目前生命週期狀態：`NotStarted`、`InProgress`、`Completed`、`Stopped`、 `Failed`
+ `concurrency` （字串） – 用於運算的執行緒數量。0 表示自動 （根據硬體決定）。範圍：1 （最低） 到 16 （最高）。
+ `lastComputedTimestamp` （字串） – 上次成功運算的 ISO-8601 UTC 時間戳記 （例如 `2026-05-29T08:00:00Z`)
+ `progressPercentage` （字串） – 運算進度：未啟動時為 0，運算期間為 0–99，完成時為 100
+ `errorMessage` （字串） – 只有在請求遭拒或運算失敗時才會顯示。說明原因。

**結構描述物件：**
+ `nodeLabels` – 圖形中所有唯一節點標籤的陣列
+ `edgeLabels` – 圖形中所有唯一邊緣標籤的陣列
+ `nodeLabelDetails` – 針對每個節點標籤：屬性及其資料類型
+ `edgeLabelDetails` – 對於每個邊緣標籤：屬性及其資料類型
+ `labelTriples` – 關係模式陣列：`{~from, ~type, ~to}`描述哪些節點類型透過哪些節點類型連接

**支援的資料類型：**`String`、`Int`、`Long`、`Double`、`Bool`、 `Date`

如果屬性在不同節點之間有多個資料類型 （例如，某些節點會以 `age`形式存放`Int`，而其他節點則以 形式存放`String`)，則所有觀察到的類型都會列在`datatypes`陣列中。

### 運算結構描述
<a name="access-graph-pg-schema-compute"></a>

觸發背景結構描述運算。

**語法:**

------
#### [ AWS CLI ]

```
aws neptunedata execute-open-cypher-query \
  --endpoint-url https://{{your-neptune-endpoint}}:{{port}} \
  --open-cypher-query "CALL neptune.graph.pg_schema.compute()"
```

使用選用並行參數：

```
aws neptunedata execute-open-cypher-query \
  --endpoint-url https://{{your-neptune-endpoint}}:{{port}} \
  --open-cypher-query "CALL neptune.graph.pg_schema.compute({concurrency: 2})"
```

------
#### [ SDK ]

```
import boto3
from botocore.config import Config

client = boto3.client(
    'neptunedata',
    endpoint_url='https://{{your-neptune-endpoint}}:{{port}}',
    config=Config(read_timeout=None, retries={'total_max_attempts': 1})
)

response = client.execute_open_cypher_query(
    openCypherQuery='CALL neptune.graph.pg_schema.compute()'
)

print(response)
```

------
#### [ awscurl ]

```
awscurl -X POST https://{{your-neptune-endpoint}}:{{port}}/openCypher \
  -H "Content-Type: application/x-www-form-urlencoded" \
  --region {{us-east-1}} --service neptune-db \
  -d 'query=CALL neptune.graph.pg_schema.compute()'
```

使用選用並行參數：

```
awscurl -X POST https://{{your-neptune-endpoint}}:{{port}}/openCypher \
  -H "Content-Type: application/x-www-form-urlencoded" \
  --region {{us-east-1}} --service neptune-db \
  -d 'query=CALL neptune.graph.pg_schema.compute({concurrency: 2})'
```

------

**所需的 IAM 動作：** `neptune-db:ReadDataViaQuery` 和 `neptune-db:WriteDataViaQuery`

**參數：**
+ `concurrency` （整數，選用） – 背景運算的執行緒數目。0 （預設） = 根據硬體自動決定。範圍：1 （最低） 到 16 （最高）。在較小的執行個體上使用較低的值，以減少資源影響。

**行為：**
+ 立即以目前狀態傳回 。運算會在背景中以非同步方式執行。
+ 如果 狀態為 時呼叫 `Stopped`，則運算會從停止的位置繼續。
+ 如果在狀態為 時呼叫 `Completed`， 會啟動新的重新計算。先前的結構描述會繼續提供讀取，直到新的運算完成為止。
+ 如果在運算已為 時呼叫 `InProgress`，Neptune 會拒絕具有錯誤訊息的請求。
+ 如果在作用中大量載入期間呼叫 ，Neptune 會拒絕具有錯誤訊息的請求。

**回應：**傳回顯示狀態的狀態物件： `"InProgress"` 與 `concurrency` `progressPercentage` 欄位。

### 停止結構描述運算
<a name="access-graph-pg-schema-stop"></a>

停止執行中的背景運算。

**語法:**

------
#### [ AWS CLI ]

```
aws neptunedata execute-open-cypher-query \
  --endpoint-url https://{{your-neptune-endpoint}}:{{port}} \
  --open-cypher-query "CALL neptune.graph.pg_schema.stop()"
```

------
#### [ SDK ]

```
import boto3
from botocore.config import Config

client = boto3.client(
    'neptunedata',
    endpoint_url='https://{{your-neptune-endpoint}}:{{port}}',
    config=Config(read_timeout=None, retries={'total_max_attempts': 1})
)

response = client.execute_open_cypher_query(
    openCypherQuery='CALL neptune.graph.pg_schema.stop()'
)

print(response)
```

------
#### [ awscurl ]

```
awscurl -X POST https://{{your-neptune-endpoint}}:{{port}}/openCypher \
  -H "Content-Type: application/x-www-form-urlencoded" \
  --region {{us-east-1}} --service neptune-db \
  -d 'query=CALL neptune.graph.pg_schema.stop()'
```

------

**所需的 IAM 動作：** `neptune-db:ReadDataViaQuery` 和 `neptune-db:WriteDataViaQuery`

**行為：**
+ 停止執行中的運算。系統會儲存進度，以便在`compute()`再次呼叫時，從停止的位置繼續。
+ 停止的運算*不會*在引擎重新啟動時自動恢復。您必須明確呼叫 `compute()`。

**回應：**傳回顯示狀態的狀態物件：`"Stopped"`使用目前的 `progressPercentage`。

## 搭配結構描述結果使用 YIELD
<a name="access-graph-pg-schema-yield"></a>

您可以使用 `YIELD`擷取結構描述欄位，並將其與其他查詢結合。下列範例會擷取所有節點標籤，並計算每個標籤的節點數量。`collSort()` 函數會依字母順序排序清單：

```
CALL neptune.graph.pg_schema()
  YIELD schema
  WITH schema.nodeLabels as nl
  UNWIND collSort(nl) as label
  MATCH (n)
  WHERE label in labels(n)
  RETURN label, COUNT(n) as count
```

輸出範例：

```
{
  "results": [{
      "label": "airport",
      "count": 3503
    }, {
      "label": "continent",
      "count": 7
    }, {
      "label": "country",
      "count": 237
    }, {
      "label": "version",
      "count": 1
    }]
}
```

## 結構描述運算生命週期
<a name="access-graph-pg-schema-lifecycle"></a>

### 非同步操作
<a name="access-graph-pg-schema-async"></a>

結構描述運算是一種非同步操作。當您呼叫 時`neptune.graph.pg_schema.compute()`，它會立即傳回目前狀態。運算會在背景執行。您可以透過呼叫 來輪詢進度和完成`neptune.graph.pg_schema()`，這會傳回目前狀態 和 `progressPercentage`。

### 州 (States)
<a name="access-graph-pg-schema-states"></a>

結構描述運算會移動到下列狀態：
+ `NotStarted` – 尚未計算結構描述。 `pg_schema()`會傳回空的結構描述。
+ `InProgress` – 正在執行背景運算。 `pg_schema()`會傳回部分結果 （最後一個完整結構描述的聯集，以及目前運算的探索）。
+ `Completed` – 運算成功完成。完整的結構描述可供使用。
+ `Stopped` – 運算已停止，方法是呼叫 `stop()`或 ，因為引擎重新啟動中斷運算。有部分結果可用。系統會儲存進度，讓運算可以在您呼叫 時從中斷的地方繼續`compute()`。
+ `Failed` – 運算發生錯誤。上次成功計算的結構描述 （如果有的話） 仍然可用。

### 持續性和重新啟動行為
<a name="access-graph-pg-schema-persistence"></a>

計算的結構描述會持續存在，並且可以承受引擎重新啟動。重新啟動行為取決於重新啟動時的狀態：
+ `InProgress` – 如果引擎在運算期間重新啟動，則運算會轉換為 `Stopped`。從停止的地方呼叫 `compute()`以繼續。系統會保留進度，並從其最後一個檢查點繼續運算。
+ `Stopped` – 運算*不會*自動繼續。您必須呼叫 從停止的地方`compute()`繼續。
+ `Completed` – 結構描述已載入並立即可用。

### 部分結果
<a name="access-graph-pg-schema-partial"></a>

當運算正在進行時， `pg_schema()`會傳回部分結果。這包括任何先前完成的結構描述，與目前運算中探索到的標籤、屬性和三元組合併。這表示您不需要等待完整運算完成，即可擷取有用的結構描述資訊。

### 僅供讀取複本
<a name="access-graph-pg-schema-replicas"></a>

僅供讀取複本執行個體可以使用 讀取結構描述`CALL neptune.graph.pg_schema()`。Neptune 會從寫入器執行個體複寫結構描述，並在寫入器上發現結構描述元素時，在複本上幾乎立即可用。

僅供讀取複本無法執行 `compute()`或 `stop()`。這些呼叫會傳回錯誤：
+ `compute()` – `"Schema cannot be computed on read replica"`
+ `stop()` – `"Schema compute cannot be stopped on read replica"`

## 最佳實務
<a name="access-graph-pg-schema-best-practices"></a>
+ **變動後重新計算** – 當資料變更時，結構描述不會自動更新。在大量載入或重大資料變動後重新計算結構描述。使用 `lastComputedTimestamp` 欄位來判斷結構描述是否相對於圖形中的最近變更過時。
+ **並行** – 預設並行值 (0) 會自動適應您的執行個體硬體。對於大多數工作負載，這是建議的設定。如果背景運算會影響查詢工作負載，請指定較低的值 （例如 1 或 2) 以減少資源用量。
+ **停止和繼續** – 如果背景運算會影響您的查詢工作負載，請使用 將其停止，`stop()`並在較低的流量期間`compute()`再次呼叫 以繼續。運算會從停止的位置繼續。
+ **正常處理重新啟動** – 如果引擎在結構描述運算進行時重新啟動，則運算會轉換為 `Stopped`。從停止的地方呼叫 `compute()`以繼續。系統會保留進度。
+ **大型資料庫** – 對於具有大型儲存磁碟區的資料庫 （多個 TB)，完整的結構描述運算可能需要較長的時間。您可以啟動運算，讓它執行到 10–20% 的進度，然後停止。在此時段收集的部分結果可提供實用的結構描述範例，其中包含許多已探索的標籤、屬性和三元組。在`pg_schema()`運算進行中或停止後，使用 讀取部分結構描述。當您的工作負載允許時，稍後繼續。

## 限制
<a name="access-graph-pg-schema-limitations"></a>
+ **刪除需要重新計算** – 刪除的標籤、屬性和三元組只會在下一次完全重新計算後從結構描述中移除。在此之前，已刪除的元素仍會出現在結構描述結果中。
+ **僅限 OpenCypher ** – 您只能透過 openCypher 查詢端點呼叫此程序。
+ **無法在大量載入期間運算** – Neptune 會在大量載入操作作用中時拒絕結構描述運算。大量載入完成後觸發運算。

## 範例輸出
<a name="access-graph-pg-schema-sample"></a>

下列範例顯示 air-routes 資料集的結構描述輸出：

```
awscurl -X POST https://{{your-neptune-endpoint}}:{{port}}/openCypher \
  -H "Content-Type: application/x-www-form-urlencoded" \
  --region {{us-east-1}} --service neptune-db \
  -d 'query=CALL neptune.graph.pg_schema()'
```

```
{
  "results": [{
      "schema": {
        "edgeLabelDetails": {
          "route": {
            "properties": {
              "dist": ["Int"]
            }
          },
          "contains": {
            "properties": {}
          }
        },
        "edgeLabels": ["route", "contains"],
        "status": {
          "concurrency": "16",
          "lastComputedTimestamp": "2026-06-04T23:58:17Z",
          "state": "Completed",
          "progressPercentage": "100"
        },
        "nodeLabels": ["version", "continent", "airport", "country"],
        "labelTriples": [{
            "~type": "route",
            "~from": "airport",
            "~to": "airport"
          }, {
            "~type": "contains",
            "~from": "country",
            "~to": "airport"
          }, {
            "~type": "contains",
            "~from": "continent",
            "~to": "airport"
          }],
        "nodeLabelDetails": {
          "continent": {
            "properties": {
              "type": ["String"],
              "code": ["String"],
              "desc": ["String"]
            }
          },
          "airport": {
            "properties": {
              "type": ["String"],
              "city": ["String"],
              "icao": ["String"],
              "code": ["String"],
              "country": ["String"],
              "lat": ["Double"],
              "longest": ["Int"],
              "runways": ["Int"],
              "desc": ["String"],
              "lon": ["Double"],
              "region": ["String"],
              "elev": ["Int"]
            }
          },
          "country": {
            "properties": {
              "type": ["String"],
              "code": ["String"],
              "desc": ["String"]
            }
          },
          "version": {
            "properties": {
              "date": ["String"],
              "desc": ["String"],
              "author": ["String"],
              "type": ["String"],
              "code": ["String"]
            }
          }
        }
      }
    }]
}
```