Ranking Search Results With LINQ/.NET MVC - c#

I have a task where I need to rank the search results based on which column the search term was found.
So for example, if the search term is found in column A of table 1, it ranks higher than if it was found in column A of table 2.
Right now, I have a linq query that joins multiple tables and searches for the search term in certain columns. I.E.
var results = db.People
.Join(db.Menu, p => p.ID, m => m.PersonID, (p, m) => new { p = p, m = m })
.Join(db.Domain, m => m.m.DomainID, d => d.ID, (m, d) => new { m = m, d = d })
.Where(d => searchTermArray.Any(x => d.m.p.p.Name.Contains(x)) || searchTermArray.Any(x => d.m.p.p.Biography.Contains(x)) || searchTermArray.Any(x => d.d.domain.Contains(x)))
.Select(p => p).Distinct();
So if the search term is found in db.People, column Name, that row/Person will rank higher than if found in db.People, column Biography, which will rank higher than if found in db.Domain, column domain.

This will order your result by the "rank". You can manipulate the query further if you also want to return the rank and not only the aggregate:
var results = db.People
.Join(db.Menu, p => p.ID, m => m.PersonID, (p, m) => new { p = p, m = m })
.Join(db.Domain, m => m.m.DomainID, d => d.ID, (m, d) => new { m = m, d = d })
.Select(d => new
{
rank = searchTermArray.Any(x => d.m.p.p.Name.Contains(x)) ? 3 : searchTermArray.Any(x => d.m.p.p.Biography.Contains(x)) ? 2 : searchTermArray.Any(x => d.d.domain.Contains(x)) ? 1 : 0,
m = d
})
.Where(a => a.rank > 0)
.OrderByDescending(a => a.rank)
.Select(a => a.m).Distinct();
Note: I take no responsibility for poor performance, that's LINQ after all.

Related

C# NEST nested filter to get values within the dateRange or NULL

I am developing something to show a pie chart of the users' age with slicing them as
0-17
18-34
35-44
44-54
55+
Not Available
here i am getting the ages based on the date range;
var aggaResonse = client.Search<JSModel>(a => a
.Size(0)
.Query(q => q.Bool(b => b.Must(m => m
.DateRange(date => date
.Field(p => p.CreatedDate)
.GreaterThanOrEquals(start)
.LessThanOrEquals(end)),
m =>
m.Term(t => t.Field(f => f.StepType.Suffix("keyword")).Value("User"))
)
))
.Aggregations(c => c.DateRange(nameof(AgeModel), x => x
.Field(f => f.BirthDate)
.Ranges(r => r.From(DateMath.Now.Subtract("17y")).To(DateMath.Now).Key(nameof(result.Years_0_17)),
r => r.From(DateMath.Now.Subtract("34y")).To(DateMath.Now.Subtract("18y")).Key(nameof(result.Years_18_34)),
r => r.From(DateMath.Now.Subtract("44y")).To(DateMath.Now.Subtract("35y")).Key(nameof(result.Years_35_44)),
r => r.From(DateMath.Now.Subtract("54y")).To(DateMath.Now.Subtract("45y")).Key(nameof(result.Years_45_54)),
r => r.From(DateMath.Now.Subtract("120y")).To(DateMath.Now.Subtract("55y")).Key(nameof(result.Years_55_Plus))
)
)
));
if (!aggaResonse.IsValid)
return result;
result.Years_0_17 = aggaResonse.Aggregations.Range(nameof(AgeModel)).Buckets.Single(c => c.Key == nameof(result.Years_0_17)).DocCount;
result.Years_18_34 = aggaResonse.Aggregations.Range(nameof(AgeModel)).Buckets.Single(c => c.Key == nameof(result.Years_18_34)).DocCount;
result.Years_35_44 = aggaResonse.Aggregations.Range(nameof(AgeModel)).Buckets.Single(c => c.Key == nameof(result.Years_35_44)).DocCount;
result.Years_45_54 = aggaResonse.Aggregations.Range(nameof(AgeModel)).Buckets.Single(c => c.Key == nameof(result.Years_45_54)).DocCount;
result.Years_55_Plus = aggaResonse.Aggregations.Range(nameof(AgeModel)).Buckets.Single(c => c.Key == nameof(result.Years_55_Plus)).DocCount;
return result;
what i need is to have a "Not Available" slice for users who has NULL as birthdate with mapping it as;
result.Not_Available = ....;
Any suggestions with following best practices for nested NEST aggs ?
I was thinking to run another search which i guess it's not the best practice.
After digging documentations too much, here is the solution i wrote;
I added a "Missing" attribute to the current aggregation;
&& c.Missing("DOBMissing", x => x.Field(f => f.BirthDate))
So it became like;
.Aggregations(c => c.DateRange(nameof(AgeModel), x => x
.Field(f => f.BirthDate)
.Ranges(r => r.From(DateMath.Now.Subtract("17y")).To(DateMath.Now).Key(nameof(result.Years_0_17)),
r => r.From(DateMath.Now.Subtract("34y")).To(DateMath.Now.Subtract("18y")).Key(nameof(result.Years_18_34)),
r => r.From(DateMath.Now.Subtract("44y")).To(DateMath.Now.Subtract("35y")).Key(nameof(result.Years_35_44)),
r => r.From(DateMath.Now.Subtract("54y")).To(DateMath.Now.Subtract("45y")).Key(nameof(result.Years_45_54)),
r => r.From(DateMath.Now.Subtract("120y")).To(DateMath.Now.Subtract("55y")).Key(nameof(result.Years_55_Plus))
)
) &&
c.Missing("DOBMissing", x => x.Field(f => f.BirthDate))
)
And i'd accessed the "missing" part of aggregation as following;
result.Not_Available = aggaResponse.Aggregations.Missing("DOBMissing").DocCount;

