public CqlRowSet GetRows() { Statement query = new SimpleStatement("SELECT * FROM simplex.songs;"); IAsyncResult asyncResult = Session.BeginExecute(query, null, null); asyncResult.AsyncWaitHandle.WaitOne(); CqlRowSet result = Session.EndExecute(asyncResult); return result; }
/// <summary> /// Gets the list of temperature stored for a provided weather station and day. /// </summary> public RowSet GetTemperatureRecords(string weatherStationId, DateTime day) { var selectCql = "SELECT * FROM temperature_by_day WHERE weatherstation_id = ? AND date = ?"; //Create a statement var selectStatement = new SimpleStatement(selectCql); //Add the parameters selectStatement.Bind(weatherStationId, DateTime.Now.ToString("yyyyMMdd")); //Execute the select statement return Session.Execute(selectStatement); }
/// <summary> /// Add a temperature information for a given weather station /// </summary> public void AddTemperature(string weatherStationId, decimal value) { var insertCql = @" INSERT INTO temperature_by_day (weatherstation_id, date, event_time, temperature) VALUES (?, ?, ?, ?)"; //Create an insert statement var insertStatement = new SimpleStatement(insertCql); //Bind the parameters to the statement insertStatement.Bind(weatherStationId, DateTime.Now.ToString("yyyyMMdd"), DateTime.Now, value); //You can set other options of the statement execution, for example the consistency level. insertStatement.SetConsistencyLevel(ConsistencyLevel.Quorum); //Execute the insert Session.Execute(insertStatement); }
/// <summary> /// Add a temperature information for a given weather station asynchronously /// </summary> public Task AddTemperatureAsync(string weatherStationId, decimal value) { //It is basically the same code as the AddTemperature //Except it returns a Task that already started but didn't finished //The row would not be in Cassandra yet when this method finishes executing. var insertCql = @" INSERT INTO temperature_by_day (weatherstation_id, date, event_time, temperature) VALUES (?, ?, ?, ?)"; //Create an insert statement var insertStatement = new SimpleStatement(insertCql); //Bind the parameters to the statement insertStatement.Bind(weatherStationId, DateTime.Now.ToString("yyyyMMdd"), DateTime.Now, value); //You can set other options of the statement execution, for example the consistency level. insertStatement.SetConsistencyLevel(ConsistencyLevel.Quorum); //Execute the insert return Session.ExecuteAsync(insertStatement); }
public static void Run() { // this sample requires buffering Cluster cluster = Cluster.Builder().AddContactPoint("127.0.0.1").Build(); using (var session = cluster.Connect()) { const string cqlKeyspaces = "SELECT * from system.schema_keyspaces"; var query = new SimpleStatement(cqlKeyspaces).EnableTracing(); var allTasks = new List<Task>(); for (int i = 0; i < 100; ++i) { var futRes = Task<RowSet>.Factory.FromAsync(session.BeginExecute, session.EndExecute, cqlKeyspaces, ConsistencyLevel.Default, null) .ContinueWith(t => DisplayKeyspace(t.Result)); allTasks.Add(futRes); } Task.WaitAll(allTasks.ToArray()); } cluster.Shutdown(); }
public IAsyncResult GetRowsAsynchronously(String query) { Statement statement = new SimpleStatement(query); return Session.BeginExecute(statement, null, null); }
private void DoFetchTrace() { try { var sessionStatement = new SimpleStatement(string.Format(SelectSessionsFormat, _traceId)) .SetConsistencyLevel(ConsistencyLevel.One); var sessionRow = _session.Execute(sessionStatement).First(); _requestType = sessionRow.GetValue<string>("request"); if (!sessionRow.IsNull("duration")) { _duration = sessionRow.GetValue<int>("duration"); } _coordinator = sessionRow.GetValue<IPAddress>("coordinator"); if (!sessionRow.IsNull("parameters")) { _parameters = sessionRow.GetValue<IDictionary<string, string>>("parameters"); } _startedAt = sessionRow.GetValue<DateTimeOffset>("started_at").ToFileTime(); if (sessionRow.GetColumn("client") != null) { ClientAddress = sessionRow.GetValue<IPAddress>("client"); } _events = new List<Event>(); var eventStatement = new SimpleStatement(string.Format(SelectEventsFormat, _traceId)) .SetConsistencyLevel(ConsistencyLevel.One); var eventRows = _session.Execute(eventStatement); foreach (var row in eventRows) { _events.Add(new Event(row.GetValue<string>("activity"), new DateTimeOffset( Utils.GetTimestampFromGuid(row.GetValue<Guid>("event_id")) + (new DateTimeOffset(1582, 10, 15, 0, 0, 0, TimeSpan.Zero)).Ticks, TimeSpan.Zero), row.GetValue<IPAddress>("source"), row.IsNull("source_elapsed") ? 0 : row.GetValue<int>("source_elapsed"), row.GetValue<string>("thread"))); } } catch (Exception ex) { _logger.Error("Unexpected exception while fetching query trace", ex); throw new TraceRetrievalException("Unexpected exception while fetching query trace", ex); } }
public long GetLastStopEvent(Guid videoId, String userName) { long videoTimestamp = 0; // Get a list of the last 5 events to find the last stop Statement statement = new SimpleStatement( "SELECT event, video_timestamp FROM videodb.video_event " + "WHERE videoId = " + videoId + " AND username = "******"LIMIT 5;"); RowSet rows = session.Execute(statement); foreach (Row row in rows.GetRows()) { // Find the first stop event, store it and stop the loop if ( row.GetValue<String>("event").ToLower().Equals("stop") ) { videoTimestamp = row.GetValue<long>("video_timestamp"); break; } } return videoTimestamp; }
/// <summary> /// Gets multiple user profiles by their Ids. /// </summary> public async Task<IEnumerable<UserProfile>> GetUserProfiles(ISet<Guid> userIds) { if (userIds == null || userIds.Count == 0) return Enumerable.Empty<UserProfile>(); // Since we're essentially doing a multi-get here, limit the number userIds (i.e. partition keys) to 20 in an attempt // to enforce some performance sanity. Anything larger and we might want to consider a different data model that doesn't // involve doing a multi-get if (userIds.Count > 20) throw new ArgumentOutOfRangeException("userIds", "Cannot do multi-get on more than 20 user id keys."); // As an example, we'll do the multi-get at the CQL level using an IN() clause (i.e. let Cassandra handle it). For an example of // doing it at the driver level, see the VideoReadModel.GetVideoPreviews method // Build a parameterized CQL statement with an IN clause var parameterList = string.Join(", ", Enumerable.Repeat("?", userIds.Count)); var statement = new SimpleStatement(string.Format("SELECT userid, firstname, lastname, email FROM users WHERE userid IN ({0})", parameterList)); statement.Bind(userIds.Cast<object>().ToArray()); // Execute and map to UserProfile object RowSet resultRows = await _session.ExecuteAsync(statement).ConfigureAwait(false); return resultRows.Select(MapRowToUserProfile).ToList(); }