Example #1
0
        public void Should_Execute_Batch_Of_Traversals(string graphName, GraphProtocol protocol)
        {
            if (graphName == BaseIntegrationTest.DefaultCoreGraphName &&
                !TestDseVersion.VersionMatch(
                    new Version(6, 8), TestClusterManager.DseVersion, Comparison.GreaterThanOrEqualsTo))
            {
                Assert.Ignore("Test requires DSE 6.8");
            }

            var g = DseGraph.Traversal(Session, new GraphOptions().SetName(graphName));

            if (graphName == BaseIntegrationTest.DefaultCoreGraphName)
            {
                g = g.With("allow-filtering");
            }
            var batch = DseGraph.Batch(new GraphOptions().SetName(graphName).SetWriteConsistencyLevel(ConsistencyLevel.LocalQuorum));

            batch
            .Add(g.AddV("character").Property("name", "Matias").Property("age", 12).Property("tag", "batch1"))
            .Add(g.AddV("character").Property("name", "Olivia").Property("age", 8).Property("tag", "batch1"));

            var rs = Session.ExecuteGraph(batch);

            Assert.AreEqual(protocol, rs.GraphProtocol);

            var list = g.V().Has("character", "tag", "batch1").Values <string>("name").ToList();

            CollectionAssert.AreEquivalent(new [] { "Matias", "Olivia" }, list);
        }
Example #2
0
        public void Should_Retrieve_Path_With_Labels()
        {
            var g      = DseGraph.Traversal(Session);
            var result = g.V().HasLabel("person").Has("name", "marko").As("a")
                         .OutE("knows").As("b")
                         .InV().As("c", "d")
                         .OutE("created").As("e", "f", "g")
                         .InV().As("h")
                         .Path().ToList();

            Assert.AreEqual(2, result.Count);
            foreach (var path in result)
            {
                var pathObjs = path.Objects;
                Assert.AreEqual(5, pathObjs.Count);
                var marko    = (Gremlin.Net.Structure.Vertex)pathObjs[0];
                var knows    = (Gremlin.Net.Structure.Edge)pathObjs[1];
                var josh     = (Gremlin.Net.Structure.Vertex)pathObjs[2];
                var created  = (Gremlin.Net.Structure.Edge)pathObjs[3];
                var software = (Gremlin.Net.Structure.Vertex)pathObjs[4];

                Assert.AreEqual(marko.Label, "person");
                Assert.AreEqual(knows.Label, "knows");
                Assert.AreEqual(josh.Label, "person");
                Assert.AreEqual(created.Label, "created");
                Assert.AreEqual(software.Label, "software");
            }
        }
