/// <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);
        }
Beispiel #2
0
 private static GraphTraversal <Vertex, Vertex> GenerateQuery(GraphTraversalSource g, Person person)
 {
     return(g.AddV("Person")
            .Property("id", person.Id)
            .Property("name", person.Name)
            .Property("born", person.BornInYear));
 }
Beispiel #3
0
        public GremlinDB(string endpoint, int port)
        {
            _gremlinConnector = new GremlinConnector(endpoint, port);
            _graph            = _gremlinConnector.GetGraph();

            _nodes = new Dictionary <string, Vertex>();
        }
Beispiel #4
0
        private List <string> GetItems(string id, string labelId, string labelItems, bool getInEdges = false)
        {
            graph = Traversal().WithRemote(new DriverRemoteConnection(gremlinClient));

            IList <VertexProperty> vertices = new List <VertexProperty>(0);

            if (getInEdges)
            {
                vertices = graph.V().Has(labelId, PropertyKey, id).In(EdgeLabel).HasLabel(labelItems)
                           .Properties <VertexProperty>(PropertyKey).ToList();
            }
            else
            {
                vertices = graph.V().Has(labelId, PropertyKey, id).Out(EdgeLabel).HasLabel(labelItems)
                           .Properties <VertexProperty>(PropertyKey).ToList();
            }

            var items = new List <string>(0);

            foreach (var v in vertices)
            {
                items.Add(v.Value);
            }

            return(items);
        }
Beispiel #5
0
 /// <summary>
 /// Create User Vertex
 /// </summary>
 public static GraphTraversal <Vertex, Vertex> CreateUserVertex(
     this GraphTraversalSource g, String userId, String userEmail)
 {
     return(g.V().AddV(VertexUser)
            .Property(PropertyUserId, userId)
            .Property(PropertyEmail, userEmail)
            .Property(PropertyAddedDate, DateTimeOffset.UtcNow));
 }
 public static GraphTraversal <Vertex, Vertex> GetAddVertexWithLabelQuery(
     GraphTraversalSource g,
     string label)
 {
     return(g
            .AddV(
                label));
 }
Beispiel #7
0
 private static GraphTraversal <Vertex, Vertex> GenerateQuery(GraphTraversalSource g, Movie movie)
 {
     return(g.AddV("Movie")
            .Property("id", movie.Id)
            .Property("title", movie.Title)
            .Property("released", movie.Released)
            .Property("language", movie.Language));
 }
Beispiel #8
0
        private static GraphTraversal <Vertex, Vertex> VerticesWithNames(this GraphTraversalSource source,
                                                                         string vertexLabel, params object[] names)
        {
            var t = source.V().HasLabel(vertexLabel);

            return(names.Length > 0
                ? t.Has("name", Within(names))
                : t);
        }
 public static GraphTraversal <Vertex, Vertex> GetGetVerticesByLabelQuery(
     GraphTraversalSource g,
     string label)
 {
     return(g
            .V()
            .HasLabel(
                label));
 }
Beispiel #10
0
 /// <summary>
 ///     Spawns a <see cref="GraphTraversalSource" /> that is bound to a remote session which enables a transaction.
 /// </summary>
 /// <returns>A <see cref="GraphTraversalSource" /> bound to a remote session.</returns>
 /// <exception cref="InvalidOperationException">Thrown if this transaction is already bound to a session.</exception>
 public GraphTraversalSource Begin()
 {
     if (_g.IsSessionBound)
     {
         throw new InvalidOperationException("Transaction already started on this object");
     }
     _g = new GraphTraversalSource(_g.TraversalStrategies, _g.Bytecode, _sessionBasedConnection);
     return(_g);
 }
 public static GraphTraversal <Vertex, Vertex> GetDropVertexByIdQuery(
     GraphTraversalSource g,
     object id)
 {
     return(g
            .V(
                id)
            .Drop());
 }
 public static GraphTraversal <Edge, Edge> GetDropEdgeByIdQuery(
     GraphTraversalSource g,
     object id)
 {
     return(g
            .E(
                id)
            .Drop());
 }
 internal static ITraversal GetTraversal(string traversalText, GraphTraversalSource g,
                                         IDictionary <string, object> contextParameterValues)
 {
     if (!FixedTranslations.TryGetValue(traversalText, out var traversalBuilder))
     {
         var tokens = ParseTraversal(traversalText);
         return(GetTraversalFromTokens(tokens, g, contextParameterValues, traversalText));
     }
     return(traversalBuilder(g));
 }
