

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

# 使用 AWS SDK 執行 Gremlin 查詢
<a name="access-graph-gremlin-sdk"></a>

使用 AWS SDK，您可以使用您選擇的程式設計語言，針對 Neptune 圖形執行 Gremlin 查詢。Neptune 資料 API SDK （服務名稱 `neptunedata`) 提供提交 Gremlin 查詢的 [ExecuteGremlinQuery](https://docs.aws.amazon.com/neptune/latest/data-api/API_ExecuteGremlinQuery.html) 動作。

您必須從與 Neptune 資料庫叢集相同的虛擬私有雲端 (VPC) 中的 Amazon EC2 執行個體，或從與叢集端點具有網路連線的位置執行這些範例。

每個 SDK 語言`neptunedata`的服務 API 參考文件的直接連結如下所示：


| 程式設計語言 | neptunedata API 參考 | 
| --- | --- | 
| C\+\+ | [https://sdk.amazonaws.com/cpp/api/LATEST/aws-cpp-sdk-neptunedata/html/annotated.html](https://sdk.amazonaws.com/cpp/api/LATEST/aws-cpp-sdk-neptunedata/html/annotated.html) | 
| Go | [https://docs.aws.amazon.com/sdk-for-go/api/service/neptunedata/](https://docs.aws.amazon.com/sdk-for-go/api/service/neptunedata/) | 
| Java | [https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/neptunedata/package-summary.html](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/neptunedata/package-summary.html) | 
| JavaScript | [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-neptunedata/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-neptunedata/) | 
| Kotlin | [https://sdk.amazonaws.com/kotlin/api/latest/neptunedata/index.html](https://sdk.amazonaws.com/kotlin/api/latest/neptunedata/index.html) | 
| .NET | [https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/Neptunedata/NNeptunedata.html](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/Neptunedata/NNeptunedata.html) | 
| PHP | [https://docs.aws.amazon.com/aws-sdk-php/v3/api/namespace-Aws.Neptunedata.html](https://docs.aws.amazon.com/aws-sdk-php/v3/api/namespace-Aws.Neptunedata.html) | 
| Python | [https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/neptunedata.html](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/neptunedata.html) | 
| Ruby | [https://docs.aws.amazon.com/sdk-for-ruby/v3/api/Aws/Neptunedata.html](https://docs.aws.amazon.com/sdk-for-ruby/v3/api/Aws/Neptunedata.html) | 
| Rust | [https://crates.io/crates/aws-sdk-neptunedata](https://crates.io/crates/aws-sdk-neptunedata) | 
| CLI | [https://docs.aws.amazon.com/cli/latest/reference/neptunedata/](https://docs.aws.amazon.com/cli/latest/reference/neptunedata/) | 

## Gremlin AWS SDK 範例
<a name="access-graph-gremlin-sdk-examples"></a>

下列範例示範如何設定`neptunedata`用戶端、執行 Gremlin 查詢，以及列印結果。將 {{YOUR\_NEPTUNE\_HOST}} 和 {{YOUR\_NEPTUNE\_PORT}} 取代為 Neptune 資料庫叢集的端點和連接埠。

**用戶端逾時和重試組態**  
SDK 用戶端逾時可控制*用戶端*等待回應的時間長度。它無法控制查詢在伺服器上執行的時間長度。如果用戶端在伺服器完成之前逾時，當用戶端無法擷取結果時，查詢可能會繼續在 Neptune 上執行。  
我們建議將用戶端讀取逾時設定為 `0`（無逾時），或設定為比 Neptune 資料庫叢集上的伺服器端 [neptune\_query\_timeout](parameters.md#parameters-db-cluster-parameters-neptune_query_timeout) 設定至少長幾秒的值。這可讓 Neptune 控制查詢逾時的時間。  
我們也建議將重試嘗試次數上限設定為 `1`（不重試）。如果 SDK 重試仍在伺服器上執行的查詢，可能會導致重複的操作。這對變動查詢尤其重要，其中重試可能會導致意外的重複寫入。

------
#### [ Python ]

1. 遵循[安裝說明](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html)來安裝 Boto3。

1. 建立名為 的檔案`gremlinExample.py`並貼上下列程式碼：

   ```
   import boto3
   import json
   from botocore.config import Config
   
   # Disable the client-side read timeout and retries so that
   # Neptune's server-side neptune_query_timeout controls query duration.
   client = boto3.client(
       'neptunedata',
       endpoint_url=f'https://{{YOUR_NEPTUNE_HOST}}:{{YOUR_NEPTUNE_PORT}}',
       config=Config(read_timeout=None, retries={'total_max_attempts': 1})
   )
   
   # Use the untyped GraphSON v3 serializer for a cleaner JSON response.
   response = client.execute_gremlin_query(
       gremlinQuery='g.V().limit(1)',
       serializer='application/vnd.gremlin-v3.0+json;types=false'
   )
   
   print(json.dumps(response['result'], indent=2))
   ```

1. 執行範例： `python gremlinExample.py`

------
#### [ Java ]

1. 依照[安裝指示](https://docs.aws.amazon.com//sdk-for-java/latest/developer-guide/setup.html)來設定適用於 Java 的 AWS SDK。

1. 使用下列程式碼來設定 `NeptunedataClient`、執行 Gremlin 查詢，並列印結果：

   ```
   import java.net.URI;
   import java.time.Duration;
   import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
   import software.amazon.awssdk.core.retry.RetryPolicy;
   import software.amazon.awssdk.services.neptunedata.NeptunedataClient;
   import software.amazon.awssdk.services.neptunedata.model.ExecuteGremlinQueryRequest;
   import software.amazon.awssdk.services.neptunedata.model.ExecuteGremlinQueryResponse;
   
   // Disable the client-side timeout and retries so that
   // Neptune's server-side neptune_query_timeout controls query duration.
   NeptunedataClient client = NeptunedataClient.builder()
       .endpointOverride(URI.create("https://{{YOUR_NEPTUNE_HOST}}:{{YOUR_NEPTUNE_PORT}}"))
       .overrideConfiguration(ClientOverrideConfiguration.builder()
           .apiCallTimeout(Duration.ZERO)
           .retryPolicy(RetryPolicy.none())
           .build())
       .build();
   
   // Use the untyped GraphSON v3 serializer for a cleaner JSON response.
   ExecuteGremlinQueryRequest request = ExecuteGremlinQueryRequest.builder()
       .gremlinQuery("g.V().limit(1)")
       .serializer("application/vnd.gremlin-v3.0+json;types=false")
       .build();
   
   ExecuteGremlinQueryResponse response = client.executeGremlinQuery(request);
   
   System.out.println(response.result().toString());
   ```

------
#### [ JavaScript ]

1. 依照[安裝指示](https://docs.aws.amazon.com//sdk-for-javascript/v3/developer-guide/getting-started-nodejs.html)來設定適用於 JavaScript 的 AWS SDK。安裝 neptunedata 用戶端套件：`npm install @aws-sdk/client-neptunedata`。

1. 建立名為 的檔案`gremlinExample.js`並貼上下列程式碼：

   ```
   import { NeptunedataClient, ExecuteGremlinQueryCommand } from "@aws-sdk/client-neptunedata";
   import { NodeHttpHandler } from "@smithy/node-http-handler";
   
   const config = {
       endpoint: "https://{{YOUR_NEPTUNE_HOST}}:{{YOUR_NEPTUNE_PORT}}",
       // Disable the client-side request timeout so that
       // Neptune's server-side neptune_query_timeout controls query duration.
       requestHandler: new NodeHttpHandler({
           requestTimeout: 0
       }),
       maxAttempts: 1
   };
   
   const client = new NeptunedataClient(config);
   
   // Use the untyped GraphSON v3 serializer for a cleaner JSON response.
   const input = {
       gremlinQuery: "g.V().limit(1)",
       serializer: "application/vnd.gremlin-v3.0+json;types=false"
   };
   
   const command = new ExecuteGremlinQueryCommand(input);
   const response = await client.send(command);
   
   console.log(JSON.stringify(response, null, 2));
   ```

1. 執行範例： `node gremlinExample.js`

------