Skip to content

Instantly share code, notes, and snippets.

@lribeiro
Created November 11, 2019 15:45
Show Gist options
  • Save lribeiro/7d9fbedf830a54685811f63dbbce9464 to your computer and use it in GitHub Desktop.
Save lribeiro/7d9fbedf830a54685811f63dbbce9464 to your computer and use it in GitHub Desktop.
Possible custom JSON Serializer to make Numpy and Elasticsearch play well together
from elasticsearch import Elasticsearch,JSONSerializer
import numpy as np
import json
class NumpyEncoder(JSONSerializer):
""" Special json encoder for numpy types """
def default(self, obj):
if isinstance(obj, (np.int_, np.intc, np.intp, np.int8,
np.int16, np.int32, np.int64, np.uint8,
np.uint16, np.uint32, np.uint64)):
return int(obj)
elif isinstance(obj, (np.float_, np.float16, np.float32,
np.float64)):
return float(obj)
elif isinstance(obj,(np.ndarray,)): #### This is the fix
return obj.tolist()
return JSONSerializer.default(self, obj)
es = Elasticsearch(
['localhost'], serializer=NumpyEncoder()
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment