Exemple #1
0
        public void ConnectingTest()
        {
// tag::connecting[]
            var remoteConnection = new DriverRemoteConnection(new GremlinClient(new GremlinServer("localhost", 8182)), "g");
            var g = Traversal().WithRemote(remoteConnection);
// end::connecting[]
        }
Exemple #2
0
        public IRemoteConnection CreateRemoteConnection()
        {
            var c = new DriverRemoteConnection(JanusGraphClientBuilder
                                               .BuildClientForServer(new GremlinServer(_host, _port)).WithSerializer(_serializer).Create());

            _connections.Add(c);
            return(c);
        }
        public void ShouldDisposeProvidedGremlinClientOnDispose()
        {
            var gremlinClientMock      = new Mock <IGremlinClient>();
            var driverRemoteConnection = new DriverRemoteConnection(gremlinClientMock.Object);

            driverRemoteConnection.Dispose();

            gremlinClientMock.Verify(m => m.Dispose());
        }
        public IRemoteConnection CreateRemoteConnection(string traversalSource = "gods_traversal")
        {
            var c = new DriverRemoteConnection(
                JanusGraphClientBuilder.BuildClientForServer(new GremlinServer(_host, _port)).Create(),
                traversalSource);

            _connections.Add(c);
            return(c);
        }
        public void DslTest()
        {
// tag::dslExamples[]
            var connection = new DriverRemoteConnection(new GremlinClient(new GremlinServer("localhost", 8182)));
            var social     = Traversal().WithRemote(connection);

            social.Persons("marko").Knows("josh");
            social.Persons("marko").YoungestFriendsAge();
            social.Persons().Filter(CreatedAtLeast(2)).Count();
// end::dslExamples[]
        }
Exemple #6
0
        public Task InitialiseAsync(CancellationToken cancellationToken = default)
        {
            var gremlinServer = new GremlinServer(
                _settings.Hostname,
                _settings.Port,
                _settings.EnableSsl,
                _settings.Username,
                _settings.Password);

            _client = new Gremlin.Net.Driver.GremlinClient(gremlinServer);
            _remote = new DriverRemoteConnection(_client);
            return(Task.CompletedTask);
        }
        public async Task <Dictionary <string, object> > GetAsync()
        {
            var result = new Dictionary <string, object>();

            try
            {
                var gremlinServiceEndpoint = configuration["Database:GremlinEndpointHostname"];
                var gremlinServicePort     = Int32.Parse(configuration["Database:GremlinEndpointPort"]);
                var gremlinUsername        = configuration["Database:GremlinUsername"];
                var gremlinPassword        = configuration["Database:GremlinPassword"];
                var partitionKey           = configuration["Database:PartitionKey"];
                var useSSL = Boolean.Parse(configuration["Database:UseSSL"]);


                var gremlinServer = new GremlinServer(gremlinServiceEndpoint, gremlinServicePort, useSSL, gremlinUsername, gremlinPassword);

                var random = new Random();

                //NOTE: Downgrading to GraphSON2Reader/Writer is necessary, when connecting to a Cosmos DB (GraphSON3 not supported?)
                var gremlinClient = new GremlinClient(gremlinServer, new GraphSON2Reader(), new GraphSON2Writer(), GremlinClient.GraphSON2MimeType);



                await gremlinClient.SubmitAsync("g.V().drop()");

                await gremlinClient.SubmitAsync($"g.addV('Person').property('{partitionKey}', '{random.Next()}').property('name', 'John Doe')");

                //NOTE: Creating a new graph and traversal works fine, even with a defined RemoteConnection. The connection is not yet established
                var graph      = new Graph();
                var connection = new DriverRemoteConnection(gremlinClient);
                var traversal  = graph.Traversal()
                                 .WithRemote(connection)
                                 .V().HasLabel("Person").Count();


                var count = traversal.Next(); //NOTE: this throws a NullReferenceException on CosmosDB, but works fine on Tinkerpop's Gremlin-Server

                //NOTE: expected result would be "1"
                result.Add("count", count);
            }
            catch (Exception e)
            {
                result.Add("exception", e);
            }
            finally
            {
            }
            return(result);
        }
        public async Task <HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
        {
            try
            {
                using (var client = new GremlinClient(_server))
                    using (var conn = new DriverRemoteConnection(client))
                    {
                        var g = Traversal().WithRemote(conn);
                        await g.Inject(0).Promise(t => t.Next());
                    }
            }
            catch (Exception ex)
            {
                return(new HealthCheckResult(status: context.Registration.FailureStatus, exception: ex));
            }

            return(HealthCheckResult.Healthy());
        }
