本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
使用 .NET 连接到 Neptune 数据库实例
如果可以的话,请始终使用您的引擎版本支持的最新版本的 Apache TinkerPop .NET Gremlin 客户端 Gremlin.NetGremlin.Net
版本通常与 Java Gremlin 客户端表中描述的 TinkerPop版本保持一致。
以下部分包含采用 C# 编写的代码示例,该示例连接到 Neptune 数据库实例并执行 Gremlin 遍历。
与 Amazon Neptune 的连接必须来自与您的 Neptune EC2 数据库实例位于同一个虚拟私有云 (VPC) 中的亚马逊实例。此示例代码已在运行 Ubuntu 的亚马逊 EC2 实例上进行了测试。
开始之前,请执行以下操作:
在亚马逊 EC2 实例上安装.NET。要获取有关在多个操作系统 (包括 Windows、Linux 和 macOS) 上安装 .NET 的说明,请参阅 .NET 入门
。 通过为您的程序包运行
dotnet add package gremlin.net
来安装 Gremlin.NET。有关更多信息,请参阅文档中的 Gremlin.net。 TinkerPop
使用 Gremlin.NET 连接到 Neptune
-
创建新的 .NET 项目。
dotnet new console -o gremlinExample
-
将目录更改为新项目目录。
cd gremlinExample
-
将以下内容复制到
Program.cs
文件中。your-neptune-endpoint
替换为您的 Neptune 数据库实例的地址。有关查找 Neptune 数据库实例的地址的信息,请参阅连接到 Amazon Neptune 端点部分。
using System; using System.Threading.Tasks; using System.Collections.Generic; using Gremlin.Net; using Gremlin.Net.Driver; using Gremlin.Net.Driver.Remote; using Gremlin.Net.Structure; using static Gremlin.Net.Process.Traversal.AnonymousTraversalSource; namespace gremlinExample { class Program { static void Main(string[] args) { try { var endpoint = "your-neptune-endpoint"; // This uses the default Neptune and Gremlin port, 8182 var gremlinServer = new GremlinServer(endpoint, 8182, enableSsl: true ); var gremlinClient = new GremlinClient(gremlinServer); var remoteConnection = new DriverRemoteConnection(gremlinClient, "g"); var g = Traversal().WithRemote(remoteConnection); g.AddV("Person").Property("Name", "Justin").Iterate(); g.AddV("Custom Label").Property("name", "Custom id vertex 1").Iterate(); g.AddV("Custom Label").Property("name", "Custom id vertex 2").Iterate(); var output = g.V().Limit<Vertex>(3).ToList(); foreach(var item in output) { Console.WriteLine(item); } } catch (Exception e) { Console.WriteLine("{0}", e); } } } }
-
输入以下命令以运行示例:
dotnet run
此示例结尾处的 Gremlin 查询将返回用于测试目的的单个顶点的计数。然后,它将输出到控制台。
注意
要将遍历提交到服务器进行评估,需要 Gremlin 查询的最后一部分
Next()
。如果您未包含该方法或其它等效方法,该查询将不会提交到 Neptune 数据库实例。以下方法将查询提交到 Neptune 数据库实例:
ToList()
ToSet()
Next()
NextTraverser()
Iterate()
如果您需要序列化并返回查询结果,请使用
Next()
,否则请使用Iterate()
。上述示例通过使用
g.V().Limit(3).ToList()
遍历返回一个列表。要查询其他内容,请将其替换为具有其中一种适当的结尾方法的其他 Gremlin 遍历。