import heapq


def get_topn_sql(dist_tbl, topn=1):
    """
    function: get the top N nearest vectors from each cluster center.
    :param dist_tbl: distance table structure
    :param topn: number of top nearest, default 1
    :return: index of top n nearest vectors
    """
    topn_index = []
    for c in dist_tbl:
        dist = heapq.nsmallest(topn, c.keys())  # top n index, the distance from center.
        idx = map(lambda x: c.get(x), dist)
        topn_index.extend(idx)

    return topn_index