Example #3
0
        public static void Main()
        {
            IDseCluster cluster = DseCluster.Builder().
                                  AddContactPoint("127.0.0.1").
                                  WithGraphOptions(new GraphOptions().SetName("killrvideo")).
                                  Build();
            IDseSession session = cluster.Connect();
            var         killr   = DseGraph.Traversal(session);

            PrintHeader("Actors for Young Guns", "killr.Movies(\"Young Guns\").Actors().Values(\"name\")");
            var results = killr.Movies("Young Guns").Actors().Values <string>("name").ToList();

            PrintItems(results);

            PrintHeader("Ratings Distribution by Age for Young Guns", "killr.Movies(\"Young Guns\").Ratings().DistributionForAges(18, 40)");
            IDictionary <string, long> ratingsByAge = killr.Movies("Young Guns").Ratings().DistributionForAges(18, 40).Next();
            var pairs = String.Join(", ", ratingsByAge.Select(kvp => kvp.Key + "=" + kvp.Value.ToString()));

            Console.WriteLine($"[{pairs}]");

            PrintHeader("Failed Validation", "killr.Movies(\"Young Guns\").Ratings().DistributionForAges(17,40)");
            try
            {
                killr.Movies("Young Guns").Ratings().DistributionForAges(17, 40).Next();
            }
            catch (ArgumentException ae)
            {
                Console.WriteLine($"Caught ArgumentException: {ae.Message}");
            }

            PrintHeader("Five Recommendations for u460", "killr.Users(\"u460\").Recommend(5, 7).Values(KEY_TITLE)");
            results = killr.Users("u460").Recommend(5, 7).Values <string>(KeyTitle).ToList();
            PrintItems(results);

            PrintHeader("Five Recommendations for u460 that are comedies", "killr.Users(\"u460\").Recommend(5, 7, Genre(COMEDY)).Values(KEY_TITLE)");
            results = killr.Users("u460").Recommend(5, 7, Genre(Comedy)).Values <string>(KeyTitle).ToList();
            PrintItems(results);

            PrintHeader("Five Recommendations for u460 that use larger actor sampling and are comedies", "killr.users(\"u460\").recommend(5, 7, genre(COMEDY)).values(KEY_TITLE)");
            results = killr.Users("u460").Recommend(5, 7, LargeSample, Genre(Comedy)).Values <string>(KeyTitle).ToList();
            PrintItems(results);

            PrintHeader("Include some additional graph statistics about Young Guns", "killr.movies(\"Young Guns\").enrich(IN_DEGREE, OUT_DEGREE)");
            IDictionary <object, object> enriched = killr.Movies("Young Guns").enrich(InDegree, OutDegree).Next();

            pairs = String.Join(", ", enriched.Select(kvp => kvp.Key + "=" + kvp.Value.ToString()));
            Console.WriteLine($"[{pairs}]");

            PrintHeader("Insert/update movie and a actors for that movie", "killr.movie(\"m100000\", \"Manos: The Hands of Fate\",...).actor(...)");
            killr.Movie("m100000", "Manos: The Hands of Fate", 1966, 70, "USA", "Sun City Films").
            Ensure <Vertex, object, Vertex>(__KillrVideo.Actor("p1000000", "Tom Neyman")).
            Ensure <Vertex, object, Vertex>(__KillrVideo.Actor("p1000001", "John Reynolds")).
            Ensure <Vertex, object, Vertex>(__KillrVideo.Actor("p1000002", "Diane Mahree")).
            Iterate();
            Console.WriteLine("Updated 'Manos: The Hands of Fate'");

            PrintHeader("Get the actors for the newly added movie", "killr.movies(\"Manos: The Hands of Fate\").actors().values(\"name\")");
            results = killr.Movies("Manos: The Hands of Fate").Actors().Values <String>("name").ToList();
            PrintItems(results);
        }