Beispiel #14
0
        public void ChooseModernGraph(string graphName)
        {
            if (graphName == "empty")
            {
                ScenarioData.CleanEmptyData();
            }
            var data = ScenarioData.GetByGraphName(graphName);

            _graphName = graphName;
            _g         = Traversal().WithRemote(data.Connection);
        }
        public RelationshipController(IConfiguration config)
        {
            var server = new GremlinServer(
                config.GetValue <string>("Gremlin:Hostname"),
                config.GetValue <int>("Gremlin:Port"),
                config.GetValue <bool>("Gremlin:EnableSsl"));

            var client = new GremlinClient(server);

            _g = Traversal().WithRemote(new DriverRemoteConnection(client));
        }
Beispiel #16
0
        public static GraphTraversal <Vertex, Vertex> Persons(this GraphTraversalSource g, params string[] personNames)
        {
            GraphTraversal <Vertex, Vertex> t = g.V().HasLabel("person");

            if (personNames.Length > 0)
            {
                t = t.Has("name", P.Within(personNames));
            }

            return(t);
        }
 public static GraphTraversal <Vertex, Vertex> GetGetOutNeighboursByEdgeLabelOfVertexByIdQuery(
     GraphTraversalSource g,
     object id,
     string label)
 {
     return(g
            .V(
                id)
            .Out(
                label));
 }
 public static GraphTraversal <Vertex, Edge> GetGetOutEdgesByLabelOfVertexByIdQuery(
     GraphTraversalSource g,
     object id,
     string label)
 {
     return(g
            .V(
                id)
            .OutE(
                label));
 }
Beispiel #19
0
        public static GraphTraversal <Vertex, Vertex> Persons(this GraphTraversalSource source,
                                                              params string[] personNames)
        {
            var traversal = source.V().HasLabel("person");

            if (personNames.Length > 0)
            {
                traversal = traversal.Has("name", Within(personNames));
            }

            return(traversal);
        }
Beispiel #20
0
 private static IDictionary <string, Vertex> GetVertices(GraphTraversalSource g)
 {
     try
     {
         return(g.V().Group <string, object>().By("name").By(__.Tail <Vertex>()).Next()
                .ToDictionary(kv => kv.Key, kv => (Vertex)kv.Value));
     }
     catch (ResponseException)
     {
         // Property name might not exist
         return(EmptyVertices);
     }
 }
        private void gV__Fix()
        {
            var client = new Mock <IGremlinClient>();

            var g = new GraphTraversalSource(new DriverRemoteConnection(client.Object));

            var entQuery = g.V()
                           .BothE().Where(__.InV().HasId("1234"));

            var query = entQuery.ToGremlinQuery();

            query.Should().Be("g.V().bothE().where(__.inV().hasId(\"1234\"))");
        }
 public static GraphTraversal <Vertex, Vertex> GetAddOrUpdatePropertyToOrOfVertexByIdQuery(
     GraphTraversalSource g,
     object id,
     string name,
     object value)
 {
     return(g
            .V(
                id)
            .Property(
                name,
                value));
 }
Beispiel #23
0
 private static IDictionary <string, Vertex> GetVertices(GraphTraversalSource g)
 {
     // Property name might not exist and C# doesn't support "null" keys in Dictionary
     if (g.V().Count().Next() == g.V().Has("name").Count().Next())
     {
         return(g.V().Group <string, object>().By("name").By(__.Tail <Vertex>()).Next()
                .ToDictionary(kv => kv.Key, kv => (Vertex)kv.Value));
     }
     else
     {
         return(EmptyVertices);
     }
 }
Beispiel #24
0
        public void TranslateTraversal(string traversalText)
        {
            if (_g == null)
            {
                throw new InvalidOperationException("g should be a traversal source");
            }

            if (ScenarioData.CurrentFeature.Tags.Select(t => t.Name).ToList().Contains("@GraphComputerOnly"))
            {
                _g = _g.WithComputer();
            }

            _traversal =
                Gremlin.UseTraversal(ScenarioData.CurrentScenario.Name, _g, _parameters);
        }
