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 18from ..utils import AttrDict, HitMeta 19 20 21class Hit(AttrDict): 22 def __init__(self, document): 23 data = {} 24 if "_source" in document: 25 data = document["_source"] 26 if "fields" in document: 27 data.update(document["fields"]) 28 29 super(Hit, self).__init__(data) 30 # assign meta as attribute and not as key in self._d_ 31 super(AttrDict, self).__setattr__("meta", HitMeta(document)) 32 33 def __getstate__(self): 34 # add self.meta since it is not in self.__dict__ 35 return super(Hit, self).__getstate__() + (self.meta,) 36 37 def __setstate__(self, state): 38 super(AttrDict, self).__setattr__("meta", state[-1]) 39 super(Hit, self).__setstate__(state[:-1]) 40 41 def __dir__(self): 42 # be sure to expose meta in dir(self) 43 return super(Hit, self).__dir__() + ["meta"] 44 45 def __repr__(self): 46 return "<Hit({}): {}>".format( 47 "/".join( 48 getattr(self.meta, key) for key in ("index", "id") if key in self.meta 49 ), 50 super(Hit, self).__repr__(), 51 ) 52