Example #4
0
        public void Should_Be_Able_To_Query_With_Predicate()
        {
            var g     = DseGraph.Traversal(Session);
            var edges = g.With("allow-filtering").E().HasLabel("knows").Has("weight", P.Gte(0.5f)).ToList();

            TraversalCoreIntegrationTest.VerifyEdgeResults(edges, 2, "knows");

            edges = g.With("allow-filtering").E().HasLabel("knows").Has("weight", P.Between(0.4f, 0.6f)).ToList();
            TraversalCoreIntegrationTest.VerifyEdgeResults(edges, 1, "knows");

            edges = g.With("allow-filtering").E().HasLabel("knows").Has("weight", P.Eq(0.5f)).ToList();
            TraversalCoreIntegrationTest.VerifyEdgeResults(edges, 1, "knows");

            edges = g.With("allow-filtering").E().HasLabel("knows").Has("weight", P.Eq(0.5f)).ToList();
            TraversalCoreIntegrationTest.VerifyEdgeResults(edges, 1, "knows");

            var vertices = g.With("allow-filtering").V().HasLabel("person").Has("name", P.Eq("marko")).ToList();

            TraversalCoreIntegrationTest.VerifyVertexResults(vertices, 1, "person");

            vertices = g.With("allow-filtering").V().HasLabel("person").Has("name", P.Neq("marko")).ToList();
            TraversalCoreIntegrationTest.VerifyVertexResults(vertices, 3, "person");

            vertices = g.With("allow-filtering").V().HasLabel("person").Has("name", P.Within("marko", "josh", "john")).ToList();
            TraversalCoreIntegrationTest.VerifyVertexResults(vertices, 2, "person");
        }
        /// <summary>
        /// Create new node in the Graph for
        /// </summary>
        public async Task UpdatGraphForNewVideo(YouTubeVideoAdded video)
        {
            String videoId = video.VideoId.ToGuid().ToString();
            String userId  = video.UserId.ToGuid().ToString();

            Logger.Information("{user} Inserting video {video} to graph", userId, videoId);

            // Create Traversal to add a Vertex Video, Edge 'upload from user to Vide, and Tags
            var traversal = DseGraph.Traversal(_session)

                            // Creating Video Vertex based on ID
                            .CreateOrUpdateVideoVertex(
                videoId,
                video.Name,
                video.Description,
                video.PreviewImageLocation
                )

                            // Edge User -- Uploaded --> Video
                            .CreateEdgeUploadedForUserAndVideo(userId);

            // Add Tags Vertices and edges to video
            foreach (string tag in video.Tags)
            {
                traversal.CreateTagVertexAndEdgeToVideo(tag);
            }

            await _session.ExecuteGraphAsync(traversal);
        }
 public void TraversalBatch_Should_Use_GraphOptions()
 {
     TraversalUnitTest.WithMock((ISession session, ref IGraphStatement statement) =>
     {
         var g       = DseGraph.Traversal(session);
         var options = new GraphOptions().SetName("name1")
                       .SetReadConsistencyLevel(ConsistencyLevel.LocalQuorum)
                       .SetWriteConsistencyLevel(ConsistencyLevel.Quorum)
                       .SetReadTimeoutMillis(123499);
         var batch = DseGraph.Batch(options);
         batch
         .Add(g.AddV("person").Property("name", "Matias").Property("age", 12))
         .Add(g.AddV("person").Property("name", "Olivia").Property("age", 8));
         session.ExecuteGraph(batch);
         Assert.NotNull(statement);
         Assert.IsInstanceOf <FluentGraphStatement>(statement);
         var query = (IEnumerable <Bytecode>)((FluentGraphStatement)statement).QueryBytecode;
         Assert.AreEqual("bytecode-json", statement.GraphLanguage);
         TraversalUnitTest.CompareGraphOptionsOnStatement(options, statement);
         var traversals = query.ToList();
         Assert.AreEqual(2, traversals.Count);
         Assert.AreEqual(3, traversals.ElementAt(0).StepInstructions.Count);
         Assert.AreEqual(3, traversals.ElementAt(1).StepInstructions.Count);
     });
 }
        /// <summary>
        /// Gets the personalized video suggestions for a specific user.
        /// Based on DSL tutorial provided here, we changed the recommendation from pre-aggration
        /// tables to real-time graph recommendation.
        /// https://academy.datastax.com/content/gremlin-dsls-net-dse-graph
        /// </summary>
        public override async Task <GetSuggestedForUserResponse> GetSuggestedForUser(GetSuggestedForUserRequest request,
                                                                                     ServerCallContext context)
        {
            Logger.Information("Request suggested video(s) for user {user}", request.UserId.Value);
            GraphTraversalSource g = DseGraph.Traversal(_session);

            // DSL Baby !
            var traversal = g.RecommendVideos(request.UserId.ToGuid().ToString(), 5, 4, 1000, 5);

            GraphResultSet result = await _session.ExecuteGraphAsync(traversal);

            // Building GRPC response from list of results vertices (hopefully 'numberOfVideosExpected')
            var grpcResponse = new GetSuggestedForUserResponse
            {
                UserId      = request.UserId,
                PagingState = ""
            };

            foreach (IVertex vertex in result.To <IVertex>())
            {
                Logger.Information("Result " + vertex);
                grpcResponse.Videos.Add(MapVertexToVideoPreview(vertex));
            }
            return(grpcResponse);
        }
Example #8
0
 public async Task RateVideoInGraph(String videoId, String userId, int rating)
 {
     var traversal = DseGraph.Traversal(_session).V(); //Added V() here so it doesn't fail
     //TODO Not sure what is expected here
     // .UserRateVideo(userId, videoId, rating);
     await _session.ExecuteGraphAsync(traversal);
 }
Example #9
0
        public void Should_Execute_Trasversal_With_Enums()
        {
            var g     = DseGraph.Traversal(Session);
            var enums = g.With("allow-filtering").V().HasLabel("person").Has("age").Order().By("age", Order.Decr).ToList();

            Assert.AreEqual(4, enums.Count);
        }
