

# Connecting to a graph


 In Neptune Analytics, you can provision your graph to be accessed publicly over the internet or have a private endpoint to access the graph within a VPC. If your graph is not configured for public connectivity, then you must create a private endpoint for your Neptune Analytics graph that allows access to the graph only from within the same Amazon Virtual Private Cloud (VPC) and availability zones associated with the subnet associated with the graph’s private endpoint (You must ensure the subnets belong to all the availability zones in the VPC). This means that applications using Neptune Analytics must be deployed in the same VPC; or For applications which are deployed in different VPC but uses techniques like VPC peering, AWS Site-to-Site VPN connections, or AWS Direct Connect connections might face issues with DNS resolution to connect to private graph endpoint. 

 If your graph is configured for public connectivity, you can connect to your graph from multiple VPCs and from the internet. This allows you to access a Neptune Analytics graph without also setting up additional supporting AWS services. The simplicity of setting up public connectivity-enabled graphs makes it useful for initial exploration of the service. 

 Graphs are created with public connectivity disabled by default. However, this can be configured by enabling public connectivity at [graph creation](https://docs.aws.amazon.com//neptune-analytics/latest/apiref/API_CreateGraph.html) or by [updating the graph configuration](https://docs.aws.amazon.com//neptune-analytics/latest/apiref/API_UpdateGraph.html) post-creation. 

**Note**  
 All Neptune Analytics graphs are configured to use AWS Identity and Access Management ([IAM](https://aws.amazon.com/iam/)) for authentication and authorization. This means that all requests to the graph should be signed using AWS Signature Version 4 [(SIGV4)](https://docs.aws.amazon.com//AmazonS3/latest/API/sig-v4-authenticating-requests.html). If you are using the AWS CLI or SDK to connect, then the signing of the requests is handled by the client library. The library requires the user to provide the credentials to sign using one of the known methods. You can also make HTTP requests to the APIs by using [AWSCurl](https://github.com/okigan/awscurl), which provides a curl like interface to make HTTP requests and supports SIGV4. For Neptune Analytics specific IAM documentation please refer to the Neptune Analytics user guide [Security IAM](https://docs.aws.amazon.com//neptune-analytics/latest/userguide/security-iam.html#security_iam_authentication) section. 

**Topics**
+ [

# AWS PrivateLink for Neptune Analytics
](gettingStarted-connecting-private-link.md)
+ [

# Connecting to a private endpoint from within the same VPC
](gettingStarted-connecting-within-VPC.md)
+ [

# Connecting to a private endpoint from a different VPC (including cross-account)
](gettingStarted-connecting-different-VPC.md)
+ [

# Accessing the graph
](gettingStarted-accessing.md)
+ [

# Best practices
](gettingStarted-connecting-best-practices.md)

# AWS PrivateLink for Neptune Analytics
AWS PrivateLink

 With AWS PrivateLink for Neptune Analytics, you can provision interface Amazon VPC endpoints (interface endpoints) in your virtual private cloud (Amazon VPC). These endpoints are directly accessible from applications that are on premises over VPN and AWS Direct Connect, or in a different AWS region over [Amazon VPC peering](https://docs.aws.amazon.com//vpc/latest/peering/what-is-vpc-peering.html). Using AWS PrivateLink and interface endpoints, you can simplify private network connectivity from your applications to Neptune Analytics. 

 Applications in your VPC do not need public IP addresses to communicate with Neptune Analytics interface VPC endpoints for Neptune Analytics operations. Interface endpoints are represented by one or more elastic network interfaces (ENIs) that are assigned private IP addresses from subnets in your Amazon VPC. Requests to Neptune Analytics over interface endpoints stay on the Amazon network. You can also access interface endpoints in your Amazon VPC from on-premises applications through AWS Direct Connect or AWS Virtual Private Network (Site-to-Site VPN). For more information about how to connect your Amazon VPC with your on-premises network, see the [AWS Direct Connect user guide](https://docs.aws.amazon.com//directconnect/latest/UserGuide/Welcome.html) and the [AWS Site-to-Site VPN user guide](https://docs.aws.amazon.com//vpn/latest/s2svpn/VPC_VPN.html). 

 For general information about interface endpoints, see [ Interface Amazon VPC endpoints (AWS PrivateLink)](https://docs.aws.amazon.com//vpc/latest/privatelink/vpce-interface.html) in the AWS PrivateLink guide. 

## Creating an Amazon VPC endpoint


 To create an Amazon VPC interface endpoint, see [ Create an Amazon VPC endpoint](https://docs.aws.amazon.com//vpc/latest/privatelink/create-interface-endpoint.html#create-interface-endpoint-aws) in the AWS PrivateLink Guide. 

**Topics**
+ [

## Creating an Amazon VPC endpoint
](#gettingStarted-connecting-private-link-create)
+ [

# Types of interface endpoint services for Neptune Analytics
](gettingStarted-connecting-private-link-types.md)
+ [

# Considerations when using AWS PrivateLink for Neptune Analytics
](gettingStarted-connecting-private-link-considerations.md)
+ [

# Accessing Neptune Analytics interface endpoints
](gettingStarted-connecting-private-link-access.md)
+ [

# Accessing Neptune Analytics graph from Neptune Analytics interface endpoints
](gettingStarted-connecting-private-link-access-interface.md)
+ [

# Creating an Amazon VPC endpoint policy for Neptune Analytics data plane
](gettingStarted-connecting-private-link-create-policy.md)

# Types of interface endpoint services for Neptune Analytics


 Neptune Analytics supports two services via interface VPC endpoints on AWS PrivateLink: `neptune-graph` for accessing Neptune Analytics control plane API operations like `CreateGraph`, `DeleteGraph` etc. and `neptune-graph-data` for accessing Neptune Analytics data plane API operations like `GetQuery`, `ListQueries`, `ExecuteQuery` etc. For more information about Neptune Analytics API operations see [Neptune Analytics APIs](https://docs.aws.amazon.com//neptune-analytics/latest/apiref/Welcome.html). 

# Considerations when using AWS PrivateLink for Neptune Analytics


 Amazon VPC considerations apply to AWS PrivateLink for Neptune Analytics. For more information, see [ Interface endpoint considerations](https://docs.aws.amazon.com//vpc/latest/privatelink/vpce-interface.html#vpce-interface-limitations) and [AWS PrivateLink quotas](https://docs.aws.amazon.com//vpc/latest/privatelink/vpc-limits-endpoints.html) in the AWS PrivateLink guide. Additionally, the following restrictions apply: 

1.  The AWS PrivateLink for Neptune Analytics control plane i.e. `neptune-graph` service does not support [ VPC endpoint policies](https://docs.aws.amazon.com//vpc/latest/privatelink/vpc-endpoints-access.html). However, AWS PrivateLink for Neptune Analytics data plane i.e. `neptune-graph-data` service supports VPC endpoint policies. 

1.  The AWS PrivateLink for Neptune Analytics supports [Federal Information Processing Standard (FIPS)](https://aws.amazon.com/compliance/fips/) endpoints in US East (N. Virginia), US East (Ohio), and US West (Oregon) for control plane API operations under the service name `neptune-graph-fips`. FIPS endpoints are not supported in any AWS region for AWS PrivateLink for data plane API operations. 

1.  Transport Layer Security (TLS) 1.1 is **not** supported. 

1.  Private and Hybrid Domain Name System (DNS) services are **not** supported. 

# Accessing Neptune Analytics interface endpoints


 When you create an interface endpoint for Neptune Analytics, AWS PrivateLink generates two types of endpoint-specific, Neptune Analytics DNS names: Regional and zonal. 
+  A Regional DNS name includes a unique Amazon VPC endpoint ID, a service identifier, the AWS Region, and `vpce.amazonaws.com` in its name. For example, for Amazon VPC endpoint ID `vpce-1a2b3c4d`, the DNS name generated might be similar to `vpce-1a2b3c4d-5e6f.neptune-graph.us-east-1.vpce.amazonaws.com`. 
+  A Zonal DNS name includes the Availability Zone - for example, `vpce-1a2b3c4d-5e6f-us-east-1a.neptune-graph.us-east-1.vpce.amazonaws.com`. You might use this option if your architecture isolates availability zones. For example, you could use it for fault containment or to reduce regional data transfer costs. 

# Accessing Neptune Analytics graph from Neptune Analytics interface endpoints


 You can use the AWS CLI or AWS SDKs to access Neptune Analytics graph API operations through Neptune Analytics interface endpoints. 

## AWS CLI examples


 To access Neptune Analytics API operations through Neptune Analytics interface endpoints in AWS CLI commands, use the `--region` parameter. 

 **Example: Create a VPC endpoint** 

```
aws ec2 create-vpc-endpoint \
--region us-east-1 \
--service-name neptune-graph-service-name (for control APIs)/ neptune-graph-data-service-name (for data APIs) \
--vpc-id client-vpc-id \
--subnet-ids client-subnet-id \
--vpc-endpoint-type Interface \
--security-group-ids client-sg-id
```

 **Example: Modify a VPC endpoint** 

 Neptune Analytics VPC endpoint service uses private hosted zone to route requests to your Neptune Analytics graph. Ensure that you have enabled private dns on your VPC interface endpoint. 

```
aws ec2 modify-vpc-endpoint \
--region us-east-1 \
--vpc-endpoint-id client-vpc-endpoint-id \
--private-dns-enabled
```

**Note**  
 Ensure that the private dns is always enabled on your VPC interface endpoint otherwise you might see errors in routing requests to your Neptune Analytics graph. 

 **Example: List graphs using the region parameter** 

```
aws neptune-graph list-graphs --region us-east-1
```

 **Example: Execute a query using the region parameter** 

```
aws neptune-graph execute-query \
--graph-identifier g-0123456789 \
--region us-east-1 \
--query-string "MATCH (n) RETURN n LIMIT 1" \
--language open_cypher \
out.txt
```

## AWS SDK examples


 To access Neptune Analytics API operations through Neptune Analytics interface endpoints when using the AWS SDKs, update your SDKs to the latest version. Then, configure your clients to use the AWS region for accessing a Neptune Analytics API operation through Neptune Analytics interface endpoints. 

 **SDK for Python (Boto3)** 

 In this example, you will use an endpoint URL to access a Neptune Analytics graph. 

```
neptune_graph_client = session.client(
service_name='neptune-graph',
region_name='us-east-1'
)
```

 **SDK for Java 2.x** 

 In this example, you will use an endpoint URL to access a Neptune Analytics graph. 

```
//client build with endpoint config
final NeptuneGraphClient NeptuneGraphClient.builder()
        .region(software.amazon.awssdk.regions.Region.US_EAST_1)
        .credentialsProvider(credentialsProvider)
        .build();
```

# Creating an Amazon VPC endpoint policy for Neptune Analytics data plane


**Note**  
 AWS PrivateLink for Neptune Analytics does not support VPC endpoint policies for the control plane service `neptune-graph`. VPC endpoint policies are only supported for the Neptune Analytics data plane service `neptune-graph-data`. 

 You can attach an endpoint policy to your Amazon VPC endpoint that controls access to a Neptune Analytics graph. The policy specifies the following information: 
+  The AWS Identity and Access Management (IAM) principal that can perform actions. 
+  The actions that can be performed. 
+  The resources on which actions can be performed. 

 **Restricting access to a specific Neptune Analytics graph from an Amazon VPC endpoint.** 

 You can create an endpoint policy that restricts access to only specific Neptune Analytics graphs. This type of policy is useful if you have other AWS services in your Amazon VPC that use graphs. The following policy only provides access to the `GetGraphSummary` action/API from the VPC endpoint. 

------
#### [ JSON ]

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Id": "Policy1216114807515",
  "Statement": [
    {
      "Sid": "Access-to-specific-graph-only",
      "Principal": "*",
      "Action": [
        "neptune-graph:GetGraphSummary"
      ],
      "Effect": "Allow",
      "Resource": [
        "arn:aws:neptune-graph:us-east-1:111122223333:graph/resource-id"
      ]
    }
  ]
}
```

------

# Connecting to a private endpoint from within the same VPC
Connecting from the same VPC

 For graphs using private endpoints, you can connect to your graph from any resource that has access to the private VPC, such as AWS Lambda, an Amazon SageMaker AI notebook instance, an Amazon EC2 instance, etc. The instance must be in the same VPC and subnet as the private endpoint for your graph. Ensure that the security group attached to the VPC endpoint of your private graph's endpoint allows ingress on port 443, and optionally port 8182. 

 For details on how to use notebooks and how to create one capable of connecting to the private endpoint of your graph, see the Neptune Analytics user guide section on [notebooks](https://docs.aws.amazon.com//neptune-analytics/latest/userguide/notebooks.html), making sure to supply the necessary VPC and subnet identifier when setting up your network options. If the VPC CIDR is 172.17.0.0/16, notebooks will have some difficult connecting the graph endpoints. 

 You can also create an Amazon EC2 instance to connect to the private endpoint of your graph. You will need to select the correct VPC and availability zone to match your graph’s private endpoint. When prompted for a security group to associate with the instance, create or choose one that has inbound TCP rules allowing ingress traffic over ports 22 (for SSH), and egress traffic over port 443 if custom egress rules are needed. For the detailed prerequisites and steps to create and connect to an Amazon EC2 instance, see the [Amazon EC2 user guide](https://docs.aws.amazon.com//AWSEC2/latest/UserGuide/EC2_GetStarted.html). 

**Note**  
 For troubleshooting connectivity issues refer to the [reachability analyzer](https://docs.aws.amazon.com//vpc/latest/reachability/what-is-reachability-analyzer.html) guide. You can get destination VPC endpointId by using the [GetPrivateGraphEndpoint](https://docs.aws.amazon.com//neptune-analytics/latest/apiref/API_GetPrivateGraphEndpoint.html) API. 

# Connecting to a private endpoint from a different VPC (including cross-account)
Connecting from a different VPC

 In some cases, you may be required to connect to your graph from a different VPC without enabling public connectivity. For example, applications that segregate AWS services using different VPCs or different accounts. In this case, connectivity can be achieved through the use of private graph endpoints and Amazon Route 53 private hosted zones. The steps in the following procedure refer to a client in VPC B, wanting to access a Neptune Analytics graph in VPC A. 

1. 

**Establish network connectivity between VPC A and VPC B**

    You can use any method that allows traffic to move between VPCs. For example, [VPC peering](https://docs.aws.amazon.com//vpc/latest/peering/what-is-vpc-peering.html) or [AWS Transit Gateway](https://docs.aws.amazon.com//vpc/latest/tgw/tgw-getting-started.html). In addition to establishing the network connection, make sure your security groups and network ACLs allow traffic between the two VPCs. You can verify network connectivity with the [reachability analyzer](https://docs.aws.amazon.com//vpc/latest/reachability/what-is-reachability-analyzer.html). 

1. 

**Create a private graph endpoint in VPC A**

    If you haven’t already, create a private graph endpoint in VPC A. This can be done through the console or the [ CreatePrivateGraphEndpoint ](https://docs.aws.amazon.com//neptune-analytics/latest/apiref/API_CreatePrivateGraphEndpoint.html) API. Once created, collect the DNS name for the VPC endpoint that was deployed. 

   1.  Find the VPC endpoint ID from the value of **vpcEndpointId** when calling the [ ListPrivateGraphEndpoints ](https://docs.aws.amazon.com//neptune-analytics/latest/apiref/API_ListPrivateGraphEndpoints.html) API. 

   1.  From the console or using the [DescribeVpcEndpoints](https://docs.aws.amazon.com//AWSEC2/latest/APIReference/API_DescribeVpcEndpoints.html) API, collect the DNS name of the VPC endpoint. This should have the format of `vpce-<alphanumeric>.vpce-svc-<alphanumeric>.<region>.vpce.amazonaws.com`. 

1.  Use Amazon Route 53 to create a [private hosted zone](https://docs.aws.amazon.com//Route53/latest/DeveloperGuide/hosted-zone-private-creating.html) for VPC B. 

   1.  From the Route 53 console, choose **Create hosted zone**. 

   1.  Set the **domain name** of the private hosted zone to the graph endpoint of the Neptune Analytics graph. The graph endpoint should have the format of `g-<alphanumeric>.<region>.neptune-graph.amazonaws.com`. 

   1.  Set the **Type** to **Private hosted zone**. 

   1.  Associate VPC B with the hosted zone. 

   1.  Choose **Create hosted zone**. 

    Add a record to route traffic destined for the graph endpoint to the VPC endpoint directly. 

   1.  When the hosted zone is created, choose **Create record**. 

   1.  From the creation wizard, choose **Simple routing** for the routing policy. 

   1.  Choose **Define simple record**. Set the **Record type** to **A**, which routes traffic to an IPv4 address and some AWS resources. Set **Value/Route** traffic to to the DNS hostname of the VPC endpoint from Step 2. This should have the format of `vpce-<alphanumeric>.vpce-svc-<alphanumeric>.<region>.vpce.amazonaws.com`. 

    To use private hosted zones, `enableDnsHostnames` and `enableDnsSupport` should be set to `true` for both VPCs. Depending on your networking configuration, other considerations may apply when using private hosted zones. See [Route 53 private hosted zone considerations](https://docs.aws.amazon.com//Route53/latest/DeveloperGuide/hosted-zone-private-considerations.html) documentation to validate your setup. 

1. 

**Establish cross-account IAM permissions (only required for cross-account access)**

    In addition to the network connectivity established in prior steps, if the client in VPC B is in a different account (Account B), they will also need appropriate credentials to access the Neptune Analytics graph in VPC A (in Account A). You can use [ cross-account IAM roles ](https://docs.aws.amazon.com//IAM/latest/UserGuide/access_policies-cross-account-resource-access.html#access_policies-cross-account-using-roles) to give permissions to the client. 

   1.  Create the IAM role and policy that the client in Account B will be using (IAM role B). 

   1.  Create an IAM role and policy in Account A that grants the desired permissions to the Neptune Analytics graph (IAM role A). Make sure that there are also permissions for IAM role B to assume this role. 

   1.  Add permissions to IAM role B to assume the IAM role A. 

   1.  When making a cross-account call to the Neptune Analytics graph, use the AWS Security Token Service AssumeRole API to have IAM role B assume IAM role A. Use the returned credentials when making requests to the Neptune Analytics graph, e.g. via AWS SDK, awscurl, etc. 

# Accessing the graph
Accessing the graph

 Once you’ve created a graph and set up the prerequisites for connecting to that graph, you can proceed with accessing your graph to load and query data. This section contains an explanation of ways you can communicate with your graph along with some example queries. For details on how to load data, see the [loading data](https://docs.aws.amazon.com/neptune-analytics/latest/userguide/loading-data.html) section in the Neptune Analytics user guide. 

## Using a notebook


 You can access to your Neptune Analytics graph through a Neptune workbench, which provides visualization tools on top of Neptune Analytics which can help with interpreting query results. For more information on how to set up and use a graph notebook, see the [notebooks](https://docs.aws.amazon.com//neptune-analytics/latest/userguide/notebooks.html) section in the Neptune Analytics user guide. 

 **Example** 

 The cell magic below submits an openCypher query that returns a single node. 

```
%%oc
MATCH (n) RETURN n LIMIT 1
```

## Using the AWS SDK


 With the AWS SDK, you can access your graph using a programming language of your choice, which provides clean integration between Neptune Analytics and your applications. With the Neptune Analytics SDK (service name Neptune graph), you can perform data operations like querying and summarization in addition to control plane operations such as graph creation, deletion, and modification. For a list of the supported programming languages and directions for setting up the SDK in each language, see the [AWS developer tools](https://aws.amazon.com/developer/tools/) documentation. 

 Direct links to the API reference documentation for the Neptune Analytics service in each SDK language can be found below: 


| Programming language | Neptune graph API reference | 
| --- | --- | 
|  C\$1\$1  |   [https://sdk.amazonaws.com/cpp/api/LATEST/aws-cpp-sdk-neptune-graph/html/annotated.html](https://sdk.amazonaws.com/cpp/api/LATEST/aws-cpp-sdk-neptune-graph/html/annotated.html)   | 
|  Go  |   [https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/neptunegraph](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/neptunegraph)   | 
|  Java  |   [https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/neptunegraph/package-summary.html](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/neptunegraph/package-summary.html)   | 
|  JavaScript  |   [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-neptune-graph/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-neptune-graph/)   | 
|  Kotlin  |   [https://sdk.amazonaws.com/kotlin/api/latest/neptunegraph/index.html](https://sdk.amazonaws.com/kotlin/api/latest/neptunegraph/index.html)   | 
|  .NET  |   [https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/NeptuneGraph/NNeptuneGraph.html](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/NeptuneGraph/NNeptuneGraph.html)   | 
|  PHP  |   [https://docs.aws.amazon.com/aws-sdk-php/v3/api/namespace-Aws.NeptuneGraph.html](https://docs.aws.amazon.com/aws-sdk-php/v3/api/namespace-Aws.NeptuneGraph.html)   | 
|  Python  |   [https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/neptune-graph.html](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/neptune-graph.html)   | 
|  CLI  |   [https://docs.aws.amazon.com/cli/latest/reference/neptune-graph/](https://docs.aws.amazon.com/cli/latest/reference/neptune-graph/)   | 
|  Ruby  |   [https://docs.aws.amazon.com/sdk-for-ruby/v3/api/Aws/NeptuneGraph.html](https://docs.aws.amazon.com/sdk-for-ruby/v3/api/Aws/NeptuneGraph.html)   | 
|  Rust  |   [https://crates.io/crates/aws-sdk-neptunegraph](https://crates.io/crates/aws-sdk-neptunegraph)   | 
|  Swift  |   [https://sdk.amazonaws.com/swift/api/awsneptunegraph/0.37.0/documentation/awsneptunegraph](https://sdk.amazonaws.com/swift/api/awsneptunegraph/0.37.0/documentation/awsneptunegraph)   | 

## Examples


 The following examples outline how to interact with an Amazon Neptune graph database using different programming languages and tools. It covers the steps to set up an SDK client, execute an OpenCypher query, and print the results, for Python as well as other languages. Additionally, it demonstrates how to use the AWS Command Line Interface (CLI) and the AWSCURL tool to submit queries directly to the Neptune graph endpoint. 

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

 The code sample below uses the Python SDK to submit a query that returns a single node and prints the result. 

1.  Follow the [ installation instructions](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html) to install Boto3. If you are using a SageMaker AI hosted Jupyter notebook, Boto3 will be pre-installed, but you may need to update it. 

1.  Configure your Boto3 credentials by following the [ configuring credentials](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html#configuring-credentials) guide. 

1.  Create a file named `queryExample.py`. 

1.  In that file, paste the following code. It will set up a Neptune graph client, execute an openCypher query request, and print the result. Replace the graph identifier and query string as needed. 

   ```
   import boto3
   
   // Set up the Neptune Graph client.
   client = boto3.client('neptune-graph')
   
   // Execute a query.
   response = client.execute_query(
       graphIdentifier='g-0123456789',
       queryString='MATCH (n) RETURN n LIMIT 1',
       language='OPEN_CYPHER'
   )
   
   // Print the response.
   print(response['payload'].read().decode('utf-8'))
   ```

1.  Run the sample code by entering `python queryExample.py`. 

------
#### [ Go ]

 The code sample below uses the Go SDK to submit a query that returns a single node and prints the result. 

1.  Follow the [ installation instructions ](https://aws.github.io/aws-sdk-go-v2/docs/getting-started/) to install Go and the AWS SDK for Go. 

1.  Create a file named `queryExample.go`. 

1.  In that file, paste the following code. It will set up a Neptune graph client, execute an openCypher query request, and print the result. Replace the graph identifier and query string as needed. 

   ```
   package main
   
   import (
           "context"
           "log"
           "github.com/aws/aws-sdk-go-v2/aws"
           "github.com/aws/aws-sdk-go-v2/config"
           "github.com/aws/aws-sdk-go-v2/service/neptunegraph"
           "io"
   )
   
   func main() {
           // Load the Shared AWS Configuration (~/.aws/config)
           cfg, err := config.LoadDefaultConfig(context.TODO())
           if err != nil {
                   log.Fatal(err)
           }
   
           // Create an Amazon Neptune Analytics service client
           client := neptunegraph.NewFromConfig(cfg)
   
           // Execute a query
           output, err := client.ExecuteQuery(context.TODO(), &neptunegraph.ExecuteQueryInput{
                   GraphIdentifier: aws.String("g-0123456789"),
                   Language: "OPEN_CYPHER",
                   QueryString: aws.String("MATCH (n) RETURN n LIMIT 1"),
           })
           if err != nil {
                   log.Fatal(err)
           }
   
           // Print the results
           bytes, err := io.ReadAll(output.Payload)
           log.Println(string(bytes))
   }
   ```

1.  Run the sample code by entering `go run queryExample.go`. 

------
#### [ Node.js ]

 The Node.js code sample below uses the JavaScript SDK to submit a query that returns a single node and prints the result. 

1.  Follow the [ installation instructions ](https://docs.aws.amazon.com//sdk-for-javascript/v3/developer-guide/getting-started-nodejs.html) to install Node.js and set up your package structure. For this example, install the Neptune graph client package instead of the Amazon S3 client package: `npm install @aws-sdk/client-neptune-graph`. 

1.  Create a file in that directory structure named `queryExample.js`. 

1.  In that file, paste the following code. It will set up a Neptune graph client, execute an openCypher query request, and print the result. Replace the graph identifier and query string as needed. 

   ```
   import { NeptuneGraphClient, ExecuteQueryCommand } from "@aws-sdk/client-neptune-graph";
   
   // Set up the client.
   const neptuneGraphClient = new NeptuneGraphClient({});
     
   // Send the query request.
   const output = await neptuneGraphClient.send(
       new ExecuteQueryCommand({
           graphIdentifier: "g-0123456789",
           language: "OPEN_CYPHER",
           queryString: "MATCH (n) RETURN n LIMIT 1"
       })
   );
   
   // Print the result.
   console.log(await output.payload.transformToString('utf-8'));
   ```

1.  Run the sample code by entering `node queryExample.js`. 

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

 The tutorial below sets up a project that uses the Java SDK to submit a query that returns a single node and prints the result. 

1.  To get started with the Java SDK, follow the [ installation instructions ](https://docs.aws.amazon.com//sdk-for-java/latest/developer-guide/setup.html#setup-envtools) to install Java and set up a build tool that supports Maven central. This example will use [Apache Maven](https://maven.apache.org/). 

1.  Follow the [steps](https://docs.aws.amazon.com//sdk-for-java/latest/developer-guide/get-started.html#get-started-projectsetup) to create a project using Maven based on the quickstart template. When executing these steps, please make the following modifications: 
**Note**  
 When generating the project from the template, specify a version of the Java SDK that includes the Neptune graph service APIs. For this example, use 2.25.7 as your archetype version. 

   ```
   mvn archetype:generate \
     -DarchetypeGroupId=software.amazon.awssdk \
     -DarchetypeArtifactId=archetype-app-quickstart \
     -DarchetypeVersion=2.25.7
   ```

    Running the command above will present you with several prompts. When asked to provide a 'service' (i.e., the service whose client and APIs you plan to use for this tutorial), please enter `neptunegraph` as the service name. An updated table of prompts and values can be found below:     
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/neptune-analytics/latest/userguide/gettingStarted-accessing.html)

1.  After generating the project structure, you should see three Maven-generated classes defined in the `getstarted/src/main/java/org/example/` directory: `App.java`, `DependencyFactory.java`, and `Handler.java`. For details on each of these classes, see step 3 in the [ SDK for Java ](https://docs.aws.amazon.com//sdk-for-java/latest/developer-guide/get-started.html#get-started-code) guide. Since this example uses the `neptunegraph` service, the Maven-generated code in the DependencyFactor and Handler classes will be using a different client than the code samples provided there. Refer to the Neptune graph-specific equivalents of the auto-generated classes below: 

   1.  Maven-generated `App.java` - this file is the same regardless of the service used. 

      ```
      package org.example;
      import org.slf4j.Logger;
      import org.slf4j.LoggerFactory;
      
      public class App {
          private static final Logger logger = LoggerFactory.getLogger(App.class);
      
          public static void main(String... args) {
              logger.info("Application starts");
      
              Handler handler = new Handler();
              handler.sendRequest();
      
              logger.info("Application ends");
          }
      }
      ```

   1.  Maven-generated `DependencyFactory.java` - This file uses the client class `NeptuneGraphClient` because `neptunegraph` was chosen as the service during the project setup. 

      ```
      package org.example;
      
      import software.amazon.awssdk.http.apache.ApacheHttpClient;
      import software.amazon.awssdk.services.neptunegraph.NeptuneGraphClient;
      
      /**
       * The module containing all dependencies required by the {@link Handler}.
       */
      public class DependencyFactory {
      
          private DependencyFactory() {}
      
          /**
           * @return an instance of NeptuneGraphClient
           */
          public static NeptuneGraphClient neptuneGraphClient() {
              return NeptuneGraphClient.builder()
                             .httpClientBuilder(ApacheHttpClient.builder())
                             .build();
          }
      }
      ```

   1.  Maven-generated `Handler.java` - This file uses the client class `NeptuneGraphClient` because `neptunegraph` was chosen as the service during the project setup. 

      ```
      package org.example;
      
      import software.amazon.awssdk.services.neptunegraph.NeptuneGraphClient;
      
      
      public class Handler {
          private final NeptuneGraphClient neptuneGraphClient;
      
          public Handler() {
              neptuneGraphClient = DependencyFactory.neptuneGraphClient();
          }
      
          public void sendRequest() {
              // TODO: invoking the api calls using neptuneGraphClient.
          }
      }
      ```

1.  Make changes to the Maven-generated handler class to fill in the missing logic in `sendRequest` to use the `NeptuneGraphClient` to execute a query, then print the result. Copy the completed code below, which replaces the TODO with code and adds the necessary imports. Replace the graph identifier and query string as needed. 

   ```
   package org.example;
   
   import software.amazon.awssdk.core.ResponseInputStream;
   import software.amazon.awssdk.services.neptunegraph.NeptuneGraphClient;
   import software.amazon.awssdk.services.neptunegraph.model.ExecuteQueryRequest;
   import software.amazon.awssdk.services.neptunegraph.model.ExecuteQueryResponse;
   
   import java.io.BufferedReader;
   import java.io.InputStreamReader;
   import java.io.IOException;
   
   
   public class Handler {
       private final NeptuneGraphClient neptuneGraphClient;
   
       public Handler() {
           neptuneGraphClient = DependencyFactory.neptuneGraphClient();
       }
   
       public void sendRequest() {
           String graphIdentifier = "g-0123456789";
           String queryString = "MATCH (n) RETURN n LIMIT 1";
   
           ExecuteQueryRequest request = ExecuteQueryRequest.builder()
                   .graphIdentifier(graphIdentifier)
                   .queryString(queryString)
                   .build();
   
           System.out.println("Executing query: " + queryString);
   
           ResponseInputStream<ExecuteQueryResponse> response = neptuneGraphClient.executeQuery(request);
           BufferedReader reader = new BufferedReader(new InputStreamReader(response));
   
           try {
                   System.out.println("Printing query result:");
                   String line;
                   while ((line = reader.readLine()) != null) {
                           System.out.println(line);
                   }
           } catch (IOException e) {
                   System.out.println("Error occurred while printing result.");
           }
       }
   }
   ```

1.  Navigate to your project directory `getStarted`. 

1.  Build your project: `mvn clean package` 

1.  Run the application: `mvn exec:java -Dexec.mainClass="org.example.App"`. 

------

## Using the AWS CLI


 You can connect to your graph using the AWS command-line interface. Specify the neptune-graph service name to use Neptune Analytics APIs. For information on AWS CLI installation and usage, see the [AWS CLI documentation](https://aws.amazon.com/cli/). To set up credentials, refer to the [AWS CLI user guide](/cli/latest/userguide/cli-chap-configure.html). 

 The example command below uses the AWS CLI to submit a query that returns a single node. 

```
aws neptune-graph execute-query \
--graph-identifier g-0123456789 \
--region us-east-2 \
--query-string "MATCH (n) RETURN n LIMIT 1" \
--language open_cypher \
out.txt
```

## Using AWSCURL


 You can connect to your graph using the `awscurl` command-line tool. This allows you to directly make requests using HTTPS against a graph endpoint. You can find the correct endpoint to use in the AWS console (under the “Connectivity & Security” section of a Neptune Analytics graph page) and in the response of any `GetGraph` API request. To set up credentials, refer to the [AWS CLI user guide](/cli/latest/userguide/cli-chap-configure.html). 

 For `awscurl` installation and setup instructions, see [AWSCURL](https://github.com/okigan/awscurl) github repository. 

 The following command uses `awscurl` to submit a query that returns a single node. 

```
awscurl -X POST "https://g-0123456789.us-east-2.neptune-graph.amazonaws.com/queries" \
-H "Content-Type: application/x-www-form-urlencoded" \
--region us-east-2 \
--service neptune-graph \
-d "query=MATCH (n) RETURN n LIMIT 1"
```

# Best practices


 Ensure the streams have been consumed and closed to be able to re-use client connections in the SDK. See the [ SDK for Java developer guide ](https://docs.aws.amazon.com//sdk-for-java/latest/developer-guide/best-practices.html#bestpractice2) for more information. 

 **CLI and SDK** 

 Using the default settings, any CLI or SDK request will timeout in 60 seconds and attempt a retry. For the cases where you are running queries that can take longer than 60 seconds, it is recommended to set the CLI/SDK timeout to 0 (no timeout), or a much larger value to avoid unnecesssary retries. It is also recommended to set `MAX_ATTEMPTS` for CLI/SDK to `1` for `execute_query` to avoid any retries by the CLI/SDK. For the Boto client, set the `read_timeout` to `None`, and the `total_max_attempts` to `1`. 

```
import boto3
from botocore.config import Config
n = boto3.client('neptune-graph', 
                 config=(Config(retries={"total_max_attempts": 1, "mode": "standard"}, read_timeout=None)))
```

 For the CLI, set the `--cli-read-timeout` parameter to `0` for no timeout, and set the environment variable `AWS_MAX_ATTEMPTS` to `1` to prevent retries. 

```
export AWS_MAX_ATTEMPTS=1
aws neptune-graph execute-query \
--graph-identifier <graph-id> \
--region <region> \
--query-string "MATCH (p:Person)-[r:KNOWS]->(p1) RETURN *;" \
--cli-read-timeout 0
--language open_cypher /tmp/out.txt
```