使用nosql排名在SQLalchemy中进行排序和分页

时间:2014-07-03 17:58:14

标签: python flask pagination sqlalchemy flask-sqlalchemy

我有一个python算法,它返回给定用户的数据库行的排名顺序。此算法输出主键ID列表(这些键可以与post.id连接)。它看起来像下面,除了可能有数千个匹配:

result_rank = [1286, 1956, 6759, 3485, 2309, 3409, 9023, 912, 13098, 23489, 19023, 1239]

我想指示sqlalchemy选择这些行,并按照它们在列表中的排序顺序排序。问题是,我希望在此

上执行pagination
results = posts.query().filter(posts.id.in_(
    resultIds)).order_by(??? how can I order by post.id = result_rank ???).paginate(page_num, posts_per_page)

我使用Postgresql作为数据库。

2 个答案:

答案 0 :(得分:1)

除非有一个好的解决方案,否则我将破解我自己的paginate对象:

class paginate_obj:

    """ Pagination dummy object. Takes a list and paginates it similar to sqlalchemy paginate() """
    def __init__(self, paginatable, page, per_page):
        self.has_next = (len(paginatable)/per_page) > page
        self.has_prev = bool(page - 1)
        self.next = page + self.has_next
        self.prev = page - self.has_prev
        self.items = paginatable[(page-1)*(per_page):(page)*(per_page)]

我认为排序的唯一方法是创建所有结果的列表,并根据一些lambda函数在python中对其进行排序:

results = my_table.query().all()
results.sort(key=lamba x: distance(x.lat, x.long, user_lat, user_long)
paginated_results = paginate_obj(results, 1, 10) #returns the first page of 10 elements

答案 1 :(得分:1)

我认为排序更重要,因为没有它,数据库级别的分页就完全没用了。注意到它后,我的回答根本没有涉及分页方面,但我认为即使是@mgoldwasser提供的答案也可用于此。

这是我想出的,以便能够根据初始过滤器列表选择一些对象并保留它们的顺序。代码是自我解释的:

# input
post_ids = [3, 4, 1]

# create helper (temporary in-query table with two columns: post_id, sort_order)
# this table looks like this:
# key | sort_order
#   3 |          0
#   4 |          1
#   1 |          2
q_subq = "\nUNION ALL\n".join(
    "SELECT {} AS key, {} AS sort_order".format(_id, i)
    for i, _id in enumerate(post_ids)
)

# wrap it in a `Selectable` so that we can use JOINs
s = (select([literal_column("key", Integer),
             literal_column("sort_order", Integer)])
     .select_from(text("({}) AS helper".format(text(q_subq))))
     ).alias("helper")

# actual query which is both the filter and sorter
q = (session.query(Post)
     .join(s, Post.id == s.c.key)  # INNER JOIN will filter implicitly
     .order_by(s.c.sort_order)  # apply sort order
     )

适用于postgresqlsqlite