在Jupyter中存储/获取AWS Neptune ML的Gremlin查询结果
解决方案
方法1:通过Neptune HTTP API直接执行查询并处理结果
Neptune提供HTTP端点接收Gremlin查询,用Python的requests库发送POST请求,即可获取结果并赋值给变量,也能保存为JSON文件。
步骤与代码示例:
import requests import json # 替换为你的实际集群端点、ML端点和节点ID neptune_endpoint = "your-neptune-cluster-endpoint:8182" ml_endpoint = "your-neptune-ml-endpoint" target_node_id = "your-target-node-id" # 构造带Neptune ML扩展的Gremlin查询 gremlin_query = f""" g.with("Neptune#ml.endpoint","{ml_endpoint}"). V("{target_node_id}"). project('name', 'related to'). by('name'). by( out('RELATED_TO').with("Neptune#ml.prediction"). hasLabel('TYPE_X').values('name') ). order(local).by(keys, desc) """ # 发送POST请求到Neptune Gremlin端点 response = requests.post( f"https://{neptune_endpoint}/gremlin", json={"gremlin": gremlin_query}, headers={"Content-Type": "application/json"} ) # 解析并处理结果 if response.status_code == 200: result_data = response.json()["result"]["data"] # 赋值给变量 prediction_results = result_data print(prediction_results) # 保存为JSON文件 with open("neptune_ml_predictions.json", "w") as f: json.dump(prediction_results, f, indent=2) else: print(f"查询失败:状态码{response.status_code},错误信息:{response.text}")
方法2:使用Neptune Python SDK(需确认版本兼容性)
AWS Neptune官方Python SDK(aws-neptune-gremlin-python)可能支持Neptune ML扩展语法,先升级到最新版本:
pip install aws-neptune-gremlin-python --upgrade
然后连接集群执行查询:
from gremlin_python.driver import client, serializer import json neptune_client = client.Client( "wss://your-neptune-cluster-endpoint:8182/gremlin", "g", message_serializer=serializer.GraphSONSerializersV2d0() ) try: query = f""" g.with("Neptune#ml.endpoint","{ml_endpoint}"). V("{target_node_id}"). project('name', 'related to'). by('name'). by( out('RELATED_TO').with("Neptune#ml.prediction"). hasLabel('TYPE_X').values('name') ). order(local).by(keys, desc) """ result_set = neptune_client.submit(query) prediction_results = [dict(item) for item in result_set.all().result()] # 保存结果到文件 with open("predictions.json", "w") as f: json.dump(prediction_results, f, indent=2) finally: neptune_client.close()
如果SDK仍不支持Neptune ML扩展语法,方法1的HTTP API方式是更可靠的替代方案。
方法3:尝试捕获%%gremlin魔法命令输出
部分版本的Neptune Jupyter魔法命令支持-o参数将输出赋值给变量,可尝试:
%%gremlin -o prediction_results g.with("Neptune#ml.endpoint","${endpoint}"). V(${id_variable}). project('name', 'related to'). by('name'). by( out('RELATED_TO').with("Neptune#ml.prediction"). hasLabel('TYPE_X').values('name') ). order(local).by(keys, desc)
如果参数有效,prediction_results变量将存储查询结果,后续可通过json.dump保存为文件。该功能依赖魔法命令版本,需确认环境支持情况。
内容的提问来源于stack exchange,提问作者Luca P.
相关产品推荐
相关产品推荐

