public async Task <Movie> FindByTitle(string title)
        {
            var session = _driver.AsyncSession(WithDatabase);

            try
            {
                return(await session.ReadTransactionAsync(async transaction =>
                {
                    var cursor = await transaction.RunAsync(@"
                        MATCH (movie:Movie {title:$title})
                        OPTIONAL MATCH (movie)<-[r]-(person:Person)
                        RETURN movie.title as title,
                               COLLECT({
                                   name:person.name,
                                   job: HEAD(SPLIT(TOLOWER(TYPE(r)),'_')),
                                   role: REDUCE(acc = '', role IN r.roles | acc + CASE WHEN acc='' THEN '' ELSE ', ' END + role)}
                               ) AS cast",
                                                            new { title }
                                                            );

                    return await cursor.SingleAsync(record => new Movie(
                                                        record["title"].As <string>(),
                                                        MapCast(record["cast"].As <List <IDictionary <string, object> > >())
                                                        ));
                }));
            }
            finally
            {
                await session.CloseAsync();
            }
        }
Beispiel #2
0
        public async Task AcceptFriend(string currentUser, string userToAccept)
        {
            var cql = $@"
                MATCH 
                    (u1:{nameof(User)} {{{User.UuidField}: ${nameof(userToAccept)}}}) 
                    -[f:FRIENDS_WITH]- 
                    (u2:{nameof(User)} {{{User.UuidField}: ${nameof(currentUser)}}}) 
                SET 
                    f.IsAccepted = true";

            var session = _db.AsyncSession();

            try
            {
                await session.RunAsync(cql, new { currentUser, userToAccept });
            }
            catch
            {
                throw;
            }
            finally
            {
                await session.CloseAsync();
            }
        }
        public async Task RunAsync()
        {
            var currentIteration = Interlocked.Increment(ref _counter);
            var query            = queries[currentIteration % queries.Length];
            var accessMode       = accessModes[currentIteration % accessModes.Length];

            var session = _driver.AsyncSession(accessMode);

            try
            {
                var result = await session.RunAsync(query);

                if (currentIteration % 1000 == 0)
                {
                    _output.WriteLine(_metrics.ConnectionPoolMetrics.ToContentString());
                }

                await result.SummaryAsync();
            }
            catch (Exception e)
            {
                _output.WriteLine(
                    $"[{DateTime.Now:HH:mm:ss.ffffff}] " +
                    $"Iteration {currentIteration} failed to run query {query} due to {e.Message}");
                _output.WriteLine(e.StackTrace);
            }
            finally
            {
                await session.CloseAsync();
            }
        }
        public async Task CommitAsync()
        {
            IAsyncSession session;

            if (!string.IsNullOrEmpty(_database))
            {
                session = _driver.AsyncSession((cf) => cf.WithDatabase(_database));
            }
            else
            {
                session = _driver.AsyncSession();
            }

            try
            {
                var sessionVars = new Dictionary <string, object>();
                sessionVars.Add("TimeStamp", DateTime.Now);
                sessionVars.Add("By", System.Environment.UserName);
                var sessionNode = new Node("Session");
                Push(sessionNode, sessionVars);

                await pushQueue(schemaStack, session, sessionNode.Id);
                await pushQueue(pushStack, session, sessionNode.Id);
                await pushQueue(relateStack, session, sessionNode.Id);
            }
            finally
            {
                await session.CloseAsync();
            }
        }
Beispiel #5
0
        public async Task ExecuteNonQuery(string cypherQuery, object queryParams = null)
        {
            IAsyncSession session = _driver.AsyncSession(o => o.WithDatabase(this._database));

            if (queryParams == null)
            {
                queryParams = new {};
            }

            try
            {
                _logger.LogDebug($"Executing query: {cypherQuery}");

                IResultCursor cursor = await session.RunAsync(cypherQuery, queryParams);

                IResultSummary result = await cursor.ConsumeAsync();

                _logger.LogTrace($"Query executed successfully.");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error executing query. {ex.Message}");
                throw;
            }
            finally
            {
                await session.CloseAsync();
            }
        }
