My Sum and Max calls on last used and usage count are wrong. They are always the value that is stored in the second maps value which is currently set to 0. I can make it -100 and that is what the reduce result will be. I noticed someone saying that you should make it an array but I don’t understand how that helps. I have a linq expression over objects using the map/reduce that works properly assuming that the two maps are unioned together.
Here’s the data => https://gist.github.com/940ccca1b0f8917e9eaf
I want to support a query like
var stats = Session.Query<MultiMapApiKeyStats.ApiKeyStats, MultiMapApiKeyStats>()
.Customize(x => x.WaitForNonStaleResultsAsOfNow())
.Where(x => x.AccountId == Account.Id)
.OrderBy(x => x.Key).ToList();
and build a table like

public MultiMapApiKeyStats()
{
AddMap<KeyUsageBase>(uses => from use in uses
select new
{
AccountId = use.AccountId,
ApiKeyId = use.ApiKeyId,
Key = (string)null,
UsageCount = 1,
LastUsed = use.LastUsedTicks,
Pattern = (string)null,
Status = ApiKey.KeyStatus.None,
Type = ApiKey.ApplicationType.None
});
AddMap<ApiKey>(keys => from key in keys
select new
{
AccountId = key.AccountId,
ApiKeyId = key.Id,
Key = key.Key,
UsageCount = 0,
LastUsed = 0,
Pattern = key.Pattern,
Status = key.ApiKeyStatus,
Type = key.Type
});
Reduce = results => from result in results
group result by result.ApiKeyId
into g
select new
{
AccountId = g.Select(x => x.AccountId).FirstOrDefault(),
ApiKeyId = g.Key,
Key = g.Select(x => x.Key).FirstOrDefault(x => x != null),
UsageCount = g.Sum(x => x.UsageCount),
LastUsed = g.Max(x => x.LastUsed),
Pattern = g.Select(x => x.Pattern).FirstOrDefault(),
Status = g.Select(x => x.Status).FirstOrDefault(),
Type = g.Select(x => x.Type).FirstOrDefault()
};
The indexing error
sequence contains no matching elementsis a result of invokingFirston an empty collection which is why you should useFirstOrDefault. Also, referencing your own classes in map and reduce declarations will cause errors because RavenDB can’t resolve those types at indexing time.