1

因此,这是我在 Python 2.7 中使用最新的 RethinkDB (1.14) 编写的一些代码的有趣简化片段。我的问题是现在我需要添加另一个条件,并且可能的组合太多了。这可以在单个过滤器语句中完成吗?

query = r.table('messages').order_by(r.desc('created'))
if tag is not None and read is not None:
    query = query.filter(lambda n: (n['user_id'] == user_id) &
                           (n['tags'].contains(tag)) &
                           (n['read'] == read))
elif read is not None:
    query = query.filter(lambda n: (n['user_id'] == user_id) &
                           (n['read'] == read))
elif tag is not None:
    query = query.filter(lambda n: (n['user_id'] == user_id) &
                           (n['tags'].contains(tag)))
else:
    query = query.filter(lambda n: n['user_id'] == user_id)
fields_list = query.skip(skip)\
                   .limit(limit)\
                   .run(g.db_conn)

附带说明一下,如果链式过滤器有效,这将容易得多,基本上充当and. 但目前看来,每个 RethinkDB 查询只能有一个过滤器。

编辑:不确定之前发生了什么,但链接过滤器确实有效。

4

1 回答 1

1

Turns out this actually works!

def _(n):
    return (n['user_id'] == user_id) & \
           (n['tags'].contains(tag) if tag is not None else True) & \
           (n['read'] == read if read is not None else True)
query = r.table('messages') \
         .order_by(r.desc('created')) \
         .filter(_) \
         .skip(skip)\
         .limit(limit)
fields_list = query.run(g.db_conn)

Edit: Also possible:

query = r.table('messages') \
         .order_by(r.desc('created')) \
         .filter(r.row['user_id'] == user_id) \
         .filter(r.row['tags'].contains(tag) if tag is not None else True) \
         .filter(r.row['read'] == read if read is not None else True) \
         .skip(skip) \
         .limit(limit)
fields_list = query.run(g.db_conn)
于 2014-08-30T21:56:21.440 回答