Beispiel #6
0
        public async Task <IEnumerable <Movie> > GetMovie(string title)
        {
            const string query = "MATCH (m:Movie) WHERE m.title = $title RETURN m";

            var session = _driver.AsyncSession();
            var results = await session.ReadTransactionAsync(async tx =>
            {
                var cursor  = await tx.RunAsync(query, new { title });
                var fetched = await cursor.FetchAsync();

                var output = new List <Movie>();
                while (fetched)
                {
                    var node = cursor.Current["m"].As <INode>();

                    var movie = new Movie
                    {
                        Title    = node.Properties["title"].As <string>(),
                        Tagline  = node.Properties["tagline"].As <string>(),
                        Released = node.Properties["released"].As <int>()
                    };

                    output.Add(movie);
                    fetched = await cursor.FetchAsync();
                }

                return(output);
            });

            await session.CloseAsync();

            return(results);
        }
Beispiel #7
0
        private void CypherExecuter(string cypher)
        {
            var session = _driver.AsyncSession();

            session.WriteTransactionAsync(a =>
            {
                return(a.RunAsync(cypher));
            }).Wait();
        }
Beispiel #8
0
        public async Task <ActionResult <IEnumerable <Movie> > > List()
        {
            // Note the use of 'Movie.Labels' here
            var query = @$ "MATCH (m:{Movie.Labels}) 
                           RETURN m";

            // We use a 'Session' to perform our queries
            var session = _driver.AsyncSession();

            // We're pulling a Movie from the query
            var movies = await session.RunReadTransactionForObjects <Movie>(query, null, "m");

            return(movies.ToList());
        }
    // ############
    // RETURN SINGLE NODE
    // ############

    async void SingleNodeLabelsTest()
    {
        // Each IDriver instance maintains a pool of connections inside, as a result, it is recommended to only use one driver per application.
        // The driver is thread-safe, while the session or the transaction is not thread-safe.
        IDriver       driver  = GraphDatabase.Driver("neo4j://localhost:7687", AuthTokens.Basic("neo4j", "123456"));
        IAsyncSession session = driver.AsyncSession(o => o.WithDatabase("neo4j"));

        try
        {
            IResultCursor cursor = await session.RunAsync("MATCH (a {name: 'Joel Silver'}) RETURN a");

            // The recommended way to access these result records is to make use of methods provided by ResultCursorExtensions such as SingleAsync,
            // ToListAsync, and ForEachAsync.
            INode person = await cursor.SingleAsync(record => record["a"].As <INode>());

            await cursor.ConsumeAsync();

            foreach (var item in person.Labels)
            {
                Debug.Log(item);
            }
        }
        finally
        {
            await session.CloseAsync();
        }
        await driver.CloseAsync();
    }
        private async Task <Bookmark> CreateNodesAsync(int batchCount, int batchSize, int batchBuffer, IDriver driver)
        {
            var timer = Stopwatch.StartNew();

            var session = driver.AsyncSession();

            try
            {
                for (var batchIndex = 0; batchIndex < batchCount; batchIndex++)
                {
                    await session.WriteTransactionAsync(txc => Task.WhenAll(
                                                            Enumerable.Range(1, batchSize)
                                                            .Select(index => (batchIndex *batchSize) + index)
                                                            .Batch(batchBuffer)
                                                            .Select(indices =>
                                                                    txc.RunAsync(CreateBatchNodesQuery(indices))
                                                                    .ContinueWith(t => t.Result.ConsumeAsync()).Unwrap()).ToArray()));
                }
            }
            finally
            {
                await session.CloseAsync();
            }

            _output.WriteLine("Creating nodes with Async API took: {0}ms", timer.ElapsedMilliseconds);

            return(session.LastBookmark);
        }
Beispiel #11
0
        public async Task <List <INode> > ConnectDb(string query)
        {
            Driver = CreateDriverWithBasicAuth("bolt://localhost:7687", "neo4j", "1234");
            List <INode>  res     = new List <INode>();
            IAsyncSession session = Driver.AsyncSession(o => o.WithDatabase("neo4j"));

            try
            {
                res = await session.ReadTransactionAsync(async tx =>
                {
                    var results = new List <INode>();
                    var reader  = await tx.RunAsync(query);

                    while (await reader.FetchAsync())
                    {
                        results.Add(reader.Current[0].As <INode>());
                    }

                    return(results);
                });
            }

            finally
            {
                await session.CloseAsync();
            }
            return(res);
        }