Example #10
0
        public void Should_Handle_Result_With_Mixed_Object()
        {
            var g      = DseGraph.Traversal(Session);
            var result = g.With("allow-filtering").V().HasLabel("software")
                         .As("a", "b", "c")
                         .Select <object>("a", "b", "c")
                         .By("name")
                         .By("lang")
                         .By(__.In("created").Values <string>("name").Fold()).ToList();

            Assert.AreEqual(2, result.Count);
            var lop    = result.FirstOrDefault(software => software["a"].Equals("lop"));
            var ripple = result.FirstOrDefault(software => software["a"].Equals("ripple"));

            Assert.IsNotNull(lop);
            Assert.IsNotNull(ripple);
            Assert.AreEqual("java", lop["b"]);
            Assert.AreEqual("java", ripple["b"]);
            var lopDevs    = (lop["c"] as IEnumerable).Cast <string>();
            var rippleDevs = (ripple["c"] as IEnumerable).Cast <string>();

            Assert.AreEqual(3, lopDevs.Count());
            Assert.AreEqual(1, rippleDevs.Count());
            Assert.True(lopDevs.Contains("marko"));
            Assert.True(lopDevs.Contains("josh"));
            Assert.True(lopDevs.Contains("peter"));
        }
Example #11
0
        public void Should_Make_OLAP_Query_Using_Traversal()
        {
            var g      = DseGraph.Traversal(Session, new GraphOptions().SetSourceAnalytics());
            var result = g.V().HasLabel("person")
                         .PeerPressure().By("cluster").ToList();

            Assert.AreEqual(4, result.Count);
        }
Example #12
0
        public void Should_Be_Able_To_Create_Vertex_With_MetaProperties()
        {
            var g = DseGraph.Traversal(Session);

            g.AddV("meta_v")
            .Property("meta_prop", "White Walkers", "sub_prop", "Dragonglass", "sub_prop2", "Valyrian steel")
            .Next();
            StatementClassicIntegrationTest.VerifyMetaProperties(Session, g, "White Walkers", "Dragonglass", "Valyrian steel");
            g.V().HasLabel("meta_v").Drop().Next();
        }
Example #13
0
        public void Should_Override_Cluster_Options()
        {
            var g = DseGraph.Traversal(Session, new GraphOptions().SetName("non_existing_graph"));

            // Its supposed to be InvalidQueryException but DSE 6.0 introduced a bug: DSP-15783
            if (TestClusterManager.DseVersion < new Version(6, 0))
            {
                Assert.Throws <InvalidQueryException>(() => g.V().HasLabel("person").ToList());
            }
        }
 public void Should_Set_The_Graph_Language()
 {
     TraversalUnitTest.WithMock((ISession session, ref IGraphStatement statement) =>
     {
         var g = DseGraph.Traversal(session);
         g.V().ToList();
         Assert.NotNull(statement);
         Assert.AreEqual("bytecode-json", statement.GraphLanguage);
     });
 }
Example #15
0
        public void Should_Parse_Property_Values()
        {
            var g     = DseGraph.Traversal(Session);
            var names = g.V().HasLabel("person").Values <string>("name").ToList();

            Assert.GreaterOrEqual(names.Count, 4);
            CollectionAssert.Contains(names, "peter");
            CollectionAssert.Contains(names, "josh");
            CollectionAssert.Contains(names, "vadas");
            CollectionAssert.Contains(names, "marko");
        }
Example #16
0
        public void Should_Parse_Vertices()
        {
            var g        = DseGraph.Traversal(Session);
            var vertices = g.V().HasLabel("person").ToList();

            Assert.GreaterOrEqual(vertices.Count, 4);
            foreach (var vertex in vertices)
            {
                Assert.AreEqual("person", vertex.Label);
            }
        }
