How to do a MaxBy in RavenDb MapReduce - mapreduce

Using the Northwind database from RavenDB tutorial I'm trying to group orders by employee and get the most resent order for every employee.
Map:
from order in docs.Orders
select new {
Employee = order.Employee,
Count = 1,
MostRecent = order.OrderedAt,
MostRecentOrderId = order.Id
}
Reduce with nonexisting MaxBy:
from result in results
group result by result.Employee into grp
select new {
Employee = grp.Key,
Count = grp.Sum(result => result.Count),
MostRecent = grp.Max(result => result.MostRecent),
MostRecentOrderId = grp.MaxBy(result => result.MostRecent).MostRecentOrderId,
}
Reduce attempt:
from result in results
group result by result.Employee into grp
let TempMostRecent = grp.Max(result => result.MostRecent)
select new {
Employee = grp.Key,
Count = grp.Sum(result => result.Count),
MostRecent = TempMostRecent,
MostRecentOrderId = grp.First(result => result.MostRecent == TempMostRecent).MostRecentOrderId
}
However my reduce attempt returns 0 results.
Also: will RavenDB treat the Order.OrderetAt as a proper DateTime value and order them correctly?

You need to do it like
from order in docs.Orders
select new {
Employee = order.Employee,
Count = 1,
MostRecent = order.OrderedAt,
MostRecentOrderId = order.Id
}
from result in results
group result by result.Employee into grp
let maxOrder = grp.OrderByDescending(x=>x.MostRecent).First()
select new {
Employee = grp.Key,
Count = grp.Sum(result => result.Count),
MostRecent = maxOrder.MostRecent,
MostRecentOrderId = maxOrder.MostRecentOrderId,
}

Related

Is there a way to find an element in a list and delete items after it that are of a specific type without using indicies?

