'Serialize the search to a structure as passed for a search body.'

def serialize(self):

    res = {}
    if self.query:
        if isinstance(self.query, dict):
            res['query'] = self.query
        elif isinstance(self.query, Query):
            res['query'] = self.query.serialize()
        else:
            raise InvalidQuery('Invalid    query')
    if self.filter:
        res['filter'] = self.filter.serialize()
    if self.facet.facets:
        res['facets'] = self.facet.serialize()
    if self.agg.aggs:
        res['aggs'] = self.agg.serialize()
    if self.rescore:
        res['rescore'] = self.rescore.serialize()
    if self.window_size:
        res['window_size'] = self.window_size
    if (self.fields is not None):
        res['fields'] = self.fields
    if (self.size is not None):
        res['size'] = self.size
    if (self.start is not None):
        res['from'] = self.start
    if self._highlight:
        res['highlight'] = self._highlight.serialize()
    if self.sort:
        if isinstance(self.sort, SortFactory):
            sort = self.sort.serialize()
            if sort:
                res['sort'] = sort
        else:
            res['sort'] = self.sort
    if self.explain:
        res['explain'] = self.explain
    if self.version:
        res['version'] = self.version
    if self.track_scores:
        res['track_scores'] = self.track_scores
    if self._script_fields:
        if isinstance(self.script_fields, ScriptFields):
            res['script_fields'] = self.script_fields.serialize()
        elif isinstance(self.script_fields, dict):
            res['script_fields'] = self.script_fields
        else:
            raise ScriptFieldsError('Parameter    script_fields    should    of    type    ScriptFields    or    dict')
    if self.index_boost:
        res['indices_boost'] = self.index_boost
    if self.min_score:
        res['min_score'] = self.min_score
    if self.stats:
        res['stats'] = self.stats
    if self.partial_fields:
        res['partial_fields'] = self.partial_fields
    if self._source:
        res['_source'] = self._source
    if self.timeout:
        res['timeout'] = self.timeout
    return res