Exemple #9
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton <GremlinClient>(
                (serviceProvider) =>
            {
                var gremlinServer = new GremlinServer(
                    hostname: "localhost",
                    port: 8182,
                    enableSsl: false,
                    username: null,
                    password: null
                    );

                var connectionPoolSettings = new ConnectionPoolSettings
                {
                    MaxInProcessPerConnection = 32,
                    PoolSize              = 4,
                    ReconnectionAttempts  = 4,
                    ReconnectionBaseDelay = TimeSpan.FromSeconds(1)
                };

                return(new GremlinClient(
                           gremlinServer: gremlinServer,
                           connectionPoolSettings: connectionPoolSettings
                           ));
            }
                );

            services.AddSingleton <GraphTraversalSource>(
                (serviceProvider) =>
            {
                GremlinClient gremlinClient = serviceProvider.GetService <GremlinClient>();
                var driverRemoteConnection  = new DriverRemoteConnection(gremlinClient, "g");
                return(AnonymousTraversalSource.Traversal().WithRemote(driverRemoteConnection));
            }
                );

            services.AddRazorPages();
        }
Exemple #10
0
        public string FunctionHandler(object input, ILambdaContext context)
        {
            var access_key       = "youraccesskey";
            var secret_key       = "yoursecretkey";
            var neptune_endpoint = "yourneptuneendpoint:8182"; // ex: mycluster.cluster.us-east-1.neptune.amazonaws.com
            var neptune_region   = "us-east-1";                //ex: us-east-1
            var using_ELB        = false;                      //Set to True if using and ELB and define ELB URL via ELB_endpoint variable
            var ELB_endpoint     = "";                         //ex: myelb.elb.us-east-1.amazonaws.com

            var neptunesigner = new AWS4RequestSigner(access_key, secret_key);
            var request       = new HttpRequestMessage
            {
                Method     = HttpMethod.Get,
                RequestUri = new Uri("http://" + neptune_endpoint + "/gremlin")
            };
            var signedrequest = neptunesigner.Sign(request, "neptune-db", neptune_region);
            var authText      = signedrequest.Headers.GetValues("Authorization").FirstOrDefault();
            var authDate      = signedrequest.Headers.GetValues("x-amz-date").FirstOrDefault();

            var webSocketConfiguration = new Action <ClientWebSocketOptions>(options => {
                options.SetRequestHeader("host", neptune_endpoint);
                options.SetRequestHeader("x-amz-date", authDate);
                options.SetRequestHeader("Authorization", authText);
            });

            /* GremlinServer() accepts the hostname and port as separate parameters.
             * Split the endpoint into both variables to pass to GremlinServer()
             *
             * Also - determine if an ELB is used.  If using an ELB, connect using the ELB hostname.
             */

            var neptune_host = "";

            if (using_ELB)
            {
                neptune_host = ELB_endpoint;
            }
            else
            {
                neptune_host = neptune_endpoint.Split(':')[0];
            }

            var neptune_port = int.Parse(neptune_endpoint.Split(':')[1]);

            var gremlinServer = new GremlinServer(neptune_host, neptune_port);


            var gremlinClient    = new GremlinClient(gremlinServer, webSocketConfiguration: webSocketConfiguration);
            var remoteConnection = new DriverRemoteConnection(gremlinClient);
            var g = Traversal().WithRemote(remoteConnection);

            foreach (var query in gremlinQueries)
            {
                Console.WriteLine(String.Format("Running this query: {0}: {1}", query.Key, query.Value));

                // Create async task to execute the Gremlin query.
                var resultSet = SubmitRequest(gremlinClient, query).Result;

                if (resultSet.Count > 0)
                {
                    Console.WriteLine("\tResult:");
                    foreach (var result in resultSet)
                    {
                        // The vertex results are formed as Dictionaries with a nested dictionary for their properties
                        string output = JsonConvert.SerializeObject(result);
                        Console.WriteLine($"\t{output}");
                    }
                    Console.WriteLine();
                }
            }

            return("Hello World");
        }
        static void Main(string[] args)
        {
            var access_key       = "youraccesskey";
            var secret_key       = "yoursecretkey";
            var neptune_endpoint = "yourneptuneendpoint"; // ex: mycluster.cluster.us-east-1.neptune.amazonaws.com
            var neptune_region   = "us-east-1";           //ex: us-east-1
            var using_ELB        = false;                 //Set to True if using and ELB and define ELB URL via ELB_endpoint variable
            var ELB_endpoint     = "";                    //ex: myelb.elb.us-east-1.amazonaws.com

            /* The AWS4RequestSigner library was intented to pass a signed request to an HTTP endpoint.
             * Since we're using websockets, we will create the HTTP request and sign the request, however
             * we will pull the headers from the signed request in order to create a webSocketConfiguration
             * object with these same headers.
             */
            var neptunesigner = new AWS4RequestSigner(access_key, secret_key);
            var request       = new HttpRequestMessage
            {
                Method     = HttpMethod.Get,
                RequestUri = new Uri("http://" + neptune_endpoint + "/gremlin")
            };
            var signedrequest = neptunesigner.Sign(request, "neptune-db", neptune_region);
            var authText      = signedrequest.Headers.GetValues("Authorization").FirstOrDefault();
            var authDate      = signedrequest.Headers.GetValues("x-amz-date").FirstOrDefault();

            var webSocketConfiguration = new Action <ClientWebSocketOptions>(options => {
                options.SetRequestHeader("host", neptune_endpoint);
                options.SetRequestHeader("x-amz-date", authDate);
                options.SetRequestHeader("Authorization", authText);
            });

            /* GremlinServer() accepts the hostname and port as separate parameters.
             * Split the endpoint into both variables to pass to GremlinServer()
             *
             * Also - determine if an ELB is used.  If using an ELB, connect using the ELB hostname.
             */
            var neptune_host = "";

            if (using_ELB)
            {
                neptune_host = ELB_endpoint;
            }
            else
            {
                neptune_host = neptune_endpoint.Split(':')[0];
            }
            var neptune_port = int.Parse(neptune_endpoint.Split(':')[1]);

            var gremlinServer = new GremlinServer(neptune_host, neptune_port);


            var gremlinClient    = new GremlinClient(gremlinServer, webSocketConfiguration: webSocketConfiguration);
            var remoteConnection = new DriverRemoteConnection(gremlinClient);
            var g = Traversal().WithRemote(remoteConnection);

            /* Example code to pull the first 5 vertices in a graph. */
            Console.WriteLine("Get List of Node Labels:");



            foreach (var query in gremlinQueries)
            {
                Console.WriteLine(String.Format("Running this query: {0}: {1}", query.Key, query.Value));

                // Create async task to execute the Gremlin query.
                var resultSet = SubmitRequest(gremlinClient, query).Result;

                if (resultSet.Count > 0)
                {
                    Console.WriteLine("\tResult:");
                    foreach (var result in resultSet)
                    {
                        // The vertex results are formed as Dictionaries with a nested dictionary for their properties
                        string output = JsonConvert.SerializeObject(result);
                        Console.WriteLine($"\t{output}");
                    }
                    Console.WriteLine();
                }


                PrintStatusAttributes(resultSet.StatusAttributes);
                Console.WriteLine();
            }
        }