I have a project that needs me to remove items if one of the properties of the item I'm trying to find within the list is true. Just so it's easier understand the project I am pasting all code needed to understand it below.
fun main() {
val acct1 = AccountId(72)
val calendars = mutableListOf<CalendarDrawerCalendarItem>()
val calendars2 = mutableListOf<CalendarDrawerCalendarItem>()
calendars.add(CalendarDrawerCalendarItem(CalendarDescriptor(acct1, CalendarId(acct1, 3),"toast", true)))
calendars.add(CalendarDrawerCalendarItem(CalendarDescriptor(acct1, CalendarId(acct1, 4), "chicken", false)))
calendars.add(CalendarDrawerCalendarItem(CalendarDescriptor(acct1, CalendarId(acct1, 5), "pizza", true)))
calendars2.add(CalendarDrawerCalendarItem(CalendarDescriptor(acct1, CalendarId(acct1, 1), "bagel", true)))
// These are example calls to collapse
collapse(calendars, CalendarDrawerGroupItem(true, CalendarGroupDescriptor( acct1, "My Calendars")))
collapse(calendars2, CalendarDrawerGroupItem(false, CalendarGroupDescriptor(acct1, "Group Calendars")))
}
fun collapse(calendars: List<CalendarDrawerListItem>, group: CalendarDrawerGroupItem): List<CalendarDrawerListItem> {
val collapsedResults = mutableListOf<CalendarDrawerListItem>()
val findGroupGiven = group
collapsedResults.addAll(calendars)
if (collapsedResults.contains(findGroupGiven)) {
group.collapsed = true
// logic for deleting items here
}
return collapsedResults
}
I'll also put the classes so you can see how they're defined
data class AccountId(
val accountId: Int
)
data class CalendarId(
val accountId: AccountId,
val calendarId: Int)
data class CalendarDescriptor(
val accountId: AccountId,
val calendarId: CalendarId,
val name: String,
val isGroupCalendar: Boolean
)
data class CalendarGroupDescriptor(
val accountId: AccountId,
val name: String,
)
sealed class CalendarDrawerListItem
data class CalendarDrawerGroupItem(var collapsed: Boolean, val groupDescriptor: CalendarGroupDescriptor) : CalendarDrawerListItem()
data class CalendarDrawerCalendarItem(val calendarDescriptor: CalendarDescriptor) : CalendarDrawerListItem()
The first step I have done is I must find the given group from the group variable, within calendars. (I did this with the contains() method). Next when I find the group I have to set its collapsed variable to true and any CalendarDrawerCalendarItems after it have to be deleted.
The input will look something like (the exact numbers and values are not the important part):
Input:
calendars:
CDGroupItem(collapsed = false, groupDescriptor = GroupDescriptor(accountId = 1, name = "My calendars"))
CDCalendarItem(calendarDescriptor = CalendarDescriptor(accountId = 1, calendarId = 1, isGroup = false))
CDCalendarItem(calendarDescriptor = CalendarDescriptor(accountId = 1, calendarId = 2, isGroup = false))
CDCalendarItem(calendarDescriptor = CalendarDescriptor(accountId = 1, calendarId = 3, isGroup = false))
CDGroupItem(collapsed = false, groupDescriptor = GroupDescriptor(accountId = 1, name = "Group calendars"))
CDCalendarItem(calendarDescriptor = CalendarDescriptor(accountId = 1, calendarId = 4, isGroup = true))
CDCalendarItem(calendarDescriptor = CalendarDescriptor(accountId = 1, calendarId = 5, isGroup = true))
group: CDGroupItem(collapsed = false, groupDescriptor = GroupDescriptor(accountId = 1, name = "My calendars"))
The output should look something like this:
Output:
CDGroupItem(collapsed = true, groupDescriptor = GroupDescriptor(accountId = 1, name = "My calendars"))
CDGroupItem(collapsed = false, groupDescriptor = GroupDescriptor(accountId = 1, name = "Group calendars"))
CDCalendarItem(calendarDescriptor = CalendarDescriptor(accountId = 1, calendarId = 4, isGroup = true))
CDCalendarItem(calendarDescriptor = CalendarDescriptor(accountId = 1, calendarId = 5, isGroup = true))
Any group item that has its collapsed boolean set to true should have all calendar items deleted after it since its collapsed is set to true. Again the names and numbers are not super important. The collapsed bool is. How can I do this without hardcoding or using indicies?
Your example code doesn't use that input and output as-is so I can only give you a general example, but you could use a fold:
val result = calendars.fold(mutableListOf<CalendarDrawerListItem>()) { items, current ->
// basically 'is there a last item stored, and is it a group item, and is it collapsed'
val lastStoredIsCollapsed =
(items.lastOrNull() as? CalendarDrawerGroupItem)?.collapsed == true
if (current is CalendarDrawerCalendarItem && lastStoredIsCollapsed) items
else items.apply { add(current) }
}
It basically pipes out each item into a list, but if the last one it stored is a CalendarDrawerGroupItem with collapsed set to true, it drops drawer items. If the last one is a non-collapsed group item, it can store a drawer item, and that means the next drawer item will be stored (since the last item isn't a collapsed group)
edit: here's the for loop equivalent if it helps, with the full logic for when a calendar is not dropped (the logic in my other example is for whether it should be dropped, which can be condensed a bit):
// assuming 'calendars' is your list of items with 'collapsed' set appropriately
val result = mutableListOf<CalendarDrawerListItem)
for (calendar in calendars) {
val lastStored = result.lastOrNull()
when {
lastStored == null ->
result.add(calendar)
lastStored is CalendarDrawerGroupItem && !lastStored.collapsed ->
result.add(calendar)
lastStored is CalendarDrawerCalendarItem ->
result.add(calendar)
}
}
return result
If you're asking how to actually mutate your list so a collapsed property is set to true, that would be easy if the property was a var in your data class. Since it's a val you'll have to do something like this:
val calendarInputWithCollapsedSet = calendars.map { calendar ->
if ((calendar as? CalendarDrawerGroupItem)?.groupDescriptor == group.groupDescriptor)
calendar.copy(collapsed = true) else calendar
}
So if you find a matching group (you'll have to work out how to match them, I'm guessing) you transform it into a copy with its collapsed property set
And then you can run the fold or whatever on that new list.

