Source code for elastipy.search

import json
from copy import copy, deepcopy
from typing import Optional, Union, Mapping, Callable, Sequence, List, Any

from elasticsearch import Elasticsearch, VERSION as ES_VERSION


from . import connections
from .aggregation import Aggregation, AggregationInterface, factory as agg_factory
from .query import QueryInterface, EmptyQuery, Query
from ._json import make_json_compatible





class Response(dict):
    """
    Simple wrapper around a dict with some elasticsearch response helper functions
    """

    @property
    def total_hits(self) -> int:
        total = self["hits"]["total"]
        if isinstance(total, dict):
            return total["value"]
        return total

    @property
    def aggregations(self) -> List[dict]:
        return self["aggregations"]

    @property
    def hits(self) -> List[dict]:
        """Returns the hits list"""
        return self["hits"]

    @property
    def documents(self) -> List[dict]:
        """Returns a list of all documents inside each hit"""
        return [
            doc["_source"]
            for doc in self["hits"]["hits"]
        ]

    @property
    def scores(self) -> List[float]:
        """Returns the list of scores of each hit"""
        return [
            hit["_score"]
            for hit in self["hits"]["hits"]
        ]

    @property
    def dump(self):
        from .response_dump import ResponseDump
        return ResponseDump(self)


def _to_query(query):
    if isinstance(getattr(query, "_query", None), QueryInterface):
        return query._query
    if isinstance(query, QueryInterface):
        return query
    raise ValueError(
        f"Expected Query, got {repr(query)}"
    )