Exemple #12
0
        private static GraphTraversalSource CreateGraphTraversalSource(GremlinClient gremlinClient, string traversalSource)
        {
            var driverRemoteConnection = new DriverRemoteConnection(gremlinClient, traversalSource);

            return(AnonymousTraversalSource.Traversal().WithRemote(driverRemoteConnection));
        }
Exemple #13
0
        // Run some tests
        static void Main(string[] args)
        {
            Console.WriteLine("\nStarting tests\n");

            GraphTraversalSource g             = null;
            GremlinClient        gremlinClient = null;

            // For testing, the default connection pool settings are fine.  To specify
            // custom values it is necessary to create a ConnectionPoolSettings object and
            // pass it to the GremlinClient upon creation.  The values used below are in
            // fact the default values but can be changed as needed.

            ConnectionPoolSettings cpSettings = new ConnectionPoolSettings();

            cpSettings.PoolSize = 4;
            cpSettings.MaxInProcessPerConnection = 32;
            cpSettings.ReconnectionAttempts      = 4;
            cpSettings.ReconnectionBaseDelay     = new TimeSpan((long)(1E9 / 100));

            // Establish a connection to the server
            try
            {
                var gremlinServer = new GremlinServer("localhost", 8182, enableSsl: false);

                // It is only required to pass a value for connectionPoolSettings if you want
                // to override any of the default values. Other options, such as which
                // serializer and deserializer to use, can also be specified as parameters to
                // the GremlinClient. The parameter names are graphSONReader and
                // graphSONWriter. At time of writing the defaults specify GraphSON3Reader
                // and GraphSON3Writer and this code does not override those settings.

                gremlinClient = new GremlinClient(gremlinServer, connectionPoolSettings: cpSettings);

                var remoteConnection = new DriverRemoteConnection(gremlinClient, "g");
                g = Traversal().WithRemote(remoteConnection);
            }
            catch (Exception e)
            {
                Console.WriteLine($"Failed to create a connection:\n ==> {e.Message}");
                System.Environment.Exit(1);
            }

            //
            // If we were able to open a connection, start running some tests.
            //

            // Count some vertices as a simple test
            Console.WriteLine("\nVertex Count tests");
            Console.WriteLine("------------------");

            var ct = g.V().Limit <Vertex>(5000).Count().Next();

            Console.WriteLine($"The count was {ct}");

            // Retrieve a few values from vertices
            Console.WriteLine("\nValues step tests");
            Console.WriteLine("-----------------");

            var cities =
                g.V().
                Has("airport", "region", "US-TX").
                Limit <Vertex>(10).
                Values <string>("city").
                ToList();

            PrintList <string>(cities);


            // Experiment with Path results
            Console.WriteLine("\nPath tests");
            Console.WriteLine("----------");

            var paths =
                g.V().Has("code", "AUS").
                Out("route").
                Path().
                By("code").
                Limit <Path>(5).
                ToList();

            PrintList <Path>(paths);

            Console.WriteLine();

            paths =
                g.V().
                Has("code", "AUS").
                OutE("route").
                InV().
                Path().
                By("code").
                By("dist").
                Limit <Path>(5).
                ToList();

            PrintList <Path>(paths);

            // Experiment with Repeat..Until
            Console.WriteLine("\nRepeat..Until tests");
            Console.WriteLine("-------------------");

            paths =
                g.V().
                Has("code", "AUS").
                Repeat(Out().SimplePath()).
                Until(Has("code", "WLG")).
                Path().
                By("code").
                Limit <Path>(5).
                ToList();

            PrintList <Path>(paths);

            // Experiment with a ValueMap step. This will generate a map result
            // represented as a .Net Dictionary.
            Console.WriteLine("\nValueMap test");
            Console.WriteLine("-------------");

            var vmap =
                g.V().
                Has("code", "AUS").
                ValueMap <string, object>().
                By(Unfold <object[]>()).
                Next();

            PrintDict <string, object>(vmap);

            //
            // Experiment with a GroupCount step. This will also generate a map result
            // represented as a .Net Dictionary..
            //
            Console.WriteLine("\nUsing GroupCount to find label distribution");
            Console.WriteLine("-------------------------------------------");

            var labelMap = g.V().GroupCount <string>().By(T.Label).Next();

            PrintDict <string, long>(labelMap);
            //foreach (string key in labelMap.Keys)
            //{
            //  Console.WriteLine($" {key} ==> {labelMap[key]}");
            //}

            //Find routes with no corresponding return flight.
            Console.WriteLine("\nWhere, Not and As tests (finding flights with no corresponding return)");
            Console.WriteLine("----------------------------------------------------------------------");

            paths =
                g.V().
                HasLabel("airport").As("a").
                Out("route").
                Where(Not(Out("route").As("a"))).
                Path().
                By("code").
                ToList();

            var found = paths.Count;

            Console.WriteLine($" Found {found} one-way only routes");

            if (found >= 10)
            {
                found = 10;
            }
            Console.WriteLine($" Here are {found} of them");
            PrintList <Path>(paths.Take(found).ToList());

            // As the prior query but using a match step
            Console.WriteLine("\nPerforming the previous count using a Match step");
            Console.WriteLine("------------------------------------------------");
            var count =
                g.V().
                HasLabel("airport").
                Match <Vertex>(__.As("a").Out("route").As("b"),
                               __.Not(__.As("b").Out("route").As("a"))).
                Count().
                Next();

            Console.WriteLine($"The count using a match step is {count}");

            // Instantiate a subgraph strategy and try counting vertices
            Console.WriteLine("\nWithStrategies tests");
            Console.WriteLine("--------------------");

            var g2  = g.WithStrategies(new SubgraphStrategy(vertices: Has("region", "US-TX")));
            var ct2 = g2.V().Count().Next();

            Console.WriteLine($" The count was {ct2}");

            // Instantiate a partition strategy and try another count
            string[] regions = { "US-TX" };

            var g3 = g.WithStrategies(new PartitionStrategy(
                                          partitionKey: "region", readPartitions: regions));

            var ct3 = g3.V().Count().Next();

            Console.WriteLine($" The count was {ct3}");


            // Create a vertex and some properties
            Console.WriteLine("\nAddV and Property tests");
            Console.WriteLine("-----------------------");
            var vertex =
                g.AddV("Dog").
                Property(T.Id, "dog-1").
                Property("name", "Max").
                Property(Set, "likes", "Toys").
                Property(Set, "likes", "Digging holes").
                Property(Set, "likes", "Long walks").
                Property(Set, "likes", "Chasing squirrels").
                Id().
                Next();

            Console.WriteLine($" New vertex created with ID '{vertex}'");

            var max = g.V("dog-1").ValueMap <string, object[]>().Next();

            Console.WriteLine($" The dog with ID {vertex} is called {max["name"][0]}");
            Console.WriteLine(" Max likes:");

            foreach (string like in max["likes"])
            {
                Console.WriteLine($"   {like}");
            }


            // All done clean up
            Console.WriteLine("\nDeleting the vertex. Closing connection.");
            Console.WriteLine("----------------------------------------");
            g.V(vertex).Drop().Iterate();

            gremlinClient.Dispose();
            Console.WriteLine(" All done!");
        }