Beispiel #12
0
        private static void InitializeNeo4jConnection(string username, string password, string uri, string database)
        {
            IDriver driver = GraphDatabase.Driver(uri,
                                                  AuthTokens.Basic(username, password));

            _session = driver.AsyncSession(o => o.WithDatabase(database));
        }
    // ############
    // RETURN TWO LIST<STRING>
    // ############

    async void MultipleReturnsTest()
    {
        // Each IDriver instance maintains a pool of connections inside, as a result, it is recommended to only use one driver per application.
        // The driver is thread-safe, while the session or the transaction is not thread-safe.
        IDriver       driver  = GraphDatabase.Driver("neo4j://localhost:7687", AuthTokens.Basic("neo4j", "123456"));
        IAsyncSession session = driver.AsyncSession(o => o.WithDatabase("neo4j"));

        try
        {
            IResultCursor cursor = await session.RunAsync("MATCH (a:Person) RETURN a.name, a.born");

            // A record is accessible once it is received by the client. It is not needed for the whole result set to be received before it can be visited.
            // Each record can only be visited (a.k.a.consumed) once!
            // The recommended way to access these result records is to make use of methods provided by ResultCursorExtensions such as SingleAsync,
            // ToListAsync, and ForEachAsync.
            List <DataHolder> people = await cursor.ToListAsync(record => new DataHolder(record["a.name"].As <string>(), record["a.born"].As <string>()));

            await cursor.ConsumeAsync();

            foreach (var item in people)
            {
                Debug.Log(item.ToString());
            }
        }
        finally
        {
            await session.CloseAsync();
        }
        await driver.CloseAsync();
    }
Beispiel #14
0
        public static async Task UpdateUniqueIdAsync(this IDriver driver, string scope, long value)
        {
            var session = driver.AsyncSession(builder => builder.WithDefaultAccessMode(AccessMode.Write));
            await session.UpdateUniqueIdAsync(scope, value).ConfigureAwait(false);

            await session.CloseAsync().ConfigureAwait(false);
        }
    // ############
    // RETURN SINGLE LIST<STRING>
    // ############

    async void SingleReturnTest()
    {
        // Each IDriver instance maintains a pool of connections inside, as a result, it is recommended to only use one driver per application.
        // The driver is thread-safe, while the session or the transaction is not thread-safe.
        IDriver       driver  = GraphDatabase.Driver("neo4j://localhost:7687", AuthTokens.Basic("neo4j", "123456"));
        IAsyncSession session = driver.AsyncSession(o => o.WithDatabase("neo4j"));

        try
        {
            IResultCursor cursor = await session.RunAsync("MATCH (a:Person) RETURN a.name as name");

            // The recommended way to access these result records is to make use of methods provided by ResultCursorExtensions such as SingleAsync,
            // ToListAsync, and ForEachAsync.
            List <string> people = await cursor.ToListAsync(record => record["name"].As <string>());

            await cursor.ConsumeAsync();

            Debug.Log(people.Count + " single returns");
        }
        finally
        {
            await session.CloseAsync();
        }
        await driver.CloseAsync();
    }
Beispiel #16
0
        public async Task CreateIndices()
        {
            string[] queries =
            {
                "CREATE CONSTRAINT ON (u:User) ASSERT u.name IS UNIQUE",
                "CREATE CONSTRAINT ON (u:User) ASSERT u.id IS UNIQUE",
                "CREATE CONSTRAINT ON (s:Suggestion) ASSERT s.id IS UNIQUE",
                "CREATE INDEX ON :Suggestion(isActive)",
                "CREATE CONSTRAINT ON (c:Category) ASSERT c.name IS UNIQUE",
                "CREATE CONSTRAINT ON (l:Like) ASSERT l.name IS UNIQUE",
                "CREATE CONSTRAINT ON (r:Report) ASSERT r.id IS UNIQUE",
                "CREATE(c:Category{name: \"Academico\"})",
                "CREATE(c:Category{name: \"Deporte\"})",
                "CREATE(c:Category{name: \"Juegos\"})",
                "CREATE(c:Category{name: \"Cultural\"})",
                "CREATE(c:Category{name: \"Comidas\"})",
                "CREATE(c:Category{name: \"Fiesta\"})",
                "CREATE(c:Category{name: \"Otros\"})"
            };
            var session = driver.AsyncSession(o => o.WithDatabase("neo4j"));

            try
            {
                foreach (var query in queries)
                {
                    await session.RunAsync(query);
                }
            }
            finally
            {
                await session.CloseAsync();
            }
        }
