您的位置:首页 > 其它

【原创】StreamInsight查询系列(三)——基本查询操作之过滤

2011-08-21 09:29 483 查看
上篇博文介绍了如何在LINQPad中输出StreamInsight查询结果。这篇文章将主要介绍StreamInsight基础查询操作中的过滤部分。

测试数据准备

为了方便测试查询,我们首先准备一个静态的测试数据源:

var weatherData = new[]
{
new { Timestamp = new DateTime(2010, 1, 1, 0, 00, 00), Temperature = -9.0, StationCode = 71395, WindSpeed = 4},
new { Timestamp = new DateTime(2010, 1, 1, 0, 30, 00), Temperature = -4.5, StationCode = 71801, WindSpeed = 41},
new { Timestamp = new DateTime(2010, 1, 1, 1, 00, 00), Temperature = -8.8, StationCode = 71395, WindSpeed = 6},
new { Timestamp = new DateTime(2010, 1, 1, 1, 30, 00), Temperature = -4.4, StationCode = 71801, WindSpeed = 39},
new { Timestamp = new DateTime(2010, 1, 1, 2, 00, 00), Temperature = -9.7, StationCode = 71395, WindSpeed = 9},
new { Timestamp = new DateTime(2010, 1, 1, 2, 30, 00), Temperature = -4.6, StationCode = 71801, WindSpeed = 59},
new { Timestamp = new DateTime(2010, 1, 1, 3, 00, 00), Temperature = -9.6, StationCode = 71395, WindSpeed = 9},
};

weatherData代表了一系列的天气信息(时间戳、温度、气象站编码以及风速)。

接下去将weatherData转变为点类型复杂事件流:

var weatherStream = weatherData.ToPointStream(Application,
t => PointEvent.CreateInsert(t.Timestamp, t),
AdvanceTimeSettings.IncreasingStartTime);

// 统计事件总数
weatherStream.ToPointEnumerable().Count().Dump("Total number of events");

细心的读者会发现事件总数是15,而不是weatherData的元素个数7。这是因为在使用AdvanceTimeSettings.IncreasingStartTime标志创建weatherStream后,StreamInsight引擎会为每一个事件后紧跟一个相同时间戳的CTI事件,因此事件个数为7*2=14。那么为什么总数变成了15呢?那是因为AdvanceTimeSettings.IncreasingStartTime默认指定了AdvanceToInfinityOnShutdown为true,即确定在关闭查询时应插入具有正无穷大的时间戳的最终CTI,用来刷新所有剩余事件。因此加上这个正无穷大的CTI事件,总的事件总数为15。感兴趣的读者可以调用weatherStream.ToPointEnumerable().Dump() 查看15个事件的具体内容。

基础过滤

问题1:怎样过滤事件流以保留特定的事件?

对weatherStream过滤可以使用LINQ中的where子句,如保留那些温度高于零下5度的事件:

var filterQuery = from e in weatherStream
where e.Temperature > -5.0
select e;

接下去使用下述语句将filterQuery中的Insert事件导出到LINQPad输出窗口:

(from e in filterQuery.ToPointEnumerable()
where e.EventKind == EventKind.Insert
select e).Dump();

最终的3个过滤事件结果如下:



问题2:怎样进行多条件过滤?

StreamInsight支持多条件过滤,只需要在where子句中指明多个过滤条件即可。问题1中我们过滤出了温度高于零下5度的所有事件;那么如果我们想要过滤出不仅温度高于零下5度,而且风速超过40的事件,该怎么做呢?很简单,只需要在where子句中增加e.WindSpeed > 40就可以了,如下:

var filterQuery2 = from e in weatherStream
where e.Temperature > -5.0 && e.WindSpeed > 40
select e;
(from e in filterQuery2.ToPointEnumerable()
where e.EventKind == EventKind.Insert
select e).Dump();

最终过滤出的2个事件如下:



下篇文章将介绍StreamInsight基础操作操作中的聚合部分。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