Example #17
0
        public async Task Should_Execute_A_Traversal()
        {
            var g  = DseGraph.Traversal(Session);
            var rs = await Session.ExecuteGraphAsync(g.V().HasLabel("person").Has("name", P.Eq("marko")));

            var rsSync = Session.ExecuteGraph(g.V().HasLabel("person").Has("name", P.Eq("marko")));

            // The result should be DSE driver vertices
            StatementCoreIntegrationTest.VerifyGraphResultSet(Session, rs);
            StatementCoreIntegrationTest.VerifyGraphResultSet(Session, rsSync);
        }
Example #18
0
        public void Should_Use_Vertex_Id_As_Parameter()
        {
            var g        = DseGraph.Traversal(Session);
            var vertices = g.V().HasLabel("person").Has("name", "marko").ToList();

            Assert.AreEqual(1, vertices.Count);
            var markoVertex           = vertices.First();
            var markoVertexByIdResult = g.V(markoVertex.Id).ToList();

            Assert.AreEqual(1, markoVertexByIdResult.Count);
            Assert.AreEqual("person", markoVertexByIdResult.First().Label);
        }
 public void Extension_Async_Method_Should_Build_Traversal_And_Execute()
 {
     TraversalUnitTest.WithMock((ISession session, ref IGraphStatement statement) =>
     {
         var g = DseGraph.Traversal(session);
         session.ExecuteGraphAsync(g.V());
         Assert.NotNull(statement);
         Assert.IsInstanceOf <FluentGraphStatement>(statement);
         var s = (FluentGraphStatement)statement;
         Assert.IsInstanceOf <Bytecode>(s.QueryBytecode);
     });
 }
        public async Task Should_Create_A_Query_From_A_Traversal()
        {
            var g         = DseGraph.Traversal(Session);
            var statement = DseGraph.StatementFromTraversal(g.V().HasLabel("person").Has("name", P.Eq("marko")));
            var rs        = await Session.ExecuteGraphAsync(statement);

            var rsSync = Session.ExecuteGraph(statement);

            // The result should be DSE driver vertices
            StatementClassicIntegrationTest.VerifyGraphResultSet(rs);
            StatementClassicIntegrationTest.VerifyGraphResultSet(rsSync);
        }
        public void Should_Be_Able_To_Create_Vertex_With_MetaProperties()
        {
            var g    = DseGraph.Traversal(Session);
            var stmt = DseGraph.StatementFromTraversal(g.AddV("meta_v")
                                                       .Property("meta_prop", "What can kill a dragon", "sub_prop", "Qyburn's scorpion", "sub_prop2", "Another dragon"));

            Session.ExecuteGraph(stmt);
            StatementClassicIntegrationTest.VerifyMetaProperties(Session, g, "What can kill a dragon", "Qyburn's scorpion", "Another dragon");
            var dropstmt = DseGraph.StatementFromTraversal(g.V().HasLabel("meta_v").Drop());

            Session.ExecuteGraph(dropstmt);
        }
Example #22
0
        public void Should_Use_Edge_Id_As_Parameter()
        {
            var g     = DseGraph.Traversal(Session);
            var edges = g.With("allow-filtering").E().HasLabel("knows").Has("weight", 0.5f).ToList();

            Assert.AreEqual(1, edges.Count);
            var knowEdge           = edges.First();
            var knowEdgeByIdResult = g.E(knowEdge.Id).ToList();

            Assert.AreEqual(1, knowEdgeByIdResult.Count);
            Assert.AreEqual("knows", knowEdgeByIdResult.First().Label);
        }
Example #23
0
        public void Should_Be_Able_To_Create_Vertex_With_Multicardinality_Property()
        {
            var g = DseGraph.Traversal(Session);

            g.AddV("multi_v")
            .Property("multi_prop", "Hold")
            .Property("multi_prop", "the")
            .Property("multi_prop", "door")
            .Next();
            StatementClassicIntegrationTest.VerifyMultiCardinalityProperty(Session, g, new [] { "Hold", "the", "door" });
            g.V().HasLabel("multi_v").Drop().Next();
        }
