Amazon Neptune
User Guide (API Version 2017-11-29)

Using .NET to Connect to a Neptune DB Instance

The following section contains a code example written in C# that connects to a Neptune DB instance and performs a Gremlin traversal.

Connections to Amazon Neptune must be from an Amazon EC2 instance in the same virtual private cloud (VPC) as your Neptune DB instance. This sample code was tested on an Amazon EC2 instance running Ubuntu.

Before you begin, do the following:

  • Install .NET on the Amazon EC2 instance. To get instructions for installing .NET on multiple operating systems, including Windows, Linux, and macOS, see Get Started with .NET.

  • Install Gremlin.NET by running dotnet add package gremlin.net for your package. For more information, see Gremlin.NET in the TinkerPop documentation.

To connect to Neptune using Gremlin.NET

  1. Create a new .NET project.

    dotnet new console -o gremlinExample
  2. Change directories into the new project directory.

    cd gremlinExample
  3. Copy the following into the Program.cs file. Replace your-neptune-endpoint with the address of your Neptune DB instance.

    For information about finding the address of your Neptune DB instance, see the Amazon Neptune Endpoints section.

    using System; using System.Threading.Tasks; using System.Collections.Generic; using Gremlin.Net; using Gremlin.Net.Driver; 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); Program program = new Program(); program.RunQueryAsync(gremlinClient).Wait(); } catch (Exception e) { Console.WriteLine("{0}", e); } } private async Task RunQueryAsync(GremlinClient gremlinClient) { var count = await gremlinClient.SubmitWithSingleResultAsync<long>( "g.V().limit(1).count().next()"); Console.WriteLine("{0}", count); } } }
  4. Enter the following command to run the sample:

    dotnet run

    The Gremlin query at the end of this example returns the count of a single vertex for testing purposes. It is then printed to the console.

    Note

    The final part of the Gremlin query, next(), is required to submit the traversal to the server for evaluation. If you don't include that method or another equivalent method, the query is not submitted to the Neptune DB instance.

    The following methods submit the query to the Neptune DB instance:

    • toList()

    • toSet()

    • next()

    • nextTraverser()

    • iterate()

    The preceding example returns a number by using the g.V().limit(1).count().next() traversal. To query for something else, replace it with another Gremlin traversal with one of the appropriate ending methods.

    For more information about Amazon Neptune, see Next Steps.