

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

# 支援 Gremlin 指令碼型工作階段
<a name="access-graph-gremlin-sessions"></a>

您可以在 Amazon Neptune 中使用 Gremlin 工作階段搭配隱含交易。如需 Gremlin 工作階段的相關資訊，請參閱 Apache TinkerPop 文件中的[考量工作階段](http://tinkerpop.apache.org/docs/current/reference/#sessions)。下面章節描述如何使用 Gremlin 工作階段搭配 Java。

**重要**  
目前 Neptune 可保持指令碼型工作階段開啟的最長時間是 10 分鐘。如果不在此時前關閉工作階段，工作階段會逾時，並轉返其中所有內容。

**Topics**
+ [Gremlin 主控台上的 Gremlin 工作階段](#access-graph-gremlin-sessions-console)
+ [Gremlin 語言變體中的 Gremlin 工作階段](#access-graph-gremlin-sessions-glv)

## Gremlin 主控台上的 Gremlin 工作階段
<a name="access-graph-gremlin-sessions-console"></a>

如果您在 Gremlin 主控台建立遠端連線，而沒有 `session` 參數，則遠端連線會以「無工作階段」**模式建立。在此模式中，每個提交至伺服器的請求本身都會視為完整交易，而且請求之間不會儲存狀態。如果請求失敗，只會轉返該請求。

如果您建立確實會**使用 `session` 參數的遠端連線，則您建立的指令碼型工作階段會持續到您關閉遠端連線為止。每個工作階段都由一個主控台產生並傳回給您的唯一 UUID 識別。

以下是建立工作階段的主控台呼叫範例。提交查詢之後，另一個呼叫會關閉工作階段並遞交查詢。

**注意**  
Gemlin 用戶端必須始終關閉才能釋出伺服器端資源。

```
gremlin> :remote connect tinkerpop.server conf/neptune-remote.yaml session
  . . .
  . . .
gremlin> :remote close
```

如需詳細資訊和範例 , 請參閱 TinkerPop 文件中的[工作階段](http://tinkerpop.apache.org/docs/current/reference/#console-sessions)。

您在工作階段期間執行的所有查詢都會形成單一交易，直到所有查詢成功且關閉遠端連線才會遞交。如有某個查詢失敗，或者您未在 Neptune 支援的最長工作階段生命週期內關閉連線，則工作階段交易不會遞交，並轉返其中所有查詢。

## Gremlin 語言變體中的 Gremlin 工作階段
<a name="access-graph-gremlin-sessions-glv"></a>

在 Gremlin 語言變體 (GLV) 中，您需要建立 `SessionedClient` 物件，以單一交易發出多個查詢，如下列範例所示。

```
try {                              // line 1
  Cluster cluster = Cluster.open();                    // line 2
  Client client = cluster.connect("sessionName");      // line 3
   ...
   ...
} finally {
  // Always close. If there are no errors, the transaction is committed; otherwise, it's rolled back.
  client.close();
}
```

上述範例中的第 3 行根據針對有問題之叢集所設定的組態選項，建立 `SessionedClient` 物件。您傳送到連線方法的 *sessionName* 字串會成為此工作階段的唯一名稱。若要避免衝突，名稱請使用 UUID。

用戶端會在初始化時啟動工作階段交易。只有在您呼叫 `client.close( )` 時，您在工作階段表單期間執行的所有查詢才會遞交。同樣地，如有單一查詢失敗，或者您未在 Neptune 支援的最長工作階段生命週期內關閉連線，則工作階段交易會失敗，並轉返其中所有查詢。

**注意**  
Gemlin 用戶端必須始終關閉才能釋出伺服器端資源。

```
GraphTraversalSource g = traversal().withRemote(conn);

Transaction tx = g.tx();

// Spawn a GraphTraversalSource from the Transaction.
// Traversals spawned from gtx are executed within a single transaction.
GraphTraversalSource gtx = tx.begin();
try {
  gtx.addV('person').iterate();
  gtx.addV('software').iterate();

  tx.commit();
} finally {
    if (tx.isOpen()) {
        tx.rollback();
    }
}
```