Translating Linq expression in c#

I am trying to convert this code:
var query2 = from b in db.MU_Reports
join downtime in db.Downtime_Reports on b.Shift equals downtime.Shift
where downtime.Downtime_Code.Equals("9185")
group downtime by new { b.Date, b.Shift, b.Machine_Number, b.MU } into g
select new
{
Date = g.Key.Date,
Shift = g.Key.Shift,
Machine = g.Key.Machine_Number,
MU = g.Key.MU,
No_Work_Hours = g.Sum(x => x.Total_DownTime)
};
To look something like this one:
var query = db.MU_Reports.Join(db.Downtime_Reports, b=> b.Shift, c=> c.Shift, (b , c) => new { b, thisshift = c })
.Where(n => n.thisshift.Down_TIme_Codes.Equals("9185"))
.GroupBy(d=> new { d.b.Date, d.b.Shift, d.b.Machine_Number, d.b.MU }, d => d.b)
.Select (g=> new
{
Date = g.Key.Date,
Shift = g.Key.Shift,
Machine = g.Key.Machine_Number,
MU = g.Key.MU,
No_Work_Hours = g.Sum(i => i.Total_DownTime)
}).ToList();
As you can see I am very close. My only issue is the last statement No_Work_Hours = g.Sum(i => i.Total_DownTime) It is trying to get the Total_DownTime from db.MU_Reports but it needs to come from db.Downtime_Reports. I am new to c# and am doing this to understand the program I created better.
Your second argument to GroupBy should be d => d.thisshift instead of d => d.b. That corresponds to the group downtime by, but by doing d => d.b it's like you're doing group b by
var query = db.MU_Reports
.Join(
db.Downtime_Reports,
b=> b.Shift,
c=> c.Shift,
(b , c) => new { b, thisshift = c })
.Where(n => n.thisshift.Down_TIme_Codes.Equals("9185"))
.GroupBy(
d=> new { d.b.Date, d.b.Shift, d.b.Machine_Number, d.b.MU },
d => d.thisshift)
.Select (g=> new
{
Date = g.Key.Date,
Shift = g.Key.Shift,
Machine = g.Key.Machine_Number,
MU = g.Key.MU,
No_Work_Hours = g.Sum(i => i.Total_DownTime)
})
.ToList();

How can I transform this SQL query to LINQ?

How can I transform this SQL query to LINQ?
SELECT eg.Name Name, sum(bi.PlannedAmount) Amount
FROM BudgetItem bi, Expense e, ExpenseGroup eg
WHERE Discriminator = 'ExpenseItem' AND
bi.ExpenseId = e.Id AND
e.ExpenseGroupId = eg.id AND
bi.MonthlyBudgetId = 1
GROUP BY eg.Name
So far I've come up with this line:
var result = context
.ExpenseGroups
.GroupBy(eg => eg.Id, (s) => new { Name = s.Name, Amount = s.Expenses.SelectMany(e => e.Items).Sum(i => i.PlannedAmount) })
.ToList();
But I still cannot figure out what expression to use to add 'bi.MonthlyBudgetItem = 1'.
Does anybody have an Idea?
Edit #1:
I forgot to mention the relationships between the entities. Every ExpenseGroup has many Expenses, and every Expense has many BudgetItems.
So, ExpenseGroup => Expenses => BudgetItems
Edit #2:
I'm using Entity Framework and every ExpenseGroup has a Collection of Expense objects (every Expense has a ExpenseGroup object), as well as every Expense has a Collection of BudgetItem objects (every BudgetItem object has a Expense object).
I suppose something like this should do it:
var result = context
.ExpenseGroups
.Where(x => x.Discriminator == 'ExpenseItem' &&
x.bi.ExpenseId == e.Id &&
x.e.ExpenseGroupId == eg.id &&
x.bi.MonthlyBudgetId == 1)
.GroupBy(eg => eg.Id, (s) => new { Name = s.Name, Amount = s.Expenses.SelectMany(e => e.Items).Sum(i => i.PlannedAmount) })
.ToList();
Something similar to this...
var result = (from g in context.ExpenseGroups
where g.Expense.BudgetItem.MonthlyBudgetId == 1
select g)
.GroupBy(eg => eg.Id, (s) => new { Name = s.Name, Amount = s.Expenses.SelectMany(e => e.Items).Sum(i => i.PlannedAmount) })
.ToList();
or
var result = context.ExpenseGroups
.Where(g => g.Expense.BudgetItem.MonthlyBudgetId == 1)
.GroupBy(eg => eg.Id, (s) => new { Name = s.Name, Amount = s.Expenses.SelectMany(e => e.Items).Sum(i => i.PlannedAmount) })
.ToList();
You are actually doing an inner join in your SQL query, so do similarly in your linq query as well. This should work:-
var result = from bi in context.BudgetItem
join e in context.Expense
on bi.ExpenseId equals e.Id
where bi.MonthlyBudgetId == 1
join eg in ExpenseGroup
on e.ExpenseGroupId equals eg.id
group new { bi, eg } by eg.Name into g
select new
{
Name = g.Key,
Amount = g.Sum(x => x.bi.PlannedAmount)
};

