forked from microsoft/semantic-kernel
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCosmosNoSqlCollectionQueryBuilder.cs
More file actions
262 lines (216 loc) · 10.1 KB
/
Copy pathCosmosNoSqlCollectionQueryBuilder.cs
File metadata and controls
262 lines (216 loc) · 10.1 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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
// Copyright (c) Microsoft. All rights reserved.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using Microsoft.Azure.Cosmos;
using Microsoft.Extensions.VectorData;
using Microsoft.Extensions.VectorData.ProviderServices;
namespace Microsoft.SemanticKernel.Connectors.CosmosNoSql;
/// <summary>
/// Contains helpers to build queries for Azure CosmosDB NoSQL.
/// </summary>
internal static class CosmosNoSqlCollectionQueryBuilder
{
/// <summary>
/// Builds <see cref="QueryDefinition"/> to get items from Azure CosmosDB NoSQL using vector search.
/// </summary>
public static QueryDefinition BuildSearchQuery<TRecord>(
object vector,
ICollection<string>? keywords,
CollectionModel model,
string vectorPropertyName,
string? distanceFunction,
string? textPropertyName,
string scorePropertyName,
Expression<Func<TRecord, bool>>? filter,
double? scoreThreshold,
int top,
int skip,
bool includeVectors)
{
Verify.NotNull(vector);
const string VectorVariableName = "@vector";
const string KeywordVariablePrefix = "@keyword";
var tableVariableName = CosmosNoSqlConstants.ContainerAlias;
IEnumerable<PropertyModel> projectionProperties = model.Properties;
if (!includeVectors)
{
projectionProperties = projectionProperties.Where(p => p is not VectorPropertyModel);
}
var fieldsArgument = projectionProperties.Select(p => GeneratePropertyAccess(tableVariableName, p.StorageName));
var vectorDistanceArgument = $"VectorDistance({GeneratePropertyAccess(tableVariableName, vectorPropertyName)}, {VectorVariableName})";
var vectorDistanceArgumentWithAlias = $"{vectorDistanceArgument} AS {scorePropertyName}";
var selectClauseArguments = string.Join(",", [.. fieldsArgument, vectorDistanceArgumentWithAlias]);
// Build filter object.
var (filterClause, filterParameters) = filter is not null
? new CosmosNoSqlFilterTranslator().Translate(filter, model)
: ((string?)null, new Dictionary<string, object?>());
var queryParameters = new Dictionary<string, object?>
{
// byte[] and ReadOnlyMemory<byte> are serialized as base64 by System.Text.Json, which causes problems for the VectorDistance function.
// Convert to int[] which serializes as a JSON array of numbers.
[VectorVariableName] = vector switch
{
ReadOnlyMemory<byte> byteMemory => ConvertToIntArray(byteMemory.Span),
_ => vector
}
};
string? fullTextScoreArgument = null;
if (textPropertyName is not null && keywords is not null)
{
var fullTextScoreBuilder = new StringBuilder();
fullTextScoreBuilder.Append($"FullTextScore({GeneratePropertyAccess(tableVariableName, textPropertyName)}");
var i = 0;
foreach (var keyword in keywords)
{
var paramName = $"{KeywordVariablePrefix}{i}";
fullTextScoreBuilder.Append(", ").Append(paramName);
queryParameters[paramName] = keyword;
i++;
}
fullTextScoreBuilder.Append(')');
fullTextScoreArgument = fullTextScoreBuilder.ToString();
}
var rankingArgument = fullTextScoreArgument is null ? vectorDistanceArgument : $"RANK RRF({vectorDistanceArgument}, {fullTextScoreArgument})";
// Add score threshold filter if specified.
// For similarity functions (CosineSimilarity, DotProductSimilarity), higher scores are better, so filter with >=.
// For distance functions (EuclideanDistance), lower scores are better, so filter with <=.
const string ScoreThresholdVariableName = "@scoreThreshold";
string? scoreThresholdClause = null;
if (scoreThreshold.HasValue)
{
var comparisonOperator = distanceFunction switch
{
Microsoft.Extensions.VectorData.DistanceFunction.CosineSimilarity => ">=",
Microsoft.Extensions.VectorData.DistanceFunction.DotProductSimilarity => ">=",
Microsoft.Extensions.VectorData.DistanceFunction.EuclideanDistance => "<=",
_ => throw new NotSupportedException($"Score threshold is not supported for distance function '{distanceFunction}'.")
};
scoreThresholdClause = $"{vectorDistanceArgument} {comparisonOperator} {ScoreThresholdVariableName}";
queryParameters[ScoreThresholdVariableName] = scoreThreshold.Value;
}
// If Offset is not configured, use Top parameter instead of Limit/Offset
// since it's more optimized. Hybrid search doesn't allow top to be passed as a parameter
// so directly add it to the query here.
var topArgument = skip == 0 ? $"TOP {top} " : string.Empty;
var builder = new StringBuilder();
builder.AppendLine($"SELECT {topArgument}{selectClauseArguments}");
builder.AppendLine($"FROM {tableVariableName}");
if (filterClause is not null || scoreThresholdClause is not null)
{
builder.Append("WHERE ");
if (filterClause is not null)
{
builder.Append(filterClause);
if (scoreThresholdClause is not null)
{
builder.Append(" AND ");
}
}
if (scoreThresholdClause is not null)
{
builder.Append(scoreThresholdClause);
}
builder.AppendLine();
}
builder.AppendLine($"ORDER BY {rankingArgument}");
if (string.IsNullOrEmpty(topArgument))
{
// Hybrid search doesn't allow offset and limit to be passed as parameters
// so directly add it to the query here.
builder.AppendLine($"OFFSET {skip} LIMIT {top}");
}
var queryDefinition = new QueryDefinition(builder.ToString());
if (filterParameters is { Count: > 0 })
{
queryParameters = queryParameters.Union(filterParameters).ToDictionary(k => k.Key, v => v.Value);
}
foreach (var queryParameter in queryParameters)
{
queryDefinition.WithParameter(queryParameter.Key, queryParameter.Value);
}
return queryDefinition;
}
internal static QueryDefinition BuildSearchQuery<TRecord>(
CollectionModel model,
string whereClause, Dictionary<string, object?> filterParameters,
FilteredRecordRetrievalOptions<TRecord> filterOptions,
int top)
{
var tableVariableName = CosmosNoSqlConstants.ContainerAlias;
IEnumerable<PropertyModel> projectionProperties = model.Properties;
if (!filterOptions.IncludeVectors)
{
projectionProperties = projectionProperties.Where(p => p is not VectorPropertyModel);
}
var fieldsArgument = projectionProperties.Select(field => GeneratePropertyAccess(tableVariableName, field.StorageName));
var selectClauseArguments = string.Join(",", [.. fieldsArgument]);
// If Offset is not configured, use Top parameter instead of Limit/Offset
// since it's more optimized.
var topArgument = filterOptions.Skip == 0 ? $"TOP {top} " : string.Empty;
var builder = new StringBuilder();
builder.AppendLine($"SELECT {topArgument}{selectClauseArguments}");
builder.AppendLine($"FROM {tableVariableName}");
builder.Append("WHERE ").AppendLine(whereClause);
var orderBy = filterOptions.OrderBy?.Invoke(new()).Values;
if (orderBy is { Count: > 0 })
{
builder.Append("ORDER BY ");
foreach (var sortInfo in orderBy)
{
builder
.Append(GeneratePropertyAccess(tableVariableName, model.GetDataOrKeyProperty(sortInfo.PropertySelector).StorageName))
.Append(sortInfo.Ascending ? " ASC," : " DESC,");
}
builder.Length--; // remove the last comma
builder.AppendLine();
}
if (string.IsNullOrEmpty(topArgument))
{
builder.AppendLine($"OFFSET {filterOptions.Skip} LIMIT {top}");
}
var queryDefinition = new QueryDefinition(builder.ToString());
foreach (var queryParameter in filterParameters)
{
queryDefinition.WithParameter(queryParameter.Key, queryParameter.Value);
}
return queryDefinition;
}
#region private
private static string GetStoragePropertyName(string propertyName, CollectionModel model)
{
if (!model.PropertyMap.TryGetValue(propertyName, out var property))
{
throw new InvalidOperationException($"Property name '{propertyName}' provided as part of the filter clause is not a valid property name.");
}
return property.StorageName;
}
/// <summary>
/// Escapes a JSON property name for use in Cosmos NoSQL SQL queries.
/// JSON property names within bracket notation need backslash and double-quote escaping.
/// </summary>
private static string EscapeJsonPropertyName(string propertyName)
=> propertyName.Replace(@"\", @"\\").Replace("\"", "\\\"");
/// <summary>
/// Generates a property access expression using bracket notation with proper escaping.
/// </summary>
private static string GeneratePropertyAccess(char alias, string propertyName)
=> $"{alias}[\"{EscapeJsonPropertyName(propertyName)}\"]";
/// <summary>
/// Converts a byte span to an int array.
/// This is needed because byte[] and ReadOnlyMemory<byte> are serialized as base64 by System.Text.Json,
/// which causes problems for the VectorDistance function.
/// </summary>
private static int[] ConvertToIntArray(ReadOnlySpan<byte> bytes)
{
var result = new int[bytes.Length];
for (var i = 0; i < bytes.Length; i++)
{
result[i] = bytes[i];
}
return result;
}
#endregion
}