def find_nested_path(field, es_mapping):
    """
    Returns path to 'highest' level nested field, in other words the first field mapped with type=nested
    found by traversing the given field from the *top* level.

    This function relies on information about the structure of the es_mapping to extract
    the *path to the object who's mapping is nested*. The comments within this function try to explain
    that structure. This information is needed to construct nested queries (it is the path).
    It returns None if the given (sub)field is not a member of a type=nested mapped field.

    :param field: the *full path* to the field we are filtering/aggregating on.
                        For example: "experiments_in_set.biosample.biosource.individual.organism.name"
    :param es_mapping: dictionary representation of the es_mapping of the type we are searching on
    :return: path for nested query or None
    """
    location = es_mapping
    possible_nested_paths = []
    path = []
    for cursor in field.split('.'):
        if cursor == 'raw':  # if we get to this point we're definitely at a leaf and should stop
            break
        if cursor not in location:  # its possible we are at a sub-embedded object boundary. Check if it has properties.
            if 'properties' not in location:  # if it doesn't have properties, there's nowhere to go, so return None.
                return None
            location = location['properties']  # else move location forward, but do not add it to the PATH
        if cursor not in location:  # if we still don't see our 'level', we are not a nested field
            break   # accumulated path will be discarded (not added to possible_nested_paths)
        location = location[cursor]
        path.append(cursor)
        if location.get('type', None) == 'nested':  # this could be a path
            possible_nested_paths.append('.'.join(path))
    # the last path added is the closest in proximity to the field and thus is correct
    return possible_nested_paths[-1] if possible_nested_paths else None