本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
使用 .NET 连接到 Neptune 数据库实例
以下部分包含采用 C# 编写的代码示例,该示例连接到 Neptune 数据库实例并执行 Grimlin 遍历。
到 Amazon Neptune 的连接必须来自与您的 Neptune 数据库实例位于同一 Virtual Private Cloud (VPC) 中的 Amazon EC2 实例。此示例代码已在运行 Ubuntu 的 Amazon EC2 实例上进行测试。
开始之前,请执行以下操作:
在 Amazon 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
文件中。Replaceyour-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 遍历。