from typing import Union


def create_search_body(from_year: Union[str, None], to_year: Union[str, None], filter_fields: dict, size: int) -> dict:
    """Create a search body that is passed on to the elasticsearch 'search' method.

    :param from_year: Refers to published year, add to 'range'. Include results where published year >= from_year
    :param to_year: Refers to published year, add to 'rangen'. Include results where published year < to_year
    :param filter_fields: Add each field and their value in filter_fields as a filter term.
    :param size: The returned size (number of hits)
    :return: search body
    """
    filter_list = []
    for field in filter_fields:
        # add if value is not None
        if filter_fields[field]:
            filter_list.append({"terms": {f"{field}.keyword": filter_fields[field]}})
    if from_year or to_year:
        range_dict = {"range": {"published_year": {"format": "yyyy-MM-dd"}}}
        if from_year:
            range_dict["range"]["published_year"]["gte"] = from_year
        if to_year:
            range_dict["range"]["published_year"]["lt"] = to_year
        filter_list.append(range_dict)
    query_body = {"bool": {"filter": filter_list}}

    search_body = {"size": size, "query": query_body, "sort": ["_doc"]}
    return search_body