|
| 1 | +class BaseConverter: |
| 2 | + """Base class for $expr to $match converters.""" |
| 3 | + |
| 4 | + @classmethod |
| 5 | + def convert(cls, expr): |
| 6 | + raise NotImplementedError("Subclasses must implement this method.") |
| 7 | + |
| 8 | + @classmethod |
| 9 | + def is_simple_value(cls, value): |
| 10 | + """Is the value is a simple type (not a dict)?""" |
| 11 | + if value is None: |
| 12 | + return True |
| 13 | + if isinstance(value, str) and value.startswith("$"): |
| 14 | + return False |
| 15 | + if isinstance(value, (list, tuple, set)): |
| 16 | + return all(cls.is_simple_value(v) for v in value) |
| 17 | + # TODO: Support `$getField` conversion. |
| 18 | + return not isinstance(value, dict) |
| 19 | + |
| 20 | + |
| 21 | +class BinaryConverter(BaseConverter): |
| 22 | + """ |
| 23 | + Base class for converting binary operations. |
| 24 | +
|
| 25 | + For example: |
| 26 | + "$expr": { |
| 27 | + {"$gt": ["$price", 100]} |
| 28 | + } |
| 29 | + is converted to: |
| 30 | + {"$gt": ["price", 100]} |
| 31 | + """ |
| 32 | + |
| 33 | + operator: str |
| 34 | + |
| 35 | + @classmethod |
| 36 | + def convert(cls, args): |
| 37 | + if isinstance(args, list) and len(args) == 2: |
| 38 | + field_expr, value = args |
| 39 | + # Check if first argument is a simple field reference. |
| 40 | + if ( |
| 41 | + isinstance(field_expr, str) |
| 42 | + and field_expr.startswith("$") |
| 43 | + and cls.is_simple_value(value) |
| 44 | + ): |
| 45 | + field_name = field_expr[1:] # Remove the $ prefix. |
| 46 | + if cls.operator == "$eq": |
| 47 | + return {field_name: value} |
| 48 | + return {field_name: {cls.operator: value}} |
| 49 | + return None |
| 50 | + |
| 51 | + |
| 52 | +class EqConverter(BinaryConverter): |
| 53 | + """ |
| 54 | + Convert $eq operation to a $match query. |
| 55 | +
|
| 56 | + For example: |
| 57 | + "$expr": { |
| 58 | + {"$eq": ["$status", "active"]} |
| 59 | + } |
| 60 | + is converted to: |
| 61 | + {"status": "active"} |
| 62 | + """ |
| 63 | + |
| 64 | + operator = "$eq" |
| 65 | + |
| 66 | + |
| 67 | +class GtConverter(BinaryConverter): |
| 68 | + operator = "$gt" |
| 69 | + |
| 70 | + |
| 71 | +class GteConverter(BinaryConverter): |
| 72 | + operator = "$gte" |
| 73 | + |
| 74 | + |
| 75 | +class LtConverter(BinaryConverter): |
| 76 | + operator = "$lt" |
| 77 | + |
| 78 | + |
| 79 | +class LteConverter(BinaryConverter): |
| 80 | + operator = "$lte" |
| 81 | + |
| 82 | + |
| 83 | +class InConverter(BaseConverter): |
| 84 | + """ |
| 85 | + Convert $in operation to a $match query. |
| 86 | +
|
| 87 | + For example: |
| 88 | + "$expr": { |
| 89 | + {"$in": ["$category", ["electronics", "books"]]} |
| 90 | + } |
| 91 | + is converted to: |
| 92 | + {"category": {"$in": ["electronics", "books"]}} |
| 93 | + """ |
| 94 | + |
| 95 | + @classmethod |
| 96 | + def convert(cls, in_args): |
| 97 | + if isinstance(in_args, list) and len(in_args) == 2: |
| 98 | + field_expr, values = in_args |
| 99 | + # Check if first argument is a simple field reference. |
| 100 | + if isinstance(field_expr, str) and field_expr.startswith("$"): |
| 101 | + field_name = field_expr[1:] # Remove the $ prefix. |
| 102 | + if isinstance(values, (list, tuple, set)) and all( |
| 103 | + cls.is_simple_value(v) for v in values |
| 104 | + ): |
| 105 | + return {field_name: {"$in": values}} |
| 106 | + return None |
| 107 | + |
| 108 | + |
| 109 | +class LogicalConverter(BaseConverter): |
| 110 | + """ |
| 111 | + Base class for converting logical operations to a $match query. |
| 112 | +
|
| 113 | + For example: |
| 114 | + "$expr": { |
| 115 | + "$or": [ |
| 116 | + {"$eq": ["$status", "active"]}, |
| 117 | + {"$in": ["$category", ["electronics", "books"]]}, |
| 118 | + ] |
| 119 | + } |
| 120 | + is converted to: |
| 121 | + "$or": [ |
| 122 | + {"status": "active"}, |
| 123 | + {"category": {"$in": ["electronics", "books"]}}, |
| 124 | + ] |
| 125 | + """ |
| 126 | + |
| 127 | + @classmethod |
| 128 | + def convert(cls, combined_conditions): |
| 129 | + if isinstance(combined_conditions, list): |
| 130 | + optimized_conditions = [] |
| 131 | + for condition in combined_conditions: |
| 132 | + if isinstance(condition, dict) and len(condition) == 1: |
| 133 | + if optimized_condition := convert_expression(condition): |
| 134 | + optimized_conditions.append(optimized_condition) |
| 135 | + else: |
| 136 | + # Any failure should stop optimization. |
| 137 | + return None |
| 138 | + if optimized_conditions: |
| 139 | + return {cls._logical_op: optimized_conditions} |
| 140 | + return None |
| 141 | + |
| 142 | + |
| 143 | +class OrConverter(LogicalConverter): |
| 144 | + _logical_op = "$or" |
| 145 | + |
| 146 | + |
| 147 | +class AndConverter(LogicalConverter): |
| 148 | + _logical_op = "$and" |
| 149 | + |
| 150 | + |
| 151 | +OPTIMIZABLE_OPS = { |
| 152 | + "$eq": EqConverter, |
| 153 | + "$in": InConverter, |
| 154 | + "$and": AndConverter, |
| 155 | + "$or": OrConverter, |
| 156 | + "$gt": GtConverter, |
| 157 | + "$gte": GteConverter, |
| 158 | + "$lt": LtConverter, |
| 159 | + "$lte": LteConverter, |
| 160 | +} |
| 161 | + |
| 162 | + |
| 163 | +def convert_expression(expr): |
| 164 | + """ |
| 165 | + Optimize MQL by converting an $expr condition to $match. Return the $match |
| 166 | + MQL, or None if not optimizable. |
| 167 | + """ |
| 168 | + if isinstance(expr, dict) and len(expr) == 1: |
| 169 | + op = next(iter(expr.keys())) |
| 170 | + if op in OPTIMIZABLE_OPS: |
| 171 | + return OPTIMIZABLE_OPS[op].convert(expr[op]) |
| 172 | + return None |
0 commit comments