|
| 1 | +# Licensed to Elasticsearch B.V. under one or more contributor |
| 2 | +# license agreements. See the NOTICE file distributed with |
| 3 | +# this work for additional information regarding copyright |
| 4 | +# ownership. Elasticsearch B.V. licenses this file to you under |
| 5 | +# the Apache License, Version 2.0 (the "License"); you may |
| 6 | +# not use this file except in compliance with the License. |
| 7 | +# You may obtain a copy of the License at |
| 8 | +# |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, |
| 12 | +# software distributed under the License is distributed on an |
| 13 | +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 14 | +# KIND, either express or implied. See the License for the |
| 15 | +# specific language governing permissions and limitations |
| 16 | +# under the License. |
| 17 | + |
| 18 | +from typing import Any, ClassVar, Dict, Self, Tuple, Type |
| 19 | + |
| 20 | +from pydantic import BaseModel, Field, PrivateAttr |
| 21 | +from typing_extensions import Annotated, dataclass_transform |
| 22 | + |
| 23 | +from elasticsearch import dsl |
| 24 | + |
| 25 | + |
| 26 | +class _BaseModel(BaseModel): |
| 27 | + meta: Annotated[Dict[str, Any], dsl.mapped_field(exclude=True)] = Field(default={}) |
| 28 | + |
| 29 | + |
| 30 | +class BaseESModelMetaclass(type(BaseModel)): # type: ignore[misc] |
| 31 | + def __new__(cls, name: str, bases: Tuple[type, ...], attrs: Dict[str, Any]) -> Any: |
| 32 | + model = super().__new__(cls, name, bases, attrs) |
| 33 | + dsl_attrs = { |
| 34 | + attr: value |
| 35 | + for attr, value in dsl.AsyncDocument.__dict__.items() |
| 36 | + if not attr.startswith("__") |
| 37 | + } |
| 38 | + model._doc = type(dsl.AsyncDocument)( # type: ignore[misc] |
| 39 | + f"_ES{name}", |
| 40 | + dsl.AsyncDocument.__bases__, |
| 41 | + {**attrs, **dsl_attrs, "__qualname__": f"_ES{name}"}, |
| 42 | + ) |
| 43 | + return model |
| 44 | + |
| 45 | + |
| 46 | +@dataclass_transform(kw_only_default=True, field_specifiers=(Field, PrivateAttr)) |
| 47 | +class BaseESModel(_BaseModel, metaclass=BaseESModelMetaclass): |
| 48 | + _doc: ClassVar[Type[dsl.AsyncDocument]] |
| 49 | + |
| 50 | + def to_doc(self) -> dsl.AsyncDocument: |
| 51 | + data = self.model_dump() |
| 52 | + meta = {f"_{k}": v for k, v in data.pop("meta", {}).items()} |
| 53 | + return self._doc(**meta, **data) |
| 54 | + |
| 55 | + @classmethod |
| 56 | + def from_doc(cls, dsl_obj: dsl.AsyncDocument) -> Self: |
| 57 | + return cls(meta=dsl_obj.meta.to_dict(), **dsl_obj.to_dict()) |
0 commit comments