Beispiel #17
0
        private async Task mnu_ClickAsync(object sender, RoutedEventArgs e)
        {
            IDriver       driver  = GraphDatabase.Driver("neo4j://localhost:7687", AuthTokens.Basic("neo4j", "neo4j"));
            IAsyncSession session = driver.AsyncSession(o => o.WithDatabase("neo4j"));

            try
            {
                IResultCursor cursor = await session.RunAsync("CREATE (n) RETURN n");

                await cursor.ConsumeAsync();
            }
            finally
            {
                await session.CloseAsync();
            }

            await driver.CloseAsync();

            ///https://stackoverflow.com/questions/59581789/why-does-idriver-not-contain-a-definition-for-session-when-using-neo4j-in-c
            ///test

            /*[TestClass]
             * {
             *  [TestMethod]
             *  {
             *      System.Console.WriteLine();
             *  }
             * }*/
        }
Beispiel #18
0
        public static async Task <List <IRecord> > Query(string query)
        {
            if (driver is null)
            {
                throw new ArgumentNullException("Connect to DB before you query");
            }
            else
            {
                IAsyncSession session = driver.AsyncSession();

                try
                {
                    return(await session.WriteTransactionAsync(tx => RunCypherWithResults(tx, query)));
                }
                catch (Exception err)
                {
                    // Error
                    throw err;
                }
                finally
                {
                    Console.WriteLine("Closed connection");
                    await session.CloseAsync();
                }
            }
        }
        private static async Task <int> CountNodeInTx(IDriver driver, int id, Bookmark bookmark = null)
        {
            var session = driver.AsyncSession(o => o.WithBookmarks(bookmark));

            try
            {
                var tx = await session.BeginTransactionAsync();

                try
                {
                    var cursor = await tx.RunAsync("MATCH (a:Person {id: $id}) RETURN a", new { id });

                    var records = await cursor.ToListAsync();

                    await tx.CommitAsync();

                    return(records.Count);
                }
                catch
                {
                    await tx.RollbackAsync();

                    throw;
                }
            }
            finally
            {
                await session.CloseAsync();
            }
        }
Beispiel #20
0
        private async Task VerifyDatabaseNameOnSummaryTxFunc(string name, string expected, Bookmark bookmark = null)
        {
            var session = _driver.AsyncSession(o =>
            {
                if (!string.IsNullOrEmpty(name))
                {
                    o.WithDatabase(name);
                }

                o.WithBookmarks(bookmark ?? Bookmark.Empty);
            });

            try
            {
                var summary = await session.ReadTransactionAsync(async txc =>
                {
                    var cursor = await txc.RunAsync("RETURN 1");
                    return(await cursor.ConsumeAsync());
                });

                summary.Database.Should().NotBeNull();
                summary.Database.Name.Should().Be(expected);
            }
            finally
            {
                await session.CloseAsync();
            }
        }
Beispiel #21
0
        public static async Task InitialiseUniqueIdsAsync(this IDriver driver)
        {
            var session = driver.AsyncSession(builder => builder.WithDefaultAccessMode(AccessMode.Write));
            await session.InitialiseUniqueIdsAsync().ConfigureAwait(false);

            await session.CloseAsync().ConfigureAwait(false);
        }
