Skip to content

Commit 9d8fbae

Browse files
committed
added data Neptune examples
1 parent 1003c0e commit 9d8fbae

9 files changed

+262
-30
lines changed

python/example_code/neptune/NeptuneScenario.py

Lines changed: 42 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -11,18 +11,7 @@
1111
POLL_INTERVAL_SECONDS = 10
1212
TIMEOUT_SECONDS = 1200 # 20 minutes
1313

14-
def delete_db_subnet_group(neptune_client, subnet_group_name: str):
15-
request = {
16-
'DBSubnetGroupName': subnet_group_name
17-
}
18-
19-
try:
20-
neptune_client.delete_db_subnet_group(**request)
21-
print(f" Deleting Subnet Group: {subnet_group_name}")
22-
except (botocore.ClientError, botocore.BotoCoreError) as e:
23-
print(f" Failed to delete subnet group '{subnet_group_name}': {e}")
24-
25-
14+
# snippet-start:[neptune.python.delete.cluster.main]
2615
def delete_db_cluster(neptune_client, cluster_id: str):
2716
request = {
2817
'DBClusterIdentifier': cluster_id,
@@ -34,14 +23,13 @@ def delete_db_cluster(neptune_client, cluster_id: str):
3423
print(f" Deleting DB Cluster: {cluster_id}")
3524
except Exception as e:
3625
print(f" Failed to delete DB Cluster '{cluster_id}': {e}")
37-
26+
# snippet-end:[neptune.python.delete.cluster.main]
3827

3928
def format_elapsed_time(seconds: int) -> str:
4029
mins, secs = divmod(seconds, 60)
4130
hours, mins = divmod(mins, 60)
4231
return f"{hours:02}:{mins:02}:{secs:02}"
4332

44-
4533
def wait_until_instance_deleted(
4634
neptune_client,
4735
instance_id: str,
@@ -86,16 +74,37 @@ def wait_until_instance_deleted(
8674

8775
time.sleep(poll_interval_seconds)
8876

89-
77+
# snippet-start:[neptune.python.delete.instance.main]
9078
def delete_db_instance(neptune_client, instance_id: str):
79+
"""
80+
Deletes a Neptune DB instance.
81+
82+
Args:
83+
neptune_client (boto3.client): The Neptune client object.
84+
instance_id (str): The ID of the Neptune DB instance to be deleted.
85+
"""
9186
delete_db_instance_request = {
9287
'DBInstanceIdentifier': instance_id,
9388
'SkipFinalSnapshot': True
9489
}
9590

9691
neptune_client.delete_db_instance(**delete_db_instance_request)
9792
print(f"Deleting DB Instance: {instance_id}")
93+
# snippet-end:[neptune.python.delete.instance.main]
94+
95+
# snippet-start:[neptune.python.delete.subnet.group.main]
96+
def delete_db_subnet_group(neptune_client, subnet_group_name):
97+
"""
98+
Deletes a Neptune DB subnet group synchronously using Boto3.
9899
100+
:param subnet_group_name: The name of the DB subnet group to delete.
101+
"""
102+
delete_group_request = {
103+
'DBSubnetGroupName': subnet_group_name
104+
}
105+
neptune_client.delete_db_subnet_group(**delete_group_request)
106+
print(f"️ Deleting Subnet Group: {subnet_group_name}")
107+
# snippet-end:[neptune.python.delete.subnet.group.main]
99108

100109
def wait_for_cluster_status(
101110
neptune_client,
@@ -149,7 +158,7 @@ def wait_for_cluster_status(
149158

150159
time.sleep(poll_interval_seconds)
151160

152-
161+
# snippet-start:[neptune.python.start.cluster.main]
153162
def start_db_cluster(neptune_client, cluster_identifier):
154163
"""
155164
Starts an Amazon Neptune DB cluster.
@@ -159,6 +168,8 @@ def start_db_cluster(neptune_client, cluster_identifier):
159168
cluster_identifier (str): The identifier of the DB cluster to start.
160169
"""
161170

171+
time.sleep(30)
172+
162173
# Create the request dictionary
163174
start_db_cluster_request = {
164175
'DBClusterIdentifier': cluster_identifier
@@ -167,8 +178,9 @@ def start_db_cluster(neptune_client, cluster_identifier):
167178
# Call the API to start the DB cluster
168179
neptune_client.start_db_cluster(**start_db_cluster_request)
169180
print(f"DB Cluster started: {cluster_identifier}")
181+
# snippet-end:[neptune.python.start.cluster.main]
170182

171-
183+
# snippet-start:[neptune.python.stop.cluster.main]
172184
def stop_db_cluster(neptune_client, cluster_identifier: str):
173185
"""
174186
Stops an Amazon Neptune DB cluster.
@@ -186,8 +198,9 @@ def stop_db_cluster(neptune_client, cluster_identifier: str):
186198
# Call the API to stop the DB cluster
187199
neptune_client.stop_db_cluster(**stop_db_cluster_request)
188200
print(f"DB Cluster stopped: {cluster_identifier}")
201+
# snippet-end:[neptune.python.stop.cluster.main]
189202

190-
203+
# snippet-start:[neptune.python.describe.cluster.main]
191204
def describe_db_clusters(neptune_client, cluster_id: str):
192205
"""
193206
Describes the details of a specific Neptune DB cluster.
@@ -224,7 +237,7 @@ def describe_db_clusters(neptune_client, cluster_id: str):
224237
print(f"Preferred Backup Window: {cluster.get('PreferredBackupWindow')}")
225238
print(f"Preferred Maintenance Window: {cluster.get('PreferredMaintenanceWindow')}")
226239
print("------")
227-
240+
# snippet-end:[neptune.python.describe.cluster.main]
228241

229242
def check_instance_status(neptune_client, instance_id: str, desired_status: str):
230243
start_time = time.time()
@@ -251,7 +264,7 @@ def check_instance_status(neptune_client, instance_id: str, desired_status: str)
251264

252265
time.sleep(POLL_INTERVAL_SECONDS)
253266

254-
267+
# snippet-start:[neptune.python.create.dbinstance.main]
255268
def create_db_instance(neptune_client, db_instance_id: str, db_cluster_id: str) -> str:
256269
create_db_instance_request = {
257270
'DBInstanceIdentifier': db_instance_id,
@@ -268,8 +281,9 @@ def create_db_instance(neptune_client, db_instance_id: str, db_cluster_id: str)
268281
instance_id = instance['DBInstanceIdentifier']
269282
print(f"Created Neptune DB Instance: {instance_id}")
270283
return instance_id
284+
# snippet-end:[neptune.python.create.dbinstance.main]
271285

272-
286+
# snippet-start:[neptune.python.create.cluster.main]
273287
def create_db_cluster(neptune_client, db_name: str) -> str:
274288
create_db_cluster_request = {
275289
'DBClusterIdentifier': db_name,
@@ -286,7 +300,7 @@ def create_db_cluster(neptune_client, db_name: str) -> str:
286300
cluster_id = cluster['DBClusterIdentifier']
287301
print(f"DB Cluster created: {cluster_id}")
288302
return cluster_id
289-
303+
# snippet-end:[neptune.python.create.cluster.main]
290304

291305
def get_subnet_ids(vpc_id: str) -> list[str]:
292306
ec2_client = boto3.client('ec2')
@@ -316,6 +330,7 @@ def get_default_vpc_id() -> str:
316330
return default_vpc_id
317331

318332

333+
# snippet-start:[neptune.python.create.subnet.main]
319334
def create_subnet_group(neptune_client, group_name: str):
320335
vpc_id = get_default_vpc_id()
321336
subnet_ids = get_subnet_ids(vpc_id)
@@ -334,7 +349,7 @@ def create_subnet_group(neptune_client, group_name: str):
334349

335350
print(f"Subnet group created: {name}")
336351
print(f"ARN: {arn}")
337-
352+
# snippet-end:[neptune.python.create.subnet.main]
338353

339354
def wait_for_input_to_continue():
340355
while True:
@@ -410,6 +425,7 @@ def run_scenario(neptune_client, subnet_group_name: str, db_instance_id: str, cl
410425
delete_db_instance(neptune_client, db_instance_id)
411426
wait_until_instance_deleted(neptune_client, db_instance_id)
412427
delete_db_cluster(neptune_client, db_cluster_id)
428+
delete_db_subnet_group(neptune_client, subnet_group_name)
413429
print("Neptune resources deleted successfully")
414430

415431
print("-" * 88)
@@ -420,9 +436,9 @@ def main():
420436

421437
# Customize the following names to match your Neptune setup
422438
# (You must change these to unique values for your environment)
423-
subnet_group_name = "neptuneSubnetGroup75"
424-
cluster_name = "neptuneCluster75"
425-
db_instance_id = "neptuneDB75"
439+
subnet_group_name = "neptuneSubnetGroup78"
440+
cluster_name = "neptuneCluster78"
441+
db_instance_id = "neptuneDB78"
426442

427443
print("""
428444
Amazon Neptune is a fully managed graph database service by AWS...
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2+
# SPDX-License-Identifier: Apache-2.0
3+
4+
import boto3
5+
from botocore.exceptions import ClientError, BotoCoreError
6+
7+
# snippet-start:[neptune.python.graph.create.main]
8+
"""
9+
Running this example.
10+
11+
----------------------------------------------------------------------------------
12+
VPC Networking Requirement:
13+
----------------------------------------------------------------------------------
14+
Amazon Neptune must be accessed from **within the same VPC** as the Neptune cluster.
15+
It does not expose a public endpoint, so this code must be executed from:
16+
17+
- An **AWS Lambda function** configured to run inside the same VPC
18+
- An **EC2 instance** or **ECS task** running in the same VPC
19+
- A connected environment such as a **VPN**, **AWS Direct Connect**, or a **peered VPC**
20+
21+
"""
22+
23+
GRAPH_NAME = "sample-analytics-graph"
24+
REGION = "us-east-1"
25+
26+
def main():
27+
"""
28+
Main entry point: create NeptuneGraph client and call graph creation.
29+
"""
30+
# Hypothetical client - boto3 currently doesn't have NeptuneGraph client, so replace with actual client if available
31+
neptune_graph_client = boto3.client("neptune", region_name=REGION)
32+
33+
execute_create_graph(neptune_graph_client, GRAPH_NAME)
34+
35+
36+
def execute_create_graph(client, graph_name):
37+
"""
38+
Creates a new Neptune graph.
39+
40+
:param client: Boto3 Neptune graph client (hypothetical)
41+
:param graph_name: Name of the graph to create
42+
"""
43+
try:
44+
print("Creating Neptune graph...")
45+
46+
# Hypothetical method for create_graph, adjust accordingly if you use HTTP API or SDK extensions
47+
response = client.create_graph(
48+
GraphName=graph_name,
49+
ProvisionedMemory=16 # Example parameter, adjust if API differs
50+
)
51+
52+
created_graph_name = response.get("Name")
53+
graph_arn = response.get("Arn")
54+
graph_endpoint = response.get("Endpoint")
55+
56+
print("Graph created successfully!")
57+
print(f"Graph Name: {created_graph_name}")
58+
print(f"Graph ARN: {graph_arn}")
59+
print(f"Graph Endpoint: {graph_endpoint}")
60+
61+
except ClientError as e:
62+
print(f"Failed to create graph: {e.response['Error']['Message']}")
63+
except BotoCoreError as e:
64+
print(f"Failed to create graph: {str(e)}")
65+
except Exception as e:
66+
print(f"Unexpected error: {str(e)}")
67+
68+
69+
if __name__ == "__main__":
70+
main()
71+
# snippet-end:[neptune.python.graph.create.main]
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2+
# SPDX-License-Identifier: Apache-2.0
3+
4+
import boto3
5+
from botocore.exceptions import ClientError
6+
7+
"""
8+
Running this example.
9+
10+
----------------------------------------------------------------------------------
11+
VPC Networking Requirement:
12+
----------------------------------------------------------------------------------
13+
Amazon Neptune must be accessed from **within the same VPC** as the Neptune cluster.
14+
It does not expose a public endpoint, so this code must be executed from:
15+
16+
- An **AWS Lambda function** configured to run inside the same VPC
17+
- An **EC2 instance** or **ECS task** running in the same VPC
18+
- A connected environment such as a **VPN**, **AWS Direct Connect**, or a **peered VPC**
19+
20+
"""
21+
22+
NEPTUNE_ANALYTICS_ENDPOINT = "https://<your-neptune-analytics-endpoint>:8182"
23+
GRAPH_ID = "<your-graph-id>"
24+
REGION = "us-east-1"
25+
26+
def main():
27+
# Build the boto3 client for neptune-graph with endpoint override
28+
client = boto3.client(
29+
"neptune-graph",
30+
region_name=REGION,
31+
endpoint_url=NEPTUNE_ANALYTICS_ENDPOINT
32+
)
33+
34+
try:
35+
execute_gremlin_profile_query(client, GRAPH_ID)
36+
except Exception as e:
37+
print(f"Unexpected error in main: {e}")
38+
39+
def execute_gremlin_profile_query(client, graph_id):
40+
"""
41+
Executes a Gremlin or OpenCypher query on Neptune Analytics graph.
42+
43+
Args:
44+
client (boto3.client): The NeptuneGraph client.
45+
graph_id (str): The graph identifier.
46+
"""
47+
print("Running openCypher query on Neptune Analytics...")
48+
49+
try:
50+
response = client.execute_query(
51+
GraphIdentifier=graph_id,
52+
QueryString="MATCH (n {code: 'ANC'}) RETURN n",
53+
Language="OPEN_CYPHER"
54+
)
55+
56+
# The response 'Payload' may contain the query results as a streaming bytes object
57+
# Convert to string and print
58+
if 'Payload' in response:
59+
result = response['Payload'].read().decode('utf-8')
60+
print("Query Result:")
61+
print(result)
62+
else:
63+
print("No query result returned.")
64+
65+
except ClientError as e:
66+
print(f"NeptuneGraph error: {e.response['Error']['Message']}")
67+
except Exception as e:
68+
print(f"Unexpected error: {e}")
69+
70+
if __name__ == "__main__":
71+
main()

python/example_code/neptune/database/GremlinProfileQueryExample.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
from botocore.exceptions import BotoCoreError, ClientError
99

1010
"""
11-
Example: Running a Gremlin PROFILE query using the AWS SDK for Python (Boto3).
11+
Running this example.
1212
1313
----------------------------------------------------------------------------------
1414
VPC Networking Requirement:

python/example_code/neptune/database/NeptuneGremlinExplainAndProfileExample.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
from botocore.exceptions import BotoCoreError, ClientError
77

88
"""
9-
Example: Running a Gremlin PROFILE query using the AWS SDK for Python (Boto3).
9+
Running this example.
1010
1111
----------------------------------------------------------------------------------
1212
VPC Networking Requirement:

python/example_code/neptune/database/NeptuneGremlinQueryExample.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
1+
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2+
# SPDX-License-Identifier: Apache-2.0
3+
14
import boto3
25
from botocore.config import Config
36
from botocore.exceptions import BotoCoreError, ClientError
47

58
"""
6-
Example: Running a Gremlin PROFILE query using the AWS SDK for Python (Boto3).
9+
Running this example.
710
811
----------------------------------------------------------------------------------
912
VPC Networking Requirement:

python/example_code/neptune/database/OpenCypherExplainExample.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
from botocore.exceptions import ClientError, BotoCoreError
77

88
"""
9-
Example: Running a Gremlin PROFILE query using the AWS SDK for Python (Boto3).
9+
Running this example.
1010
1111
----------------------------------------------------------------------------------
1212
VPC Networking Requirement:

0 commit comments

Comments
 (0)