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
|
# Licensed to Elasticsearch B.V. under one or more contributor
# license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright
# ownership. Elasticsearch B.V. licenses this file to you under
# the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import uuid
from datetime import date, datetime
from decimal import Decimal
from typing import Any, ClassVar, Dict, Tuple
from elastic_transport import JsonSerializer as _JsonSerializer
from elastic_transport import NdjsonSerializer as _NdjsonSerializer
from elastic_transport import Serializer as Serializer
from elastic_transport import TextSerializer as TextSerializer
from .exceptions import SerializationError
INTEGER_TYPES = ()
FLOAT_TYPES = (Decimal,)
TIME_TYPES = (date, datetime)
__all__ = [
"Serializer",
"JsonSerializer",
"TextSerializer",
"NdjsonSerializer",
"CompatibilityModeJsonSerializer",
"CompatibilityModeNdjsonSerializer",
"MapboxVectorTileSerializer",
]
try:
from elastic_transport import OrjsonSerializer as _OrjsonSerializer
__all__.append("OrjsonSerializer")
except ImportError:
_OrjsonSerializer = None # type: ignore[assignment,misc]
try:
import pyarrow as pa
__all__.append("PyArrowSerializer")
except ImportError:
pa = None
class JsonSerializer(_JsonSerializer):
mimetype: ClassVar[str] = "application/json"
def default(self, data: Any) -> Any:
if isinstance(data, TIME_TYPES):
# Little hack to avoid importing pandas but to not
# return 'NaT' string for pd.NaT as that's not a valid
# Elasticsearch date.
formatted_data = data.isoformat()
if formatted_data != "NaT":
return formatted_data
if isinstance(data, uuid.UUID):
return str(data)
elif isinstance(data, FLOAT_TYPES):
return float(data)
# This is kept for backwards compatibility even
# if 'INTEGER_TYPES' isn't used by default anymore.
elif INTEGER_TYPES and isinstance(data, INTEGER_TYPES):
return int(data)
# Special cases for numpy and pandas types
# These are expensive to import so we try them last.
serialized, value = _attempt_serialize_numpy_or_pandas(data)
if serialized:
return value
raise TypeError(f"Unable to serialize {data!r} (type: {type(data)})")
if _OrjsonSerializer is not None:
class OrjsonSerializer(JsonSerializer, _OrjsonSerializer):
def default(self, data: Any) -> Any:
return JsonSerializer.default(self, data)
class NdjsonSerializer(JsonSerializer, _NdjsonSerializer):
mimetype: ClassVar[str] = "application/x-ndjson"
def default(self, data: Any) -> Any:
return JsonSerializer.default(self, data)
class CompatibilityModeJsonSerializer(JsonSerializer):
mimetype: ClassVar[str] = "application/vnd.elasticsearch+json"
class CompatibilityModeNdjsonSerializer(NdjsonSerializer):
mimetype: ClassVar[str] = "application/vnd.elasticsearch+x-ndjson"
class MapboxVectorTileSerializer(Serializer):
mimetype: ClassVar[str] = "application/vnd.mapbox-vector-tile"
def loads(self, data: bytes) -> bytes:
return data
def dumps(self, data: bytes) -> bytes:
if isinstance(data, bytes):
return data
raise SerializationError(f"Cannot serialize {data!r} into a MapBox vector tile")
if pa is not None:
class PyArrowSerializer(Serializer):
"""PyArrow serializer for deserializing Arrow Stream data."""
mimetype: ClassVar[str] = "application/vnd.apache.arrow.stream"
def loads(self, data: bytes) -> pa.Table:
try:
with pa.ipc.open_stream(data) as reader:
return reader.read_all()
except pa.ArrowException as e:
raise SerializationError(
message=f"Unable to deserialize as Arrow stream: {data!r}",
errors=(e,),
)
def dumps(self, data: Any) -> bytes:
raise SerializationError(
message="Elasticsearch does not accept Arrow input data"
)
DEFAULT_SERIALIZERS: Dict[str, Serializer] = {
JsonSerializer.mimetype: JsonSerializer(),
MapboxVectorTileSerializer.mimetype: MapboxVectorTileSerializer(),
NdjsonSerializer.mimetype: NdjsonSerializer(),
CompatibilityModeJsonSerializer.mimetype: CompatibilityModeJsonSerializer(),
CompatibilityModeNdjsonSerializer.mimetype: CompatibilityModeNdjsonSerializer(),
}
if pa is not None:
DEFAULT_SERIALIZERS[PyArrowSerializer.mimetype] = PyArrowSerializer()
# Alias for backwards compatibility
JSONSerializer = JsonSerializer
def _attempt_serialize_numpy_or_pandas(data: Any) -> Tuple[bool, Any]:
"""Attempts to serialize a value from the numpy or pandas libraries.
This function is separate from JSONSerializer because the inner functions
are rewritten to be no-ops if either library isn't available to avoid
attempting to import and raising an ImportError over and over again.
Returns a tuple of (bool, Any) where the bool corresponds to whether
the second value contains a properly serialized value and thus
should be returned by JSONSerializer.default().
"""
serialized, value = _attempt_serialize_numpy(data)
if serialized:
return serialized, value
serialized, value = _attempt_serialize_pandas(data)
if serialized:
return serialized, value
return False, None
def _attempt_serialize_numpy(data: Any) -> Tuple[bool, Any]:
global _attempt_serialize_numpy
try:
import numpy as np
if isinstance(
data,
(
np.int_,
np.intc,
np.int8,
np.int16,
np.int32,
np.int64,
np.uint8,
np.uint16,
np.uint32,
np.uint64,
),
):
return True, int(data)
elif isinstance(
data,
(
np.float16,
np.float32,
np.float64,
),
):
return True, float(data)
elif isinstance(data, np.bool_):
return True, bool(data)
elif isinstance(data, np.datetime64):
return True, data.item().isoformat()
elif isinstance(data, np.ndarray):
return True, data.tolist()
except ImportError:
# Since we failed to import 'numpy' we don't want to try again.
_attempt_serialize_numpy = _attempt_serialize_noop
return False, None
def _attempt_serialize_pandas(data: Any) -> Tuple[bool, Any]:
global _attempt_serialize_pandas
try:
import pandas as pd
if isinstance(data, (pd.Series, pd.Categorical)):
return True, data.tolist()
elif isinstance(data, pd.Timestamp) and data is not getattr(pd, "NaT", None):
return True, data.isoformat()
elif data is getattr(pd, "NA", None):
return True, None
except ImportError:
# Since we failed to import 'pandas' we don't want to try again.
_attempt_serialize_pandas = _attempt_serialize_noop
return False, None
def _attempt_serialize_noop(data: Any) -> Tuple[bool, Any]: # noqa
# Short-circuit if the above functions can't import
# the corresponding library on the first attempt.
return False, None
|