Beispiel #22
0
        }                                   // stores driver

        /// <summary>
        /// Connect to database and run a query string
        /// </summary>
        /// <param name="query">Query to run</param>
        /// <returns>Result from database</returns>
        public async Task <List <INode> > ConnectDb(string query)
        {
            // TODO get auth params from some config file
            Driver = CreateDriverWithBasicAuth("bolt://localhost:7687", "neo4j", "1234"); // connect to database
            List <INode>  res     = new List <INode>();                                   // create list to store results in
            IAsyncSession session = Driver.AsyncSession(o => o.WithDatabase("neo4j"));    // start session

            // try to start transaction with query proved. Return results
            try {
                res = await session.ReadTransactionAsync(async tx => {
                    var results = new List <INode>();
                    var reader  = await tx.RunAsync(query);

                    while (await reader.FetchAsync())
                    {
                        results.Add(reader.Current[0].As <INode>());
                    }

                    return(results); // return results
                });
            } finally {
                await session.CloseAsync(); // close session
            }

            return(res); // return results
        }
        public static IAsyncSession GetSession()
        {
            IDriver driver = GraphDatabase.Driver("bolt://localhost:7687", AuthTokens.Basic("neo4j", "admin"));

            session = driver.AsyncSession();

            return(session);
        }
Beispiel #24
0
        /// <summary>
        /// Obtain a session which is designed to be used synchronously, which is built on top of the default
        /// asynchronous <see cref="IAsyncSession"/> with the customized <see cref="SessionConfig"/>.
        /// </summary>
        /// <param name="driver">driver instance</param>
        /// <param name="action">An action, provided with a <see cref="SessionConfigBuilder"/> instance, that should populate
        /// the provided instance with desired session configurations <see cref="SessionConfig"/>.</param>
        /// <returns>A simple session instance</returns>
        public static ISession Session(this IDriver driver, Action <SessionConfigBuilder> action)
        {
            var asyncDriver = driver.CastOrThrow <IInternalDriver>();

            return(new InternalSession(driver.AsyncSession(action).CastOrThrow <IInternalAsyncSession>(),
                                       new RetryLogic(asyncDriver.Config.MaxTransactionRetryTime, asyncDriver.Config.Logger),
                                       new BlockingExecutor()));
        }
Beispiel #25
0
        public override async Task Process()
        {
            IDriver driver = ((NewDriver)ObjManager.GetObject(data.driverId)).Driver;

            Session = driver.AsyncSession(SessionConfig);

            await Task.CompletedTask;
        }
Beispiel #26
0
        public Neo4j(string connectionString, string username, string password)
        {
            var uri = new Uri($"bolt://{connectionString}/");

            driver = GraphDatabase.Driver(uri, AuthTokens.Basic(username, password));

            session = driver.AsyncSession();
        }
        /// <summary>
        /// Obtain a session which is designed to be used synchronously, which is built on top of the default
        /// asynchronous <see cref="IAsyncSession"/> with the specified access mode and bookmarks.
        /// </summary>
        /// <param name="driver">driver instance</param>
        /// <param name="mode">access mode for the returned session</param>
        /// <param name="bookmarks">bookmarks to establish causal chaining</param>
        /// <returns>A reactive session instance</returns>
        public static ISession Session(this IDriver driver, AccessMode mode, IEnumerable <string> bookmarks)
        {
            var reactiveDriver = driver.CastOrThrow <IInternalDriver>();

            return(new InternalSession(driver.AsyncSession(mode, bookmarks).CastOrThrow <IInternalAsyncSession>(),
                                       new RetryLogic(reactiveDriver.Config.MaxTransactionRetryTime, reactiveDriver.Config.DriverLogger),
                                       new BlockingExecutor()));
        }