Linq query with group by with .NET Core

I'm trying to do a simple query. I want to have a list with a string and a Guid and a sub-list with a decimal and a string. I have my query this way but it keeps getting error when translated to Entity Framework what am I doing wrong?
Thanks in advance
var a = ( from c in DbContext.CC
join icc in DbContext.ICC c.Id equals icc.CCId
join i in DbContext.I on icc.IId equals i.Id
join p in DbContext.P on i.PId equals p.Id
select new
{
GuidId = p.Id,
StringN = p.StringN,
CCString = c.CCString ,
DecimalValue = icc.DecimalValue
}).GroupBy(x => new { x.GuidId , x.StringN }).
Select(x => new Model
{
GuidId = x.Key.GuidId ,
StringN = x.Key.StringN ,
Values= x.Select(y => new OtherModel
{
DecimalValue = y.DecimalValue ,
CCString = y.CCString
})
}
).OrderBy(x => x.StringN );
Error:
The LINQ expression '(GroupByShaperExpression:
KeySelector: new {
GuidId = (p.Id),
StringN = (p.Name)
},
ElementSelector:new {
GuidId = (ProjectionBindingExpression: GuidId ),
StringN = (ProjectionBindingExpression: StringN ),
CCString = (ProjectionBindingExpression: CCString ),
DecimalValue = (ProjectionBindingExpression: DecimalValue )
}
)
.Select(y => new OtherModel{
DecimalValue = y.DecimalValue ,
CCString = y.CCString
}
)' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync(). See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.
It is SQL limitation. You cannot select grouped items, only Key and aggregation result is allowed.
Add AsEnumerable to your LINQ query to do grouping on the client side:
var a = (
from c in DbContext.CC
join icc in DbContext.ICC c.Id equals icc.CCId
join i in DbContext.I on icc.IId equals i.Id
join p in DbContext.P on i.PId equals p.Id
select new
{
GuidId = p.Id,
StringN = p.StringN,
CCString = c.CCString,
DecimalValue = icc.DecimalValue
})
.AsEnumerable()
.GroupBy(x => new { x.GuidId , x.StringN })
.Select(x => new Model
{
GuidId = x.Key.GuidId,
StringN = x.Key.StringN,
Values = x.Select(y => new OtherModel
{
DecimalValue = y.DecimalValue,
CCString = y.CCString
})
})
.OrderBy(x => x.StringN);

Add items to an existing list mvc5

