|
| 1 | +/* |
| 2 | + * Copyright 2023-present the original author or authors. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * https://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package org.springframework.ai.vectorstore; |
| 18 | + |
| 19 | +import java.time.ZoneOffset; |
| 20 | +import java.time.format.DateTimeFormatter; |
| 21 | +import java.util.Date; |
| 22 | +import java.util.List; |
| 23 | +import java.util.Map; |
| 24 | +import java.util.Objects; |
| 25 | + |
| 26 | +import org.jspecify.annotations.Nullable; |
| 27 | + |
| 28 | +import org.springframework.ai.vectorstore.filter.Filter; |
| 29 | +import org.springframework.ai.vectorstore.filter.FilterExpressionBuilder; |
| 30 | + |
| 31 | +/** |
| 32 | + * Internal helper used by {@link SimpleVectorStore} to evaluate a |
| 33 | + * {@link Filter.Expression} AST directly against a document metadata map, without |
| 34 | + * converting to an intermediate string representation (e.g. SpEL or SQL). |
| 35 | + * |
| 36 | + * <p> |
| 37 | + * Supports all {@link Filter.ExpressionType} operations: |
| 38 | + * <ul> |
| 39 | + * <li>Logical: {@code AND}, {@code OR}, {@code NOT}</li> |
| 40 | + * <li>Comparison: {@code EQ}, {@code NE}, {@code GT}, {@code GTE}, {@code LT}, |
| 41 | + * {@code LTE}</li> |
| 42 | + * <li>Collection: {@code IN}, {@code NIN}</li> |
| 43 | + * <li>Null checks: {@code ISNULL}, {@code ISNOTNULL}</li> |
| 44 | + * </ul> |
| 45 | + * |
| 46 | + * <p> |
| 47 | + * <b>Type handling:</b> Numbers are promoted to {@code double} so that mixed |
| 48 | + * {@code Integer}/{@code Long}/{@code Double} metadata values compare correctly. |
| 49 | + * {@link Date} filter values are normalised to their ISO-8601 UTC string representation |
| 50 | + * (matching the format used to store dates in metadata). |
| 51 | + * |
| 52 | + * <p> |
| 53 | + * <b>Missing-key semantics:</b> A metadata key that is absent is treated as {@code null}. |
| 54 | + * Null ordering follows SQL {@code NULLS FIRST} semantics — {@code null} is considered |
| 55 | + * less than any non-null value. Consequently, ordered comparisons ({@code GT}, |
| 56 | + * {@code GTE}, {@code LT}, {@code LTE}) against a missing key evaluate as if that key |
| 57 | + * holds the smallest possible value (e.g. {@code year > 2020} returns {@code false} when |
| 58 | + * {@code year} is absent). |
| 59 | + * |
| 60 | + * @author Christian Tzolov |
| 61 | + */ |
| 62 | +final class SimpleVectorStoreFilterExpressionEvaluator { |
| 63 | + |
| 64 | + // 'Z' is intentionally a literal suffix, not the offset pattern 'X'. Combined with |
| 65 | + // withZone(UTC) this always produces the fixed form "yyyy-MM-dd'T'HH:mm:ss'Z'", |
| 66 | + // matching the format used to store Date values in document metadata. |
| 67 | + private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'") |
| 68 | + .withZone(ZoneOffset.UTC); |
| 69 | + |
| 70 | + /** |
| 71 | + * Evaluates the given filter expression against the provided metadata map. |
| 72 | + * @param expression the filter expression to evaluate; must not be {@code null} |
| 73 | + * @param metadata the document metadata to match against; must not be {@code null} |
| 74 | + * @return {@code true} if the metadata satisfies the expression |
| 75 | + */ |
| 76 | + public boolean evaluate(Filter.Expression expression, Map<String, Object> metadata) { |
| 77 | + return evaluateExpression(expression, metadata); |
| 78 | + } |
| 79 | + |
| 80 | + private boolean evaluateOperand(Filter.Operand operand, Map<String, Object> metadata) { |
| 81 | + if (operand instanceof Filter.Group group) { |
| 82 | + return evaluateOperand(group.content(), metadata); |
| 83 | + } |
| 84 | + if (operand instanceof Filter.Expression expression) { |
| 85 | + return evaluateExpression(expression, metadata); |
| 86 | + } |
| 87 | + // Filter.Key and Filter.Value are leaf operands consumed directly by |
| 88 | + // metadataValue() and filterValue() inside evaluateExpression(). They are never |
| 89 | + // passed here as top-level boolean operands, so this branch is unreachable under |
| 90 | + // normal usage. |
| 91 | + throw new IllegalArgumentException("Unsupported operand type: " + operand.getClass().getName()); |
| 92 | + } |
| 93 | + |
| 94 | + private boolean evaluateExpression(Filter.Expression expression, Map<String, Object> metadata) { |
| 95 | + return switch (expression.type()) { |
| 96 | + case AND -> evaluateOperand(left(expression), metadata) && evaluateOperand(right(expression), metadata); |
| 97 | + case OR -> evaluateOperand(left(expression), metadata) || evaluateOperand(right(expression), metadata); |
| 98 | + // Unary operator: only the left operand is used. Ignore right operand |
| 99 | + case NOT -> !evaluateOperand(left(expression), metadata); |
| 100 | + case EQ -> compare(metadataValue(left(expression), metadata), filterValue(right(expression))) == 0; |
| 101 | + case NE -> compare(metadataValue(left(expression), metadata), filterValue(right(expression))) != 0; |
| 102 | + case GT -> compare(metadataValue(left(expression), metadata), filterValue(right(expression))) > 0; |
| 103 | + case GTE -> compare(metadataValue(left(expression), metadata), filterValue(right(expression))) >= 0; |
| 104 | + case LT -> compare(metadataValue(left(expression), metadata), filterValue(right(expression))) < 0; |
| 105 | + case LTE -> compare(metadataValue(left(expression), metadata), filterValue(right(expression))) <= 0; |
| 106 | + case IN -> { |
| 107 | + Object metaVal = metadataValue(left(expression), metadata); |
| 108 | + List<?> list = asList(filterValue(right(expression)), expression); |
| 109 | + yield list.stream().anyMatch(item -> compare(metaVal, item) == 0); |
| 110 | + } |
| 111 | + case NIN -> { |
| 112 | + Object metaVal = metadataValue(left(expression), metadata); |
| 113 | + List<?> list = asList(filterValue(right(expression)), expression); |
| 114 | + yield list.stream().noneMatch(item -> compare(metaVal, item) == 0); |
| 115 | + } |
| 116 | + // Unary operators: only the left operand (the key) is used. |
| 117 | + // A non-null right operand is silently ignored here. |
| 118 | + case ISNULL -> metadataValue(left(expression), metadata) == null; |
| 119 | + case ISNOTNULL -> metadataValue(left(expression), metadata) != null; |
| 120 | + }; |
| 121 | + } |
| 122 | + |
| 123 | + private Filter.Operand left(Filter.Expression expression) { |
| 124 | + Filter.Operand left = expression.left(); |
| 125 | + if (left == null) { |
| 126 | + throw new IllegalArgumentException( |
| 127 | + "Expression of type %s requires a left operand".formatted(expression.type())); |
| 128 | + } |
| 129 | + return left; |
| 130 | + } |
| 131 | + |
| 132 | + private Filter.Operand right(Filter.Expression expression) { |
| 133 | + Filter.Operand right = expression.right(); |
| 134 | + if (right == null) { |
| 135 | + throw new IllegalArgumentException( |
| 136 | + "Expression of type %s requires a right operand".formatted(expression.type())); |
| 137 | + } |
| 138 | + return right; |
| 139 | + } |
| 140 | + |
| 141 | + /** |
| 142 | + * Extracts the metadata value for the given {@link Filter.Key} operand. Outer quotes |
| 143 | + * ({@code "..."} or {@code '...'}) are stripped from the key name to match the format |
| 144 | + * used by {@link FilterExpressionBuilder} and the text parser. |
| 145 | + */ |
| 146 | + private @Nullable Object metadataValue(Filter.Operand operand, Map<String, Object> metadata) { |
| 147 | + if (operand instanceof Filter.Key key) { |
| 148 | + String k = key.key(); |
| 149 | + if (k.length() >= 2 |
| 150 | + && ((k.startsWith("\"") && k.endsWith("\"")) || (k.startsWith("'") && k.endsWith("'")))) { |
| 151 | + k = k.substring(1, k.length() - 1); |
| 152 | + } |
| 153 | + return metadata.get(k); |
| 154 | + } |
| 155 | + throw new IllegalArgumentException("Expected a Key operand but got: " + operand.getClass().getName()); |
| 156 | + } |
| 157 | + |
| 158 | + /** |
| 159 | + * Extracts the constant value from a {@link Filter.Value} operand. {@link Date} |
| 160 | + * instances are formatted to their ISO-8601 UTC string so they can be compared |
| 161 | + * directly with metadata strings stored in the same format. |
| 162 | + */ |
| 163 | + private Object filterValue(Filter.Operand operand) { |
| 164 | + if (operand instanceof Filter.Value filterValue) { |
| 165 | + Object value = filterValue.value(); |
| 166 | + return (value instanceof Date date) ? DATE_FORMATTER.format(date.toInstant()) : value; |
| 167 | + } |
| 168 | + throw new IllegalArgumentException("Expected a Value operand but got: " + operand.getClass().getName()); |
| 169 | + } |
| 170 | + |
| 171 | + /** |
| 172 | + * Compares two values. Numbers are promoted to {@code double} to allow cross-type |
| 173 | + * numeric comparison (e.g. {@code Integer} vs {@code Double}). All other |
| 174 | + * {@link Comparable} types are compared directly. |
| 175 | + * |
| 176 | + * <p> |
| 177 | + * Null ordering follows SQL {@code NULLS FIRST} semantics: {@code null} is considered |
| 178 | + * less than any non-null value. As a result, a missing metadata key causes ordered |
| 179 | + * comparisons ({@code GT}, {@code GTE}, {@code LT}, {@code LTE}) to behave as if the |
| 180 | + * key holds the smallest possible value — e.g. {@code year > 2020} returns |
| 181 | + * {@code false} when {@code year} is absent. |
| 182 | + */ |
| 183 | + @SuppressWarnings("unchecked") |
| 184 | + private int compare(@Nullable Object metaVal, @Nullable Object filterVal) { |
| 185 | + if (metaVal == null && filterVal == null) { |
| 186 | + return 0; |
| 187 | + } |
| 188 | + if (metaVal == null) { |
| 189 | + return -1; |
| 190 | + } |
| 191 | + if (filterVal == null) { |
| 192 | + return 1; |
| 193 | + } |
| 194 | + if (metaVal instanceof Number n1 && filterVal instanceof Number n2) { |
| 195 | + return Double.compare(n1.doubleValue(), n2.doubleValue()); |
| 196 | + } |
| 197 | + if (Objects.equals(metaVal, filterVal)) { |
| 198 | + return 0; |
| 199 | + } |
| 200 | + if (metaVal instanceof Comparable comparable && filterVal instanceof Comparable) { |
| 201 | + try { |
| 202 | + return comparable.compareTo(filterVal); |
| 203 | + } |
| 204 | + catch (ClassCastException ex) { |
| 205 | + throw new IllegalArgumentException("Cannot compare values of incompatible types %s and %s" |
| 206 | + .formatted(metaVal.getClass().getName(), filterVal.getClass().getName()), ex); |
| 207 | + } |
| 208 | + } |
| 209 | + throw new IllegalArgumentException("Cannot compare values of types %s and %s" |
| 210 | + .formatted(metaVal.getClass().getName(), filterVal.getClass().getName())); |
| 211 | + } |
| 212 | + |
| 213 | + private List<?> asList(Object value, Filter.Expression expression) { |
| 214 | + if (value instanceof List<?> list) { |
| 215 | + return list; |
| 216 | + } |
| 217 | + throw new IllegalArgumentException( |
| 218 | + "Expected a List value for %s expression but got: %s".formatted(expression.type(), value)); |
| 219 | + } |
| 220 | + |
| 221 | +} |
0 commit comments