|
| 1 | +// Copyright (c) Microsoft. All rights reserved. |
| 2 | + |
| 3 | +using System; |
| 4 | +using System.Collections; |
| 5 | +using System.Collections.Generic; |
| 6 | +using System.Diagnostics; |
| 7 | +using System.Diagnostics.CodeAnalysis; |
| 8 | +using System.Linq; |
| 9 | +using System.Linq.Expressions; |
| 10 | +using System.Reflection; |
| 11 | +using System.Runtime.CompilerServices; |
| 12 | +using Pinecone; |
| 13 | + |
| 14 | +namespace Microsoft.SemanticKernel.Connectors.Pinecone; |
| 15 | + |
| 16 | +// This class is a modification of MongoDBFilterTranslator that uses the same query language |
| 17 | +// (https://docs.pinecone.io/guides/data/understanding-metadata#metadata-query-language), |
| 18 | +// with the difference of representing everything as Metadata rather than BsonDocument. |
| 19 | +// For representing collections of any kinds, we use List<MetadataValue>, |
| 20 | +// as we sometimes need to extend the collection (with for example another condition). |
| 21 | +internal class PineconeFilterTranslator |
| 22 | +{ |
| 23 | + private IReadOnlyDictionary<string, string> _storagePropertyNames = null!; |
| 24 | + private ParameterExpression _recordParameter = null!; |
| 25 | + |
| 26 | + internal Metadata Translate(LambdaExpression lambdaExpression, IReadOnlyDictionary<string, string> storagePropertyNames) |
| 27 | + { |
| 28 | + this._storagePropertyNames = storagePropertyNames; |
| 29 | + |
| 30 | + Debug.Assert(lambdaExpression.Parameters.Count == 1); |
| 31 | + this._recordParameter = lambdaExpression.Parameters[0]; |
| 32 | + |
| 33 | + return this.Translate(lambdaExpression.Body); |
| 34 | + } |
| 35 | + |
| 36 | + private Metadata Translate(Expression? node) |
| 37 | + => node switch |
| 38 | + { |
| 39 | + BinaryExpression |
| 40 | + { |
| 41 | + NodeType: ExpressionType.Equal or ExpressionType.NotEqual |
| 42 | + or ExpressionType.GreaterThan or ExpressionType.GreaterThanOrEqual |
| 43 | + or ExpressionType.LessThan or ExpressionType.LessThanOrEqual |
| 44 | + } binary |
| 45 | + => this.TranslateEqualityComparison(binary), |
| 46 | + |
| 47 | + BinaryExpression { NodeType: ExpressionType.AndAlso or ExpressionType.OrElse } andOr |
| 48 | + => this.TranslateAndOr(andOr), |
| 49 | + UnaryExpression { NodeType: ExpressionType.Not } not |
| 50 | + => this.TranslateNot(not), |
| 51 | + |
| 52 | + // MemberExpression is generally handled within e.g. TranslateEqualityComparison; this is used to translate direct bool inside filter (e.g. Filter => r => r.Bool) |
| 53 | + MemberExpression member when member.Type == typeof(bool) && this.TryTranslateFieldAccess(member, out _) |
| 54 | + => this.TranslateEqualityComparison(Expression.Equal(member, Expression.Constant(true))), |
| 55 | + |
| 56 | + MethodCallExpression methodCall => this.TranslateMethodCall(methodCall), |
| 57 | + |
| 58 | + _ => throw new NotSupportedException("The following NodeType is unsupported: " + node?.NodeType) |
| 59 | + }; |
| 60 | + |
| 61 | + private Metadata TranslateEqualityComparison(BinaryExpression binary) |
| 62 | + { |
| 63 | + if ((this.TryTranslateFieldAccess(binary.Left, out var storagePropertyName) && TryGetConstant(binary.Right, out var value)) |
| 64 | + || (this.TryTranslateFieldAccess(binary.Right, out storagePropertyName) && TryGetConstant(binary.Left, out value))) |
| 65 | + { |
| 66 | + if (value is null) |
| 67 | + { |
| 68 | + throw new NotSupportedException("Pincone does not support null checks in vector search pre-filters"); |
| 69 | + } |
| 70 | + |
| 71 | + // Short form of equality (instead of $eq) |
| 72 | + if (binary.NodeType is ExpressionType.Equal) |
| 73 | + { |
| 74 | + return new Metadata { [storagePropertyName] = ToMetadata(value) }; |
| 75 | + } |
| 76 | + |
| 77 | + var filterOperator = binary.NodeType switch |
| 78 | + { |
| 79 | + ExpressionType.NotEqual => "$ne", |
| 80 | + ExpressionType.GreaterThan => "$gt", |
| 81 | + ExpressionType.GreaterThanOrEqual => "$gte", |
| 82 | + ExpressionType.LessThan => "$lt", |
| 83 | + ExpressionType.LessThanOrEqual => "$lte", |
| 84 | + |
| 85 | + _ => throw new UnreachableException() |
| 86 | + }; |
| 87 | + |
| 88 | + return new Metadata { [storagePropertyName] = new Metadata { [filterOperator] = ToMetadata(value) } }; |
| 89 | + } |
| 90 | + |
| 91 | + throw new NotSupportedException("Invalid equality/comparison"); |
| 92 | + } |
| 93 | + |
| 94 | + private Metadata TranslateAndOr(BinaryExpression andOr) |
| 95 | + { |
| 96 | + var mongoOperator = andOr.NodeType switch |
| 97 | + { |
| 98 | + ExpressionType.AndAlso => "$and", |
| 99 | + ExpressionType.OrElse => "$or", |
| 100 | + _ => throw new UnreachableException() |
| 101 | + }; |
| 102 | + |
| 103 | + var (left, right) = (this.Translate(andOr.Left), this.Translate(andOr.Right)); |
| 104 | + |
| 105 | + List<MetadataValue?>? nestedLeft = GetListOrNull(left, mongoOperator); |
| 106 | + List<MetadataValue?>? nestedRight = GetListOrNull(right, mongoOperator); |
| 107 | + |
| 108 | + switch ((nestedLeft, nestedRight)) |
| 109 | + { |
| 110 | + case (not null, not null): |
| 111 | + nestedLeft.AddRange(nestedRight); |
| 112 | + return left; |
| 113 | + case (not null, null): |
| 114 | + nestedLeft.Add(right); |
| 115 | + return left; |
| 116 | + case (null, not null): |
| 117 | + nestedRight.Insert(0, left); |
| 118 | + return right; |
| 119 | + case (null, null): |
| 120 | + return new Metadata { [mongoOperator] = new MetadataValue(new List<MetadataValue?> { left, right }) }; |
| 121 | + } |
| 122 | + } |
| 123 | + |
| 124 | + private Metadata TranslateNot(UnaryExpression not) |
| 125 | + { |
| 126 | + switch (not.Operand) |
| 127 | + { |
| 128 | + // Special handling for !(a == b) and !(a != b) |
| 129 | + case BinaryExpression { NodeType: ExpressionType.Equal or ExpressionType.NotEqual } binary: |
| 130 | + return this.TranslateEqualityComparison( |
| 131 | + Expression.MakeBinary( |
| 132 | + binary.NodeType is ExpressionType.Equal ? ExpressionType.NotEqual : ExpressionType.Equal, |
| 133 | + binary.Left, |
| 134 | + binary.Right)); |
| 135 | + |
| 136 | + // Not over bool field (Filter => r => !r.Bool) |
| 137 | + case MemberExpression member when member.Type == typeof(bool) && this.TryTranslateFieldAccess(member, out _): |
| 138 | + return this.TranslateEqualityComparison(Expression.Equal(member, Expression.Constant(false))); |
| 139 | + } |
| 140 | + |
| 141 | + var operand = this.Translate(not.Operand); |
| 142 | + |
| 143 | + // Identify NOT over $in, transform to $nin (https://www.mongodb.com/docs/manual/reference/operator/query/nin/#mongodb-query-op.-nin) |
| 144 | + if (operand.Count == 1 && operand.First() is { Key: var fieldName, Value: MetadataValue nested } && nested.Value is Metadata nestedMetadata |
| 145 | + && GetListOrNull(nestedMetadata, "$in") is List<MetadataValue> values) |
| 146 | + { |
| 147 | + return new Metadata { [fieldName] = new Metadata { ["$nin"] = values } }; |
| 148 | + } |
| 149 | + |
| 150 | + throw new NotSupportedException("Pinecone does not support the NOT operator in vector search pre-filters"); |
| 151 | + } |
| 152 | + |
| 153 | + private Metadata TranslateMethodCall(MethodCallExpression methodCall) |
| 154 | + => methodCall switch |
| 155 | + { |
| 156 | + // Enumerable.Contains() |
| 157 | + { Method.Name: nameof(Enumerable.Contains), Arguments: [var source, var item] } contains |
| 158 | + when contains.Method.DeclaringType == typeof(Enumerable) |
| 159 | + => this.TranslateContains(source, item), |
| 160 | + |
| 161 | + // List.Contains() |
| 162 | + { |
| 163 | + Method: |
| 164 | + { |
| 165 | + Name: nameof(Enumerable.Contains), |
| 166 | + DeclaringType: { IsGenericType: true } declaringType |
| 167 | + }, |
| 168 | + Object: Expression source, |
| 169 | + Arguments: [var item] |
| 170 | + } when declaringType.GetGenericTypeDefinition() == typeof(List<>) => this.TranslateContains(source, item), |
| 171 | + |
| 172 | + _ => throw new NotSupportedException($"Unsupported method call: {methodCall.Method.DeclaringType?.Name}.{methodCall.Method.Name}") |
| 173 | + }; |
| 174 | + |
| 175 | + private Metadata TranslateContains(Expression source, Expression item) |
| 176 | + { |
| 177 | + switch (source) |
| 178 | + { |
| 179 | + // Contains over array column (r => r.Strings.Contains("foo")) |
| 180 | + case var _ when this.TryTranslateFieldAccess(source, out _): |
| 181 | + throw new NotSupportedException("Pinecone does not support Contains within array fields ($elemMatch) in vector search pre-filters"); |
| 182 | + |
| 183 | + // Contains over inline enumerable |
| 184 | + case NewArrayExpression newArray: |
| 185 | + var elements = new object?[newArray.Expressions.Count]; |
| 186 | + |
| 187 | + for (var i = 0; i < newArray.Expressions.Count; i++) |
| 188 | + { |
| 189 | + if (!TryGetConstant(newArray.Expressions[i], out var elementValue)) |
| 190 | + { |
| 191 | + throw new NotSupportedException("Invalid element in array"); |
| 192 | + } |
| 193 | + |
| 194 | + elements[i] = elementValue; |
| 195 | + } |
| 196 | + |
| 197 | + return ProcessInlineEnumerable(elements, item); |
| 198 | + |
| 199 | + // Contains over captured enumerable (we inline) |
| 200 | + case var _ when TryGetConstant(source, out var constantEnumerable) |
| 201 | + && constantEnumerable is IEnumerable enumerable and not string: |
| 202 | + return ProcessInlineEnumerable(enumerable, item); |
| 203 | + |
| 204 | + default: |
| 205 | + throw new NotSupportedException("Unsupported Contains expression"); |
| 206 | + } |
| 207 | + |
| 208 | + Metadata ProcessInlineEnumerable(IEnumerable elements, Expression item) |
| 209 | + { |
| 210 | + if (!this.TryTranslateFieldAccess(item, out var storagePropertyName)) |
| 211 | + { |
| 212 | + throw new NotSupportedException("Unsupported item type in Contains"); |
| 213 | + } |
| 214 | + |
| 215 | + return new Metadata |
| 216 | + { |
| 217 | + [storagePropertyName] = new Metadata |
| 218 | + { |
| 219 | + ["$in"] = new MetadataValue(elements.Cast<object>().Select(ToMetadata).ToList()) |
| 220 | + } |
| 221 | + }; |
| 222 | + } |
| 223 | + } |
| 224 | + |
| 225 | + private bool TryTranslateFieldAccess(Expression expression, [NotNullWhen(true)] out string? storagePropertyName) |
| 226 | + { |
| 227 | + if (expression is MemberExpression memberExpression && memberExpression.Expression == this._recordParameter) |
| 228 | + { |
| 229 | + if (!this._storagePropertyNames.TryGetValue(memberExpression.Member.Name, out storagePropertyName)) |
| 230 | + { |
| 231 | + throw new InvalidOperationException($"Property name '{memberExpression.Member.Name}' provided as part of the filter clause is not a valid property name."); |
| 232 | + } |
| 233 | + |
| 234 | + return true; |
| 235 | + } |
| 236 | + |
| 237 | + storagePropertyName = null; |
| 238 | + return false; |
| 239 | + } |
| 240 | + |
| 241 | + private static bool TryGetConstant(Expression expression, out object? constantValue) |
| 242 | + { |
| 243 | + switch (expression) |
| 244 | + { |
| 245 | + case ConstantExpression { Value: var v }: |
| 246 | + constantValue = v; |
| 247 | + return true; |
| 248 | + |
| 249 | + // This identifies compiler-generated closure types which contain captured variables. |
| 250 | + case MemberExpression { Expression: ConstantExpression constant, Member: FieldInfo fieldInfo } |
| 251 | + when constant.Type.Attributes.HasFlag(TypeAttributes.NestedPrivate) |
| 252 | + && Attribute.IsDefined(constant.Type, typeof(CompilerGeneratedAttribute), inherit: true): |
| 253 | + constantValue = fieldInfo.GetValue(constant.Value); |
| 254 | + return true; |
| 255 | + |
| 256 | + default: |
| 257 | + constantValue = null; |
| 258 | + return false; |
| 259 | + } |
| 260 | + } |
| 261 | + |
| 262 | + private static MetadataValue? ToMetadata(object? value) |
| 263 | + => value is null ? null : PineconeVectorStoreRecordFieldMapping.ConvertToMetadataValue(value); |
| 264 | + |
| 265 | + private static List<MetadataValue?>? GetListOrNull(Metadata value, string mongoOperator) |
| 266 | + => value.Count == 1 && value.First() is var element && element.Key == mongoOperator ? element.Value?.Value as List<MetadataValue?> : null; |
| 267 | +} |
0 commit comments