Having problems with a Lambda LINQ Query

I'm trying to convert the following SQL expression into a Lambda LINQ query and I seem to be going round in circles at the moment:
select m.MemberExternalPK FROM Member.Member AS m INNER JOIN Member.Account AS a ON m.MemberID = a.MemberID where m.MemberExternalPK in
(
SELECT m.MemberExternalPK
FROM Member.Member AS m INNER JOIN Member.Account AS a ON m.MemberID = a.MemberID
group by MemberExternalPK
having Count(AccountID) = 1
)
and AccountStatusID = 3
So far I have managed to get the following syntax that returns the correct number of rows I am after but all columns (except the MemberExternalPK one I want)!
Members.Join(Accounts, m => m.MemberID, a => a.MemberID, (m, a) => new { m, a })
.GroupBy(t => t.m.MemberExternalPK, t => t.a)
.Where(grp => grp.Count(p => p.AccountID != null) == 1)
.SelectMany(sublist => sublist).Where(x => x.AccountStatusID == 3)
I think this is fairly close:
var query =
from m in Member_Member
join a in Member_Account on m.MemberID equals a.MemberID
group a by m.MemberExternalPK into gas
where gas.Count(ga => ga.AccountID != null) == 1
from ga in gas
where ga.AccountStatusID == 3
select gas.Key;
The only concern is the ga.AccountID != null which means that the gas group may have more than one record so you might end up with more than one gas.Key at the end.
Something like this? Splitting it up could also improve performance.
var externalMembers =
Members.Join(Accounts, m => m.MemberID, a => a.MemberID, (m, a) => new { m, a })
.GroupBy(grp => grp.MemberExternalPK)
.Where(grp => grp.Count() > 1)
.Select(grp => grp.Key);
var result =
Members.Where(w => externalMembers.Contains(w.MemberExternalPK) && w.AccountStatusID == 3)
.Select(s => s.MemberExternalPK)

Helpme to Convert from SQL to linq Nested lambda Expression with EntityFramework

I´m trying to bring some Data from SQL but I cant do it with Linq, in T-SQL this Work:
select *
from MTRBatch MB
Inner Join MTR M on MB.Id = M.MTRBatchId
Inner JOIN MTRHeats MH on M.Id = MH.MTRId
LEFT OUTER JOIN Vendor V on MB.VendorId = v.Id
Inner Join Manufacturer MF on MB.ManufacturerId = MF.Id
Where MB.ManufacturerId = 1
AND MH.Heat = 'z01'
I need All the tree but with that filter.
I try this but didnt work :
MTRBatches
.Include(x => x.MTRs.Select(m => m.MTRHeats))
.Include(x => x.Manufacturer)
.Include(x => x.Vendor)
.Where(x => (x.Manufacturer.Id == 1));
.Where(x => x.MTRs.Any(m => m.MTRHeats.Any(h => h.Heat == 'z01')));
This should help; dataContext is the name of your instance of Entity Framework container.
var result = dataContext.MTRBatches
.Join(dataContext.MTRs,
mb => mb.Id,
mtr => mtr.MTRBatchId,
(mb, mtr) => new{ Batch = mb, MTR = mtr })
.Join(dataContext.MTRHeats,
x => x.MTR.Id,
mh => mh.MTRId,
(x, mh) => new{ Batch = x.Batch, MTR = x.MTR, Heat = mh })
.Join(dataContext.Vendors.DefaultIfEmpty(),
x => x.Batch.VendorId,
v => v.Id,
(x, v) => new{ Batch = x.Batch, MTR = x.MTR, Heat = x.Heat, Vendor = v })
.Join(dataContext.Manufacturers,
x => x.Batch.ManufacturerId,
mf => mf.Id,
(x, mf) => new{ Batch = x.Batch, MTR = x.MTR, Heat = x.Heat, Vendor = x.Vendor, Manufacturer = mf})
.Where(x => x.Manufacturer.Id == 1 && x.Heat.Heat == "z01");

Categories

Resources