Beispiel #25
0
        public static void VerifyMultiCardinalityProperty(ISession session, GraphTraversalSource g, string[] values)
        {
            var stmt   = DseGraph.StatementFromTraversal(g.V().HasLabel("multi_v"));
            var vertex = session.ExecuteGraph(stmt);
            var result = vertex.FirstOrDefault();

            Assert.IsNotNull(result);
            var multiPropertyVertex = result.ToVertex();

            Assert.AreEqual("multi_v", multiPropertyVertex.Label);
            TestHelper.FillVertexProperties(session, multiPropertyVertex);
            var properties = multiPropertyVertex.GetProperty("multi_prop").Value.To <IList <string> >();

            Assert.AreEqual(values.Length, properties.Count);
            CollectionAssert.AreEqual(values, properties);
        }
Beispiel #26
0
 private static IDictionary <string, Edge> GetEdges(GraphTraversalSource g)
 {
     try
     {
         return(g.E().Group <string, object>()
                .By(__.Project <Edge>("o", "l", "i")
                    .By(__.OutV().Values <string>("name")).By(__.Label()).By(__.InV().Values <string>("name")))
                .By(__.Tail <object>())
                .Next()
                .ToDictionary(kv => GetEdgeKey(kv.Key), kv => (Edge)kv.Value));
     }
     catch (ResponseException)
     {
         // Property name might not exist
         return(EmptyEdges);
     }
 }
Beispiel #27
0
        private void AddNewLike(string userId, string itemId, string label)
        {
            // execute remotely
            graph = Traversal().WithRemote(new DriverRemoteConnection(gremlinClient));

            // Add vertices if do not exist
            var    u    = graph.V().Has(UserLabel, PropertyKey, userId);
            var    i    = graph.V().Has(label, PropertyKey, itemId);
            Vertex user = u.HasNext() ? u.Next() : graph.AddV(UserLabel).Property(PropertyKey, userId).Next();
            Vertex item = i.HasNext() ? i.Next() : graph.AddV(label).Property(PropertyKey, itemId).Next();

            // Add the edge if does not exist
            if (graph.V(user.Id).OutE("likes").ToList().Where(e => e.InV.Id.Equals(item.Id)).Count() == 0)
            {
                graph.V(user).AddE(EdgeLabel).To(item).Iterate();
            }
        }
Beispiel #28
0
        public static void VerifyCollectionProperties(ISession session, GraphTraversalSource g, string meta, string sub1, string sub2)
        {
            var stmt    = DseGraph.StatementFromTraversal(g.V().HasLabel("collection_v"));
            var walkers = session.ExecuteGraph(stmt);
            var result  = walkers.FirstOrDefault();

            Assert.IsNotNull(result);
            var nightKing = result.ToVertex();

            Assert.AreEqual("collection_v", nightKing.Label);
            TestHelper.FillVertexProperties(session, nightKing);
            var metaProp = nightKing.GetProperty("pk").Value.To <string>();

            Assert.AreEqual(meta, metaProp);
            CollectionAssert.AreEqual(new [] { sub1 }, nightKing.GetProperty("sub_prop").Value.To <IEnumerable <string> >());
            CollectionAssert.AreEqual(new [] { sub2 }, nightKing.GetProperty("sub_prop2").Value.To <IEnumerable <string> >());
        }
Beispiel #29
0
        private static IDictionary <string, Edge> GetEdges(GraphTraversalSource g)
        {
            try
            {
                IFunction lambda = Lambda.Groovy(
                    "it.outVertex().value('name') + '-' + it.label() + '->' + it.inVertex().value('name')", 1);

                return(g.E().Group <string, Edge>()
                       .By(lambda)
                       .By(__.Tail <object>())
                       .Next());
            }
            catch (ResponseException)
            {
                // Property name might not exist
                return(EmptyEdges);
            }
        }
Beispiel #30
0
        /// <summary>
        /// Gets users by their identifier
        /// </summary>
        public static GraphTraversal <Vertex, Vertex> Users(this GraphTraversalSource g, string userId, params string[] additionalUserIds)
        {
            var userIds = new List <string>();

            userIds.Add(userId);
            userIds.AddRange(additionalUserIds);
            GraphTraversal <Vertex, Vertex> t = g.V().HasLabel(VertexUser);

            if (userIds.Count == 1)
            {
                t = t.Has(KeyUserId, userIds[0]);
            }
            else if (userIds.Count > 1)
            {
                t = t.Has(KeyUserId, P.Within(userIds.ToArray()));
            }
            return(t);
        }