Example #24
0
        public void Should_Be_Able_To_Create_Vertex_With_Multicardinality_Property()
        {
            var g          = DseGraph.Traversal(Session);
            var direwolves = new[] { "Ghost", "Nymeria", "Shaggydog", "Grey Wind", "Lady" };
            var stmt       = DseGraph.StatementFromTraversal(
                g.AddV("multi_v")
                .Property("pk", Guid.NewGuid())
                .Property("multi_prop", new object[] { direwolves }));

            Session.ExecuteGraph(stmt);
            StatementCoreIntegrationTest.VerifyMultiCardinalityProperty(Session, g, direwolves);
            g.V().HasLabel("multi_v").Drop().Next();
        }
Example #25
0
        public void Should_Be_Able_To_Create_And_Drop_Vertex()
        {
            const string name = "john snow";
            var          g    = DseGraph.Traversal(Session);

            g.AddV("character").Property("name", name).Property("age", 20).Next();
            var knowsNothing = g.V().HasLabel("character").Has("name", name).ToList();

            Assert.AreEqual(1, knowsNothing.Count);
            g.With("force-vertex-deletion").V().HasLabel("character").Has("name", P.Eq(name)).Drop().ToList();
            knowsNothing = g.V().HasLabel("character").Has("name", P.Eq(name)).ToList();
            Assert.AreEqual(0, knowsNothing.Count);
        }
Example #26
0
        /// <summary>
        /// Create new node in the Graph for
        /// </summary>
        public async Task AddUserVertexToGraph(UserCreated user)
        {
            String userId = user.UserId.ToGuid().ToString();

            Logger.Information("Inserting to graph Vertext user {user} ", userId);

            // Create Traversal
            var traversal = DseGraph.Traversal(_session)
                            .CreateUserVertex(userId, user.Email);

            // Add Vertex 'user' with expected properties asynchronously
            await _session.ExecuteGraphAsync(traversal);
        }
Example #27
0
        public void Should_Handle_Types(string type)
        {
            var g = DseGraph.Traversal(Session);

            foreach (var value in TraversalClassicIntegrationTest.PropertyItems.Where(i => i.Item1 == type).Select(i => i.Item2))
            {
                var vertexLabel  = $"vertex{type}";
                var propertyName = $"prop{type}";
                g.AddV(vertexLabel).Property(propertyName, value).Next();
                var result = g.V().HasLabel(vertexLabel).Has(propertyName, value)
                             .Values <object>(propertyName).Next();
                Assert.AreEqual(value, result);
            }
        }
Example #28
0
        public void Should_Parse_Property_Map()
        {
            var g           = DseGraph.Traversal(Session);
            var propertyMap = g.V().HasLabel("person").PropertyMap <object>("age").ToList();

            Assert.Greater(propertyMap.Count, 0);
            var firstAge   = (IEnumerable)propertyMap.First()["age"];
            var enumerator = firstAge.GetEnumerator();

            enumerator.MoveNext();
            var firstKv = (VertexProperty)enumerator.Current;

            Assert.IsInstanceOf <int>(firstKv.Value);
        }
Example #29
0
        public void Should_Be_Able_To_Create_Vertex_With_TupleProperties()
        {
            var g     = DseGraph.Traversal(Session);
            var tuple = new Tuple <string, int>("test 123", 123);
            var guid  = Guid.NewGuid();

            g.AddV("tuple_v")
            .Property("pk", guid)
            .Property("tuple_prop", tuple)
            .Next();

            StatementCoreIntegrationTest.VerifyProperty(Session, g, "tuple_v", guid, "tuple_prop", tuple);
            g.V().HasLabel("tuple_v").Drop().Next();
        }
Example #30
0
        public void Should_Use_Vertex_Id_As_Parameter()
        {
            var g          = DseGraph.Traversal(Session);
            var statement  = DseGraph.StatementFromTraversal(g.V().HasLabel("person").Has("name", "marko"));
            var rs         = Session.ExecuteGraph(statement);
            var markoArray = rs.ToArray();

            Assert.AreEqual(1, markoArray.Length);
            var markoVertex   = markoArray[0].ToVertex();
            var getStmt       = DseGraph.StatementFromTraversal(g.V(markoVertex.Id));
            var getvertexById = Session.ExecuteGraph(getStmt);
            var getByIdArray  = getvertexById.ToArray();

            Assert.AreEqual(1, getByIdArray.Length);
            Assert.AreEqual("person", getByIdArray[0].ToVertex().Label);
        }