-
Notifications
You must be signed in to change notification settings - Fork 3.4k
Expand file tree
/
Copy pathSqlServerQueryableExtensions.cs
More file actions
246 lines (226 loc) · 12.4 KB
/
SqlServerQueryableExtensions.cs
File metadata and controls
246 lines (226 loc) · 12.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics.CodeAnalysis;
using Microsoft.EntityFrameworkCore.Query;
using Microsoft.EntityFrameworkCore.Query.Internal;
#pragma warning disable IDE0130 // Namespace does not match folder structure
// ReSharper disable once CheckNamespace
namespace Microsoft.EntityFrameworkCore;
/// <summary>
/// SQL Server extension methods for LINQ queries.
/// </summary>
public static class SqlServerQueryableExtensions
{
#region VectorSearch
/// <summary>
/// Search for vectors similar to a given query vector using an approximate nearest neighbors vector search algorithm.
/// </summary>
/// <param name="source">The <see cref="DbSet{T}" /> representing the table containing the vector column to query.</param>
/// <param name="vectorPropertySelector">A selector for the vector property on the entity.</param>
/// <param name="similarTo">The vector used for search, either a parameter or another vector column.</param>
/// <param name="metric">
/// The distance metric used to calculate the distance between the query vector and the vectors in the specified column.
/// An ANN (Approximate Nearest Neighbor) index is used only if a matching ANN index, with the same metric and on the same column,
/// is found. If there are no compatible ANN indexes, a warning is raised and the KNN (k-Nearest Neighbor) algorithm is used.
/// </param>
/// <remarks>
/// <para>
/// Results are implicitly ordered by distance ascending. Compose the returned query with <c>Take(...)</c> to limit the
/// number of results as required for approximate vector search.
/// </para>
/// </remarks>
/// <seealso href="https://learn.microsoft.com/sql/t-sql/functions/vector-search-transact-sql">
/// SQL Server documentation for <c>VECTOR_SEARCH()</c>.
/// </seealso>
/// <seealso href="https://learn.microsoft.com/sql/relational-databases/vectors/vectors-sql-server">Vectors in the SQL Database Engine.</seealso>
[Experimental(EFDiagnostics.SqlServerVectorSearch)]
public static IQueryable<VectorSearchResult<T>> VectorSearch<T, TVector>(
this DbSet<T> source,
Expression<Func<T, TVector>> vectorPropertySelector,
TVector similarTo,
[NotParameterized] string metric)
where T : class
where TVector : unmanaged
{
var queryableSource = (IQueryable)source;
var root = (EntityQueryRootExpression)queryableSource.Expression;
return queryableSource.Provider is EntityQueryProvider
? queryableSource.Provider.CreateQuery<VectorSearchResult<T>>(
Expression.Call(
// Note that the method used is the one below, accepting IQueryable<T>, not DbSet<T>
method: new Func<IQueryable<T>, Expression<Func<T, TVector>>, TVector, string, IQueryable<VectorSearchResult<T>>>(VectorSearch).Method,
root,
Expression.Quote(vectorPropertySelector),
Expression.Constant(similarTo),
Expression.Constant(metric)))
: throw new InvalidOperationException(CoreStrings.FunctionOnNonEfLinqProvider(nameof(VectorSearch)));
}
// A separate method stub is required since the public method accepts DbSet (to limit to direct usage on DbSets),
// but the MethodCallExpression built above needs to accept an EntityQueryRootExpression (which is what we get for
// a DbSet, but which isn't itself a DbSet).
[Experimental(EFDiagnostics.SqlServerVectorSearch)]
private static IQueryable<VectorSearchResult<T>> VectorSearch<T, TVector>(
this IQueryable<T> source,
Expression<Func<T, TVector>> vectorPropertySelector,
TVector similarTo,
[NotParameterized] string metric)
where T : class
where TVector : unmanaged
=> throw new UnreachableException();
#endregion VectorSearch
#region Full-text search TVFs
/// <summary>
/// Queries a full-text index using the SQL Server <c>FREETEXTTABLE</c> function.
/// </summary>
/// <typeparam name="T">The entity type being queried.</typeparam>
/// <typeparam name="TKey">The type of the full-text key column.</typeparam>
/// <param name="source">The <see cref="DbSet{T}" /> representing the table with the full-text index.</param>
/// <param name="freeText">The text to search for.</param>
/// <param name="columnSelector">
/// An optional selector for the column(s) to search. Can be a single property (e.g., <c>e => e.Title</c>)
/// or multiple properties via an anonymous type (e.g., <c>e => new { e.Title, e.Body }</c>).
/// When omitted, all full-text indexed columns are searched.
/// </param>
/// <param name="languageTerm">Optional language term from <c>sys.syslanguages</c> for word-breaking.</param>
/// <param name="topN">Optional maximum number of results to return.</param>
/// <returns>An <see cref="IQueryable{T}" /> of <see cref="FullTextSearchResult{TKey}" /> containing the key and rank of matching rows.</returns>
/// <remarks>
/// <para>
/// Use the <see cref="FullTextSearchResult{TKey}.Key" /> property to join back to the original table
/// to retrieve the full entity data.
/// </para>
/// <para>
/// See <see href="https://learn.microsoft.com/sql/relational-databases/system-functions/freetexttable-transact-sql">
/// SQL Server documentation for <c>FREETEXTTABLE</c></see> for more information.
/// </para>
/// </remarks>
public static IQueryable<FullTextSearchResult<TKey>> FreeTextTable<T, TKey>(
this DbSet<T> source,
string freeText,
Expression<Func<T, object>>? columnSelector = null,
[NotParameterized] string? languageTerm = null,
int? topN = null)
where T : class
{
var queryableSource = (IQueryable)source;
var root = (EntityQueryRootExpression)queryableSource.Expression;
if (queryableSource.Provider is not EntityQueryProvider)
{
throw new InvalidOperationException(CoreStrings.FunctionOnNonEfLinqProvider(nameof(FreeTextTable)));
}
return columnSelector is null
? queryableSource.Provider.CreateQuery<FullTextSearchResult<TKey>>(
Expression.Call(
method: new Func<
IQueryable<T>,
string,
string?,
int?,
IQueryable<FullTextSearchResult<TKey>>>(FreeTextTable<T, TKey>).Method,
root,
Expression.Constant(freeText),
Expression.Constant(languageTerm, typeof(string)),
Expression.Constant(topN, typeof(int?))))
: queryableSource.Provider.CreateQuery<FullTextSearchResult<TKey>>(
Expression.Call(
method: new Func<
IQueryable<T>,
Expression<Func<T, object>>, string, string?, int?,
IQueryable<FullTextSearchResult<TKey>>>(FreeTextTable<T, TKey>).Method,
root,
Expression.Quote(columnSelector),
Expression.Constant(freeText),
Expression.Constant(languageTerm, typeof(string)),
Expression.Constant(topN, typeof(int?))));
}
// A separate method stub is required since the public method accepts DbSet (to limit to direct usage on DbSets),
// but the MethodCallExpression built above needs to accept an EntityQueryRootExpression (which is what we get for
// a DbSet, but which isn't itself a DbSet).
private static IQueryable<FullTextSearchResult<TKey>> FreeTextTable<T, TKey>(
this IQueryable<T> source,
Expression<Func<T, object>> columnSelector,
string freeText,
[NotParameterized] string? languageTerm,
int? topN)
where T : class
=> throw new UnreachableException();
private static IQueryable<FullTextSearchResult<TKey>> FreeTextTable<T, TKey>(
this IQueryable<T> source,
string freeText,
[NotParameterized] string? languageTerm,
int? topN)
where T : class
=> throw new UnreachableException();
/// <summary>
/// Queries a full-text index using the SQL Server <c>CONTAINSTABLE</c> function.
/// </summary>
/// <typeparam name="T">The entity type being queried.</typeparam>
/// <typeparam name="TKey">The type of the full-text key column.</typeparam>
/// <param name="source">The <see cref="DbSet{T}" /> representing the table with the full-text index.</param>
/// <param name="searchCondition">The search condition, supporting full-text predicates like <c>AND</c>, <c>OR</c>, <c>NEAR</c>, etc.</param>
/// <param name="columnSelector">
/// An optional selector for the column(s) to search. Can be a single property (e.g., <c>e => e.Title</c>)
/// or multiple properties via an anonymous type (e.g., <c>e => new { e.Title, e.Body }</c>).
/// When omitted, all full-text indexed columns are searched.
/// </param>
/// <param name="languageTerm">Optional language term from <c>sys.syslanguages</c> for word-breaking.</param>
/// <param name="topN">Optional maximum number of results to return.</param>
/// <returns>An <see cref="IQueryable{T}" /> of <see cref="FullTextSearchResult{TKey}" /> containing the key and rank of matching rows.</returns>
/// <remarks>
/// <para>
/// Use the <see cref="FullTextSearchResult{TKey}.Key" /> property to join back to the original table
/// to retrieve the full entity data.
/// </para>
/// <para>
/// See <see href="https://learn.microsoft.com/sql/relational-databases/system-functions/containstable-transact-sql">
/// SQL Server documentation for <c>CONTAINSTABLE</c></see> for more information.
/// </para>
/// </remarks>
public static IQueryable<FullTextSearchResult<TKey>> ContainsTable<T, TKey>(
this DbSet<T> source,
string searchCondition,
Expression<Func<T, object>>? columnSelector = null,
[NotParameterized] string? languageTerm = null,
int? topN = null)
where T : class
{
var queryableSource = (IQueryable)source;
var root = (EntityQueryRootExpression)queryableSource.Expression;
if (queryableSource.Provider is not EntityQueryProvider)
{
throw new InvalidOperationException(CoreStrings.FunctionOnNonEfLinqProvider(nameof(ContainsTable)));
}
return columnSelector is null
? queryableSource.Provider.CreateQuery<FullTextSearchResult<TKey>>(
Expression.Call(
method: new Func<IQueryable<T>, string, string?, int?, IQueryable<FullTextSearchResult<TKey>>>(ContainsTable<T, TKey>).Method,
root,
Expression.Constant(searchCondition),
Expression.Constant(languageTerm, typeof(string)),
Expression.Constant(topN, typeof(int?))))
: queryableSource.Provider.CreateQuery<FullTextSearchResult<TKey>>(
Expression.Call(
method: new Func<IQueryable<T>, Expression<Func<T, object>>, string, string?, int?, IQueryable<FullTextSearchResult<TKey>>>(ContainsTable<T, TKey>).Method,
root,
Expression.Quote(columnSelector),
Expression.Constant(searchCondition),
Expression.Constant(languageTerm, typeof(string)),
Expression.Constant(topN, typeof(int?))));
}
private static IQueryable<FullTextSearchResult<TKey>> ContainsTable<T, TKey>(
this IQueryable<T> source,
Expression<Func<T, object>> columnSelector,
string searchCondition,
[NotParameterized] string? languageTerm,
int? topN)
where T : class
=> throw new UnreachableException();
private static IQueryable<FullTextSearchResult<TKey>> ContainsTable<T, TKey>(
this IQueryable<T> source,
string searchCondition,
[NotParameterized] string? languageTerm,
int? topN)
where T : class
=> throw new UnreachableException();
#endregion Full-text search TVFs
}