(I am a new developer)I have a list that I put in a viewBag to make a dropwdown in my view and I would like to add 3 elements to this list so that we can see them at the end of my dropdown. I make a timesheet for the employees and I have a dropdown of the projects that the person worked during the week and I would like to add at the end of the dropdown the 3 options "Vacancy", "Unplanned Absence", "Planned Absence" if the person has been on leave instead of working.
This is my request for the projects :
var projectAssignment = (from pa in db.ProjectAssignment
join p in db.Projects on pa.ProjectId equals p.ID
where pa.EmployeeId == EmployeeId && pa.StartDate !=null && (pa.EndDate == null || pa.EndDate >= DateTime.Now)
select new ProjectTimesheetList
{
ProjectName = p.ProjectName,
ProjectId = pa.ProjectId
});
ViewBag.ProjectTimeSHeet = projectAssignment;
This is a the modal to add my timehseet and i want to put the 3 daysoff type at the end of dropdown, so in this case after "NatureBooker"
And this is my code of my dropdown:
<select name="' + row + '_' + col + '" class="custom-select" id="tsCell_' + row + '_' + col + '" data-row="' + row + '" data-col="' + col + '">' +
'<option value="">----Select----</option>#Html.Raw(projsStr)</select>';
SOLUTION:
var projectAssignment = (from pa in db.ProjectAssignment
join p in db.Projects on pa.ProjectId equals p.ID
where pa.EmployeeId == EmployeeId && pa.StartDate !=null && (pa.EndDate == null || pa.EndDate >= DateTime.Now)
select new ProjectTimesheetList
{
ProjectName = p.ProjectName,
ProjectId = pa.ProjectId
});
List<ProjectTimesheetList> projectAssignments = projectAssignment.ToList();
projectAssignments.Add(new ProjectTimesheetList
{
ProjectName = "Vacancy",
ProjectId = -1,
});
projectAssignments.Add(new ProjectTimesheetList
{
ProjectName = "Unplanned Absence",
ProjectId = -2,
});
projectAssignments.Add(new ProjectTimesheetList
{
ProjectName = "Planned Absence",
ProjectId = -3,
});
ViewBag.ProjectTimeSHeet = projectAssignments;
And the result:
Still not clear what exactly you want, but if my guess is right you probably want to add "fake" projects to the enumerable you're binding to (not a list, by the way).
As long as you understand that this is absolutely wrong and grounds for being fired on the spot, here you go:
ViewBag.ProjectTimeSHeet = projectAssignment
.Concat(new[]
{
new ProjectTimesheetList
{
ProjectName = "Vacancy",
ProjectId = -1,
},
new ProjectTimesheetList
{
ProjectName = "Unplanned Absence",
ProjectId = -2,
},
new ProjectTimesheetList
{
ProjectName = "Planned Absence",
ProjectId = -3,
},
});
var myOptions = {
val1 : 'Vacancy',
val2 : 'Unplanned Absence',
val3 : 'Planned Absence',
};
var mySelect = $('#dropdownID');
$.each(myOptions, function(val, text) {
mySelect.append(
$('<option></option>').val(val).html(text)
);
});
through Javascript
var ddl = document.getElementById("dropdownID");
for ( let key in myOptions )
{
var option = document.createElement("OPTION");
option.innerHTML = key
option.value = myOptions[key]
ddl.options.add(option);
}

how can i execute or not a line of a for-comprehension depending on a condition, with scala slickdb

I have this code using slickdb:
val action: DBIOAction[Int, NoStream, Effect] =
for {
id <- sql"select id from product where name = $name".as[Int].head
_ <- sql"update product set description = ${description(id, name)}".asUpdate if id != 5
} yield id
db.run(action)
With this code, the action will not return the id if id != 5. This is not what I want. I want that the set description update is only executed if id != 5, and at the same time dbaction must return the id independenting or whether id != 5 or not.
How can I achieve this?
You might need something like this:
val action: DBIOAction[Int, NoStream, Effect] =
for {
id <- sql"select id from product where name = $name".as[Int].head
} yield {
if (id != 5) {sql"update product set description = ${description(id, name)}".asUpdate }
id
}

RavenDB Map/Reduce with grouping by date

I have to create a query to get a statistic by post per year/month, e.g. group by date. I created an index:
public class Posts_Count : AbstractIndexCreationTask<Post, ArchiveItem>
{
public Posts_Count()
{
Map = posts => from post in posts
select new
{
Year = post.PublishedOn.Year,
Month = post.PublishedOn.Month,
Count = 1
};
Reduce = results => from result in results
group result by new {
result.Year,
result.Month
}
into agg
select new
{
Year = agg.Key.Year,
Month = agg.Key.Month,
Count = agg.Sum(x => x.Count)
};
}
}
In studio I have next map and reduce functions:
Map:
docs.Posts.Select(post => new {Year = post.PublishedOn.Year, Month = post.PublishedOn.Month, Count = 1})
Reduce:
results
.GroupBy(result => new {Year = result.Year, Month = result.Month})
.Select(agg => new {Year = agg.Key.Year, Month = agg.Key.Month, Count = agg.Sum(x => ((System.Int32)(x.Count)))})
But the problem is I alway get a null values of Year and Month properties:
{
"Year": null,
"Month": null,
"Count": "1"
}
Can anybody help me to resolve the issue with my code? Thank You!
Your code looks fine. I tested it and it works in the current unstable build 1.2.2096. There have been some discussion around this lately on the RavenDB google group, so perhaps it was broken previously. Try again with the current build and see if it works for you now.