Beispiel #28
0
        public async Task <object> FindFlight(string OriginCode, string DestinationCode, DateTime departureDate, string sortType)
        {
            var    session   = _driver.AsyncSession(WithDatabase);
            string startDate = departureDate.Date.ToString("yyyy-MM-dd");

            //string sortBy = "DEPARTURE_DATETIME";
            string sortBy = sortType ?? "COST";

            string query = @"
CALL{
    match (origin:AIRPORT_DATE_DESTINATION)-[:ORIGIN_OF]->(flight:FLIGHT)
    where origin.airport = ($origin)
    and origin.destination = ($destination)
    and origin.date = date(($startDt))
    return [flight] as ROUTE, flight.cost as COST, flight.originTime as DEPARTURE_DATETIME
    union all
    match(origin: AIRPORT_DATE) -[:HAS_FLIGHT_TO]->(:AIRPORT_DATE_DESTINATION) -[:ORIGIN_OF]->(flight1: FLIGHT) -[:LANDS_AT]->(:AIRPORT_DATE) -[:HAS_FLIGHT_TO]->(:AIRPORT_DATE_DESTINATION) -[:ORIGIN_OF]->(flight2: FLIGHT) -[:LANDS_AT]->(destinationDate: AIRPORT_DATE)
    where origin.airport = ($origin)
    and destinationDate.airport = ($destination)
    and origin.date = date(($startDt))
    and(flight1.destinationTime.epochMillis + (3600 * 1000)) <= flight2.originTime.epochMillis
    and destinationDate.date = date(flight2.destinationTime)
    and(flight1.destinationTime.epochMillis + (6 * 3600 * 1000)) >= flight2.originTime.epochMillis
    return [flight1, flight2] as ROUTE, flight1.cost + flight2.cost as COST, flight1.originTime as DEPARTURE_DATETIME
    union all
    match(origin: AIRPORT_DATE) -[:HAS_FLIGHT_TO]->(:AIRPORT_DATE_DESTINATION) -[:ORIGIN_OF]->(flight1: FLIGHT) -[:LANDS_AT]->(airportDate1: AIRPORT_DATE) -[:HAS_FLIGHT_TO]->(:AIRPORT_DATE_DESTINATION) -[:ORIGIN_OF]->(flight2: FLIGHT) -[:LANDS_AT]->(airportDate2: AIRPORT_DATE) -[:HAS_FLIGHT_TO]->(:AIRPORT_DATE_DESTINATION) -[:ORIGIN_OF]->(flight3: FLIGHT) -[:LANDS_AT]->(destinationDate: AIRPORT_DATE)
    where origin.airport = ($origin)
    and destinationDate.airport = ($destination)
    and origin.date = date(($startDt))
    and origin.airport<> airportDate2.airport
    and airportDate1.airport<> destinationDate.airport
    and(flight1.destinationTime.epochMillis + (3600 * 1000)) <= flight2.originTime.epochMillis
    and(flight2.destinationTime.epochMillis + (3600 * 1000)) <= flight3.originTime.epochMillis
    and destinationDate.date = date(flight3.destinationTime)
    and(flight1.destinationTime.epochMillis + (6 * 3600 * 1000)) >= flight2.originTime.epochMillis
    and(flight2.destinationTime.epochMillis + (6 * 3600 * 1000)) >= flight3.originTime.epochMillis
    return [flight1, flight2, flight3] as ROUTE, flight1.cost + flight2.cost + flight3.cost as COST, flight1.originTime as DEPARTURE_DATETIME
    }
    RETURN ROUTE, COST, DEPARTURE_DATETIME
    ORDER BY  " + sortBy;

            try
            {
                var result = await session.ReadTransactionAsync(async tx =>
                {
                    var cursor = await tx.RunAsync(query, new { origin = OriginCode, destination = DestinationCode, startDt = startDate, orderBy = sortBy });
                    var res    = await cursor.ToListAsync();
                    return(res);
                });

                return(result);
            }
            finally
            {
                await session.CloseAsync();
            }
        }
Beispiel #29
0
        public async Task CreateIndices()
        {
            string[] queries =
            {
                "CREATE INDEX ON :Movie(title)",
                "CREATE INDEX ON :Movie(id)",
                "CREATE INDEX ON :Person(id)",
                "CREATE INDEX ON :Person(name)",
                "CREATE INDEX ON :Genre(name)"
            };

            var session = driver.AsyncSession();

            foreach (var query in queries)
            {
                await session.RunAsync(query);
            }
        }
Beispiel #30
0
        public static async Task <long> NextUniqueIdAsync(this IDriver driver, string scope)
        {
            var session      = driver.AsyncSession(builder => builder.WithDefaultAccessMode(AccessMode.Write));
            var nextUniqueId = await session.NextUniqueIdAsync(scope).ConfigureAwait(false);

            await session.CloseAsync().ConfigureAwait(false);

            return(nextUniqueId);
        }