public async Task <List <IRecord> > queryRead(string query) { List <IRecord> _records = null; try { _records = await session.ReadTransactionAsync(async tx => { // Send cypher query to the database var _reader = await tx.RunAsync(query); List <IRecord> _records = await _reader.ToListAsync(); return(_records); }); } catch (Exception e) { Console.WriteLine("{0} Exception caught.", e); } finally { // asynchronously close session await session.CloseAsync(); } return(_records); }
public async Task UpsertNodes <T>(IEnumerable <T> nodes, IEnumerable <string> indices = null) { IAsyncSession session = AsyncSession(); string objectName = typeof(T).Name.ToLowerInvariant(); string key = null; try { if (!indices.IsNullOrEmpty()) { key = indices.Select(_ => $"{{{_}:{objectName}.{_}}}").FirstOrDefault(); foreach (var query in indices.Select(_ => $"INDEX ON :{objectName}({_})")) { ICypherBuilder cypherBuilder = _cypherBuilderFactory.NewCypherBuilder().AddCreate(query); await session.RunAsync(cypherBuilder.ToString()); } } string cypher = UpsertNodesCypher <T>(key); await session.WriteTransactionAsync(tx => RunCypher(tx, cypher, new Dictionary <string, object>() { { "nodes", nodes.ToDictionaries() } })); } finally { await session.CloseAsync(); } }
public async Task <T> ExecuteScalar <T>(string cypherQuery, object queryParams = null) { T result = default(T); IAsyncSession session = _driver.AsyncSession(o => o.WithDatabase(this._database)); _logger.LogDebug($"Executing query: {cypherQuery}"); if (queryParams == null) { queryParams = new {}; } try { IResultCursor resultCursor = await session.RunAsync(cypherQuery, queryParams); IRecord record = await resultCursor.SingleAsync(); result = record[0].As <T>(); _logger.LogDebug("Query executed successfully"); } catch (Exception ex) { _logger.LogError(ex, $"Error executing query. {ex.Message}"); throw; } finally { await session.CloseAsync(); } return(result); }
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(); } }
} // 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 }
// Get all records as a List public async Task <List <T> > FetchRecords <T>( Func <IRecord, T> recordProcessor, string cypherQuery, object queryParams = null) { List <T> result = null; IAsyncSession session = _driver.AsyncSession(o => o.WithDatabase(this._database)); _logger.LogDebug($"Executing query: {cypherQuery}"); if (queryParams == null) { queryParams = new {}; } try { IResultCursor resultCursor = await session.RunAsync(cypherQuery, queryParams); result = await resultCursor.ToListAsync(record => recordProcessor(record)); _logger.LogDebug("Query executed successfully"); } catch (Exception ex) { _logger.LogError(ex, $"Error executing query. {ex.Message}"); throw; } finally { await session.CloseAsync(); } return(result); }
// ############ // 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(); }
// ############ // 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(); }
// ############ // 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(); }
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(); * } * }*/ }
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(); } } }
public async Task <List <T> > Run <T>(IQuery <T>[] queries, string databaseName, bool defaultDatabase) { IAsyncSession session = GetAsyncSession(databaseName, defaultDatabase); try { LogRun("queries", databaseName, defaultDatabase); var resultToReturn = new List <T>(); foreach (var query in queries) { await session.ReadTransactionAsync(async tx => { IResultCursor result = await tx.RunAsync(query.Query); resultToReturn.AddRange(await result.ToListAsync(query.ProcessRecord)); }); } return(resultToReturn); } finally { await session.CloseAsync(); } }
public async Task InserirNoAsync(string nome, string anilha, string sexo, string nomePopular, string nascimento) { session = _driver.AsyncSession(o => o.WithDatabase("neo4j"));//Nome da database está nas propriedades como padrão string query = String.Empty; if (sexo != string.Empty) { query += ",Sexo:" + "$sexo"; } if (nomePopular != string.Empty) { query += ",NomePopular:" + "$nomePopular"; } if (nascimento != string.Empty) { query += ",Nascimento:" + "$nascimento"; } try { if (anilha == string.Empty) { cursor = await session.RunAsync("CREATE (p:Passaro{nome:$nome" + query + "})", new { nome, sexo, nomePopular, nascimento });//MERGE Impede cadastro de mesmo nome } else { cursor = await session.RunAsync("CREATE (p:Passaro{nome:$nome, anilha:$anilha" + query + "})", new { nome, anilha, sexo, nomePopular, nascimento }); } await cursor.ConsumeAsync(); } finally { await session.CloseAsync(); } }
public async void CreateActor() { // arrange IAsyncSession session = _neo4JResource.GetAsyncSession(); try { // act var actor = new Actor("Keanu Reaves", 56); IDictionary <string, object> parameters = new Neo4jParameters().WithEntity("newActor", actor); IResultCursor cursor = await session.RunAsync( @"CREATE (actor:Actor $newActor) RETURN actor", parameters); Actor createdActor = await cursor.MapSingleAsync <Actor>(); await cursor.ConsumeAsync(); // assert createdActor.MatchSnapshot(); } finally { await session.CloseAsync(); } }
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); }
public async void Dispose() { await _session.RunAsync("MATCH (u:TestUser) DETACH DELETE u"); await _session.RunAsync("MATCH (r:TestRole) DETACH DELETE r"); await _session.CloseAsync(); _driver.Dispose(); }
public void Dispose() { session.CloseAsync(); if (driver == null) { return; } driver.CloseAsync(); driver.Dispose(); }
public override async Task Process() { try { IAsyncSession session = ((NewSession)ObjManager.GetObject(data.sessionId)).Session; await session.CloseAsync(); } catch (Exception ex) { throw new Exception($"Failed to Process NewDriver protocol object, failed with - {ex.Message}"); } }
public async Task ProcurarFamilia(string filho, string aniFilho, bool comAnilha) //Testar essa função { session = _driver.AsyncSession(o => o.WithDatabase("neo4j")); //Nome da database está nas propriedades como padrão try { string optMatch; string matchf; if (comAnilha) { matchf = "MATCH (f:Passaro{nome:$filho, anilha:$aniFilho})" + "OPTIONAL MATCH (f)<-[:PAI]-(p1:Passaro)" + "OPTIONAL MATCH (m1:Passaro)-[:MAE]->(f)"; } else { matchf = "MATCH (f:Passaro{nome:$filho})" + "WHERE ID(f) = toInteger($aniFilho)" + "OPTIONAL MATCH (f)<-[:PAI]-(p1:Passaro)" + "OPTIONAL MATCH (m1:Passaro)-[:MAE]->(f)"; } optMatch = "optional match(m2:Passaro)-[:MAE]->(p1) < -[:PAI] - (p2: Passaro)" + "optional match(m3:Passaro)-[:MAE]->(m1) < -[:PAI] - (p3: Passaro)" + "optional match(m4:Passaro)-[:MAE]->(p2) < -[:PAI] - (p4: Passaro)" + "optional match(m5:Passaro)-[:MAE]->(m2) < -[:PAI] - (p5: Passaro)" + "optional match(m6:Passaro)-[:MAE]->(p3) < -[:PAI] - (p6: Passaro)" + "optional match(m7:Passaro)-[:MAE]->(m3) < -[:PAI] - (p7: Passaro)" + "OPTIONAL MATCH(m8:Passaro)-[:MAE]->(p4) < -[:PAI] - (p8: Passaro)" + "OPTIONAL MATCH(m9:Passaro)-[:MAE]->(m4) < -[:PAI] - (p9: Passaro)" + "OPTIONAL MATCH(m10:Passaro)-[:MAE]->(p5) < -[:PAI] - (p10: Passaro)" + "OPTIONAL MATCH(m11:Passaro)-[:MAE]->(m5) < -[:PAI] - (p11: Passaro)" + "OPTIONAL MATCH(m12:Passaro)-[:MAE]->(p6) < -[:PAI] - (p12: Passaro)" + "OPTIONAL MATCH(m13:Passaro)-[:MAE]->(m6) < -[:PAI] - (p13: Passaro)" + "OPTIONAL MATCH(m14:Passaro)-[:MAE]->(p7) < -[:PAI] - (p14: Passaro)" + "OPTIONAL MATCH(m15:Passaro)-[:MAE]->(m7) < -[:PAI] - (p15: Passaro)" + "return [f.nome, p1.nome, m1.nome, p2.nome, m2.nome, p3.nome, m3.nome, " + "p4.nome, m4.nome, p5.nome, m5.nome, p6.nome, m6.nome, p7.nome, m7.nome," + "p8.nome, m8.nome, p9.nome, m9.nome, p10.nome, m10.nome, p11.nome, m11.nome," + "p12.nome, m12.nome, p13.nome, m13.nome, p14.nome, m14.nome, p15.nome, m15.nome] AS familia"; cursor = await session.RunAsync(matchf + optMatch, new { filho, aniFilho }); records = await cursor.ToListAsync(); familia = new List <string>(); //familia.Add(aniFilho); //familia.Add(filho); familia = Records(); resultado = await cursor.ConsumeAsync(); } finally { await session.CloseAsync(); } }
public async Task CriarUniqueAsync() { session = _driver.AsyncSession(o => o.WithDatabase("neo4j"));//Nome da database está nas propriedades como padrão try { cursor = await session.RunAsync("CREATE CONSTRAINT anilhaC ON (p:Passaro) ASSERT p.anilha IS UNIQUE"); await cursor.ConsumeAsync(); } finally { await session.CloseAsync(); } }
//todo: create package for DFC.ServiceTaxonomy.Neo4j?? public async Task <object> ExecuteCypherQueryInNeo4JAsync(string query, IDictionary <string, object> statementParameters) { IAsyncSession session = _neo4JDriver.AsyncSession(); try { return(await session.ReadTransactionAsync(async tx => { _resultCursor = await tx.RunAsync(query, statementParameters); return await GetListOfRecordsAsync(); })); } finally { await session.CloseAsync(); } }
// Get records as a stream of buffered List public async IAsyncEnumerable <List <T> > FetchRecordsAsStream <T>( Func <IRecord, T> recordProcessor, string cypherQuery, object queryParams = null, long bufferSize = 100) { long recordsProcessed = 0; List <T> resultBuffer = new List <T>(); IAsyncSession session = _driver.AsyncSession(o => o.WithDatabase(this._database)); _logger.LogDebug($"Executing query: {cypherQuery}"); if (queryParams == null) { queryParams = new {}; } try { IResultCursor resultCursor = await session.RunAsync(cypherQuery, queryParams); _logger.LogDebug("Reading cursor"); while (await resultCursor.FetchAsync()) { recordsProcessed += 1; resultBuffer.Add(recordProcessor(resultCursor.Current)); if (resultBuffer.Count >= bufferSize) { _logger.LogDebug($"Records processed: {recordsProcessed} ..."); yield return(resultBuffer); resultBuffer.Clear(); } } _logger.LogDebug($"* Total records processed: {recordsProcessed} *"); yield return(resultBuffer); } finally { await session.CloseAsync(); } }
private async Task ExecuteCypher(string cypher, Dictionary <string, object> parameters = null) { IAsyncSession session = AsyncSession(); try { await session.WriteTransactionAsync(tx => RunCypher(tx, cypher, parameters)); } catch (Neo4jException e) { throw new GraphRepositoryException(e.Message, e); } finally { await session.CloseAsync(); } }
public async Task DefinirPaisAsync(string filho, string aniFilho, string pai, string aniPai, string mae, string aniMae, bool[] comAnilha) { session = _driver.AsyncSession(o => o.WithDatabase("neo4j"));//Nome da database está nas propriedades como padrão try { if (!comAnilha.All(anilhas => anilhas == true)) //Expressão Lambda (entrada) => (corpo/condição) { string matchf = " MATCH(f: Passaro { nome: $filho, anilha:$aniFilho})"; string matchp = " MATCH(p: Passaro { nome: $pai, anilha:$aniPai})"; string matchm = " MATCH(m:Passaro { nome: $mae, anilha:$aniMae})"; string where = " WHERE NOT (:Passaro)-[:PAI]->(f)<-[:MAE]-(:Passaro)"; string merge = " MERGE (p)-[:PAI]->(f)<-[:MAE]-(m)"; if (!comAnilha[0]) { matchf = "MATCH (f:Passaro {nome: $filho})"; where += " and ID(f) = toInteger($aniFilho)"; } if (!comAnilha[1]) { matchp = "MATCH (p:Passaro {nome: $pai})"; where += " and ID(p) = toInteger($aniPai)"; } if (!comAnilha[2]) { matchm = "MATCH (m:Passaro {nome: $mae})"; where += " and ID(m) = toInteger($aniMae)"; } cursor = await session.RunAsync(matchf + matchp + matchm + where + merge, new { filho, aniFilho, pai, aniPai, mae, aniMae }); } else { cursor = await session.RunAsync("MATCH (f:Passaro {nome: $filho, anilha:$aniFilho})" + "MATCH (p:Passaro {nome: $pai, anilha:$aniPai})" + "MATCH (m:Passaro {nome: $mae, anilha:$aniMae})" + "WHERE NOT (:Passaro)-[:PAI]->(f)<-[:MAE]-(:Passaro)" + "MERGE (p)-[:PAI]->(f)<-[:MAE]-(m)", new { filho, aniFilho, pai, aniPai, mae, aniMae }); } resultado = await cursor.ConsumeAsync(); } finally { await session.CloseAsync(); } }
public async Task <IEnumerable <Entity <TNode> > > GetAllEntities <TNode>(GraphInterfaces.IField field, IEnumerable <string> relationships) where TNode : class { IAsyncSession session = AsyncSession(); try { string cypher = GetAllCypher <TNode>(field, relationships); List <IRecord> records = await session.ReadTransactionAsync(tx => RunCypherWithResults(tx, cypher)); return(records?.Select(_ => new Entity <TNode> { Node = _[0].As <INode>().Properties.AsJson().AsPoco <TNode>(), Relationships = Transform(_[1].As <IPath>()) })); } finally { await session.CloseAsync(); } }
public async Task <ActionResult> Get() { IResultCursor cursor; var types = new List <string>(); IAsyncSession session = _driver.AsyncSession(); try { cursor = await session.RunAsync(@"MATCH (t:Type) RETURN t.name AS name"); types = await cursor.ToListAsync(record => record["name"].As <string>()); } finally { await session.CloseAsync(); } return(Ok(types)); }
public async Task <List <IRecord> > ProcurarPais(string nome, string anilha, bool comAnilha) { session = _driver.AsyncSession(o => o.WithDatabase("neo4j"));//Nome da database está nas propriedades como padrão try { if (!comAnilha) { if (anilha != String.Empty) { cursor = await session.RunAsync("MATCH (f:Passaro{nome:$nome})" + "WHERE ID(f) = toInteger($anilha) " + "OPTIONAL MATCH (m1:Passaro)-[:MAE]->(f)" + "OPTIONAL MATCH (f)<-[:PAI]-(p1:Passaro)" + "RETURN f,[f.nome] AS Nomes,[m1.nome] AS Maes,[p1.nome] AS Pais, [ID(f)] AS Ids", new { nome, anilha }); } else { cursor = await session.RunAsync("MATCH (f:Passaro{nome:$nome})" + "OPTIONAL MATCH (m1:Passaro)-[:MAE]->(f)" + "OPTIONAL MATCH (f)<-[:PAI]-(p1:Passaro)" + "RETURN f,[f.nome] AS Nomes,[m1.nome] AS Maes,[p1.nome] AS Pais, [ID(f)] AS Ids", new { nome }); } } else { cursor = await session.RunAsync("MATCH (f:Passaro {nome: $nome, anilha:$anilha})" + "OPTIONAL MATCH (m1:Passaro)-[:MAE]->(f)" + "OPTIONAL MATCH (f)<-[:PAI]-(p1:Passaro)" + "RETURN f,[f.nome] AS Nomes,[m1.nome] AS Maes,[p1.nome] AS Pais, [ID(f)] AS Ids", new { nome, anilha }); } var lista = await cursor.ToListAsync(); resultado = await cursor.ConsumeAsync(); return(lista); } finally { await session.CloseAsync(); } }
//TODO: Mudar cor das labels na frente do cartão pelo usuário //TODO: Menu para atualizar campos de passarinho //TODO: Pontos que precisam estão marcados com indicadores de bandeira branca //TODO: Clicar em pesquisar sem sair nomeFilhoF faz com que listnomesF == null //TODO: Criar menu para cadastrar em árvore //TODO: Atualizar buttonPesquisa para buttonImpressão public async Task <List <IRecord> > ProcurarFilhos(string nome) { session = _driver.AsyncSession(o => o.WithDatabase("neo4j"));//Nome da database está nas propriedades como padrão try { cursor = await session.RunAsync("MATCH (p:Passaro {nome: $nome})" + "OPTIONAL MATCH (p)-[:PAI|MAE]->(f:Passaro)" + "RETURN [p.nome] AS Nomes, [ID(p)] AS Ids,[f.nome] AS Filhos, " + "[p.anilha] AS Anilhas, [p.Sexo] AS Sexos, [p.NomePopular] AS NomesPopulares, " + "[p.Nascimento] AS Nascimentos ", new { nome }); var lista = await cursor.ToListAsync(); resultado = await cursor.ConsumeAsync(); return(lista); } finally { await session.CloseAsync(); } }
public async Task Run(ICommand[] commands, string databaseName, bool defaultDatabase) { IAsyncSession session = GetAsyncSession(databaseName, defaultDatabase); try { // transaction functions auto-retry //todo: configure retry? timeout? etc. LogRun("command(s)", databaseName, defaultDatabase); await session.WriteTransactionAsync(async tx => { foreach (ICommand command in commands) { IResultCursor result = await tx.RunAsync(command.Query); var records = await result.ToListAsync(r => r); var resultSummary = await result.ConsumeAsync(); _logger.LogDebug("Query result available after: {ResultAvailableAfter}, consumed after: {ResultConsumedAfter}", resultSummary.ResultAvailableAfter, resultSummary.ResultConsumedAfter); if (resultSummary.Notifications.Any()) { _logger.LogWarning($"Query had notifications{Environment.NewLine}:{string.Join(Environment.NewLine, resultSummary.Notifications)}"); } command.ValidateResults(records, resultSummary); } }); } finally { await session.CloseAsync(); } }
protected virtual async Task TestFixtureTearDown() { await Session.CloseAsync(); Driver.Dispose(); }