我有一个这样的实体:
public class Event
{
public string Code;
public DateTimeOffset DateTime;
}
我想按Code
过滤,然后按DateTime.Date
分组。我尝试过:
var results = session
.Query<Event>()
.Where(e => e.Code == "123")
.GroupBy(e => e.DateTime.Date)
.ToList();
但是出现以下错误:
Raven.Client.Exceptions.InvalidQueryException: Field 'Code' isn't neither an aggregation operation nor part of the group by key
Query: from Events group by DateTime.Date where Code = $p0
Parameters: {"p0":"123"}
从结果查询中可以看出,在where
子句之后添加了group by
子句,这解释了错误。
那么如何在RavenDB中执行此查询?
编辑:
我使用的code
“ 123”只是一个例子。我需要它是一个传递给查询的变量,像这样:
var results = session
.Query<Event>()
.Where(e => e.Code == code)
.GroupBy(e => e.DateTime.Date)
.ToList();
答案 0 :(得分:1)
首先,请了解以下内容中的 dynamic aggregation query syntax :
https://demo.ravendb.net/demos/auto-indexes/auto-map-reduce-index
但是,在您的情况下,您需要定义一个静态地图减少索引来为您计算:
(将(过滤后的)每个唯一日期的文件)
即
public class Result
{
public string Date { get; set; }
public int NumberOfDocs { get; set; }
}
Map = events => from event in events
where event.Code == "123"
select new Result
{
Date = event.DateTime.Date
NumberOfDocs = 1
}
Reduce = results => from result in results
group result by result.Date into g
select new Result
{
Date = g.Key,
Count = g.Sum(x => x.NumberOfDocs )
}
==>在以下位置了解 Static Map-Reduce Index :
https://demo.ravendb.net/demos/static-indexes/map-reduce-index
按照详细的演练进行操作。
更新: 要使用以下map-reduce索引汇总每个代码和日期“夫妇” 的文档数量,然后可以使用“代码”
进行查询public class Result
{
public string Code { get; set; }
public string Date { get; set; }
public int NumberOfDocs { get; set; }
}
Map = events => from event in events
select new Result
{
Code = event.Code
Date = event.DateTime.Date
NumberOfDocs = 1
}
Reduce = results => from result in results
group result by new
{
result.Code,
result.Date
}
into g
select new Result
{
Code = g.Key.Code
Date = g.Key.DateTime.Date,
NumberOfDocs = g.Sum(x => x.NumberOfDocs )
}
然后查询
List<Result> queryResults = session.Query< Result, <Index_Name> >()
.Where(x => x.Code == "some-code-number")
.ToList();
然后您也可以在代码中完成
queryResults.GroupBy(x => x.Date)