我正在实现搜索算法,我需要通过多列搜索数据库。然后算法将返回“最佳匹配”。例如,假设我有一个实体:
public class Person{
public string Name { get; set; }
public int Age { get; set; }
public string Title { get; set; }
}
我的搜索方法需要接受搜索名称,年龄和标题,所有可选,其中任何组合都是可能的。所有字段都有一个权重,我将在我的代码中进行微调以获得更好的结果。结果应按score
排序score
:
matchedColumn1Weight + matchedColumn2Weight + ... + matchedColumnNWeight
我们假设我有一个名为people的表:
Name Age Title
-------------------------
Alice 20 Manager
Bob 21 Friend
James 20 Friend
Will 22 Manager
我们假设Name
的权重为1
,Age
权重为1
,Title
权重为1.1
。如果我用字段name = null, age = 20, title = Friend
搜索,它应首先返回James,然后是Bob,然后是Alice,然后是Will。
如何在LINQ-to-Entities中实现此类功能?换句话说,我需要一个LINQ,我在其中查询多个可选字段,将我的数据库中的每个项目映射到匹配的列的总分(其中列具有固定的预设权重),然后按该分数排序。 如何制作?
答案 0 :(得分:2)
让我们从查询开始:
const decimal nameWeight = 1, ageWeight = 1, titleWeight = 1.1m;
string name = null;
int? age = 20;
string title = (string)"Friend";
var query = from p in db.Persons
let nameMatch = name == null || p.Name == name
let ageMatch = age == null || p.Age == age.Value
let titleMatch = title == null || p.Title == title
let score = (nameMatch ? nameWeight : 0) + (ageMatch ? ageWeight : 0) + (titleMatch ? titleWeight : 0)
where nameMatch || ageMatch || titleMatch
orderby score descending
select p;
这将起作用,但由于嵌入了最佳参数,SQL查询不是最佳的。例如,使用上面的示例参数,SQL查询是这样的:
SELECT
[Project1].[Id] AS [Id],
[Project1].[Name] AS [Name],
[Project1].[Age] AS [Age],
[Project1].[Title] AS [Title]
FROM ( SELECT
[Extent1].[Id] AS [Id],
[Extent1].[Name] AS [Name],
[Extent1].[Age] AS [Age],
[Extent1].[Title] AS [Title],
(CASE WHEN ((CASE WHEN (@p__linq__0 IS NULL OR [Extent1].[Name] = @p__linq__1) THEN cast(1 as bit) WHEN ( NOT (@p__linq__0 IS NULL OR [Extent1].[Name] = @p__linq__1)) THEN cast(0 as bit) END) = 1) THEN cast(1 as decimal(18)) ELSE cast(0 as decimal(18)) END) + (CASE WHEN ((CASE WHEN (@p__linq__2 IS NULL OR [Extent1].[Age] = @p__linq__3) THEN cast(1 as bit) WHEN ( NOT (@p__linq__2 IS NULL OR [Extent1].[Age] = @p__linq__3)) THEN cast(0 as bit) END) = 1) THEN cast(1 as decimal(18)) ELSE cast(0 as decimal(18)) END) + (CASE WHEN ((CASE WHEN (@p__linq__4 IS NULL OR [Extent1].[Title] = @p__linq__5) THEN cast(1 as bit) WHEN ( NOT (@p__linq__4 IS NULL OR [Extent1].[Title] = @p__linq__5)) THEN cast(0 as bit) END) = 1) THEN 1.1 ELSE cast(0 as decimal(18)) END) AS [C1]
FROM [dbo].[People] AS [Extent1]
WHERE ((CASE WHEN (@p__linq__0 IS NULL OR [Extent1].[Name] = @p__linq__1) THEN cast(1 as bit) WHEN ( NOT (@p__linq__0 IS NULL OR [Extent1].[Name] = @p__linq__1)) THEN cast(0 as bit) END) = 1) OR ((CASE WHEN (@p__linq__2 IS NULL OR [Extent1].[Age] = @p__linq__3) THEN cast(1 as bit) WHEN ( NOT (@p__linq__2 IS NULL OR [Extent1].[Age] = @p__linq__3)) THEN cast(0 as bit) END) = 1) OR ((CASE WHEN (@p__linq__4 IS NULL OR [Extent1].[Title] = @p__linq__5) THEN cast(1 as bit) WHEN ( NOT (@p__linq__4 IS NULL OR [Extent1].[Title] = @p__linq__5)) THEN cast(0 as bit) END) = 1)
) AS [Project1]
ORDER BY [Project1].[C1] DESC
动态查询部分可以使用我最近编写并在此处"Nullable object must have a value" exception after checking for null on a non-primitive/non-struct object和此处How to write dynamic where clause for join range varible发布的ReduceConstPredicates
辅助方法进行优化。你最需要的就是最后说:
query = query.ReduceConstPredicates();
,生成的SQL变为:
SELECT
[Project1].[Id] AS [Id],
[Project1].[Name] AS [Name],
[Project1].[Age] AS [Age],
[Project1].[Title] AS [Title]
FROM ( SELECT
[Extent1].[Id] AS [Id],
[Extent1].[Name] AS [Name],
[Extent1].[Age] AS [Age],
[Extent1].[Title] AS [Title],
cast(1 as decimal(18)) + (CASE WHEN ((CASE WHEN ([Extent1].[Age] = @p__linq__0) THEN cast(1 as bit) WHEN ([Extent1].[Age] <> @p__linq__0) THEN cast(0 as bit) END) = 1) THEN cast(1 as decimal(18)) ELSE cast(0 as decimal(18)) END) + (CASE WHEN ((CASE WHEN ([Extent1].[Title] = @p__linq__1) THEN cast(1 as bit) WHEN ([Extent1].[Title] <> @p__linq__1) THEN cast(0 as bit) END) = 1) THEN 1.1 ELSE cast(0 as decimal(18)) END) AS [C1]
FROM [dbo].[People] AS [Extent1]
) AS [Project1]
ORDER BY [Project1].[C1] DESC
P.S。以下是使用方法的源代码:
public static class QueryableExtensions
{
public static IQueryable<T> ReduceConstPredicates<T>(this IQueryable<T> source)
{
var reducer = new ConstPredicateReducer();
var expression = reducer.Visit(source.Expression);
if (expression == source.Expression) return source;
return source.Provider.CreateQuery<T>(expression);
}
class ConstPredicateReducer : ExpressionVisitor
{
private int evaluateConst;
private bool EvaluateConst { get { return evaluateConst > 0; } }
private ConstantExpression TryEvaluateConst(Expression node)
{
evaluateConst++;
try { return Visit(node) as ConstantExpression; }
catch { return null; }
finally { evaluateConst--; }
}
protected override Expression VisitUnary(UnaryExpression node)
{
if (EvaluateConst || node.Type == typeof(bool))
{
var operandConst = TryEvaluateConst(node.Operand);
if (operandConst != null)
{
var result = Expression.Lambda(node.Update(operandConst)).Compile().DynamicInvoke();
return Expression.Constant(result, node.Type);
}
}
return EvaluateConst ? node : base.VisitUnary(node);
}
protected override Expression VisitBinary(BinaryExpression node)
{
if (EvaluateConst || node.Type == typeof(bool))
{
var leftConst = TryEvaluateConst(node.Left);
if (leftConst != null)
{
if (node.NodeType == ExpressionType.AndAlso)
return (bool)leftConst.Value ? Visit(node.Right) : Expression.Constant(false);
if (node.NodeType == ExpressionType.OrElse)
return !(bool)leftConst.Value ? Visit(node.Right) : Expression.Constant(true);
var rightConst = TryEvaluateConst(node.Right);
if (rightConst != null)
{
var result = Expression.Lambda(node.Update(leftConst, node.Conversion, rightConst)).Compile().DynamicInvoke();
return Expression.Constant(result, node.Type);
}
}
}
return EvaluateConst ? node : base.VisitBinary(node);
}
protected override Expression VisitConditional(ConditionalExpression node)
{
if (EvaluateConst || node.Type == typeof(bool))
{
var testConst = TryEvaluateConst(node.Test);
if (testConst != null)
return Visit((bool)testConst.Value ? node.IfTrue : node.IfFalse);
}
return EvaluateConst ? node : base.VisitConditional(node);
}
protected override Expression VisitMember(MemberExpression node)
{
if (EvaluateConst || node.Type == typeof(bool))
{
var expressionConst = node.Expression != null ? TryEvaluateConst(node.Expression) : null;
if (expressionConst != null || node.Expression == null)
{
var result = Expression.Lambda(node.Update(expressionConst)).Compile().DynamicInvoke();
return Expression.Constant(result, node.Type);
}
}
return EvaluateConst ? node : base.VisitMember(node);
}
protected override Expression VisitMethodCall(MethodCallExpression node)
{
if (EvaluateConst || node.Type == typeof(bool))
{
var objectConst = node.Object != null ? TryEvaluateConst(node.Object) : null;
if (objectConst != null || node.Object == null)
{
var argumentsConst = new ConstantExpression[node.Arguments.Count];
int count = 0;
while (count < argumentsConst.Length && (argumentsConst[count] = TryEvaluateConst(node.Arguments[count])) != null)
count++;
if (count == argumentsConst.Length)
{
var result = Expression.Lambda(node.Update(objectConst, argumentsConst)).Compile().DynamicInvoke();
return Expression.Constant(result, node.Type);
}
}
}
return EvaluateConst ? node : base.VisitMethodCall(node);
}
}
}
答案 1 :(得分:0)
你可以让你的类IComparable像下面的代码使用的方法。您可以使用类似的代码创建更复杂的排序算法。 CompareTo返回-1(小),0相等,+ 1(更多)。
public class Person : IComparable
{
public string Name { get; set; }
public int Age { get; set; }
public string Title { get; set; }
public List<string> order { get; set; }
public int CompareTo(object _other)
{
Person other = (Person)_other;
int results = 0;
if (this.Name != other.Name)
{
results = this.Name.CompareTo(other.Name);
}
else
{
if (this.Age != other.Age)
{
results = this.Age.CompareTo(other.Age);
}
else
{
results = this.Title.CompareTo(other.Title);
}
}
return results;
}