Related to this question: RavenDB Get By List of IDs? What I have is not working:
public class Entity
{
public int CategoryId; //Unique identifier for the category the price applies to.
public int Price; //Changes with time
public DateTime Timestamp; //DateTime.UtcNow
}
public class LastEntityIndex : AbstractIndexCreationTask<Entity, Entity>
{
public LastEntityIndex()
{
Map = prices => prices.Select(a => new { a.CategoryId, a.Price, a.Timestamp });
Reduce = prices => from price in prices
group price by price.CategoryId
into g
let a = g.OrderByDescending(a => a.Timestamp).FirstOrDefault()
select new
{
a.CategoryId,
a.Price,
a.Timestamp
};
}
}
public class LastEntity
{
public int CategoryId;
public DateTime Timestamp;
public Entity LastEntity;
}
public class LastReportIndex : AbstractIndexCreationTask<Entity, LastEntity>
{
public LastReportIndex()
{
Map = reports => reports.Select(a => new { a.CategoryId, a.Timestamp, LastEntity = a });
Reduce = reports => from report in reports
group report by report.CategoryId
into g
let a = g.OrderByDescending(a => a.Timestamp).FirstOrDefault()
select new
{
a.CategoryId,
a.Timestamp,
a.LastEntity
};
}
}
I'd like to create an index to get the latest record by each category. But none of the above are working. Any help is hugely appreciated. Going away from sql for this new project and evaluating Raven. So far it seems very powerful and spot on for what we need, but it's hard with the paradigm shift away from sql dbs.
Thank you very much.
PS Using this to retrieve the records:
public List<Entity> GetLastEntityForCategoryIds(List<int> categoryIds)
{
using (var session = _documentStore.OpenSession())
{
return session.Query<LastEntity, LastReportIndex>()
.Where(x => x.CategoryId.In(categoryIds))
.Select(a => a.LastEntity)
.ToList();
}
}
Obviously the 'LastEntityIndex' is not something that I'd use long term (it's just to try out see if that works), because the real Entity has a lot more fields that just 3 and copying them all and maintaining it will be very hard.