动态构建数据库查询python

2024-09-28 19:21:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试动态地在服务器端构建一个数据库查询。最终目标是使查询的结构大致如下(在javascript中):

r.db('test').table('data')
.filter(function (row) {
  return row('subgroup').eq('x').or(row('subgroup').eq('y'))
  .and(
    .row('metric_id').eq('a')
    .or(row('metric_id).eq('b')
    .or(row('metric_id').eq('c'))
})

我需要传入一组键,每个键都有一组可接受的值。对于上面的例子,我将忽略

{
  'subgroup': ['x', 'y'],
  'metric_id': ['a', 'b', 'c']
}

查询应返回subgroupxymetric_idabc的所有记录。你知道吗

我正在努力找到正确的方法。请参见下面的一个尝试:

def parse_filters(cls, filters):
    def rethink_filter(data):
        result = r.expr(True) # initialize filter function
        for key in filters:
            or_statements = []
            for value in filters[key]:
                f = {}
                f[key] = value
                or_statements.append(r.expr(f)) # build a list of 
            result = result.and_(r.or_(r.expr(or_statements)))
            if not result:
                break
        return result

    return rethink_filter

输入

{
  'entity_id': ['a', 'b'],
  'metric_id': ['x']
}

rethink_filter给出查询:

r.and_(r.and_(True, r.or_([{'entity_id': 'a'}, {'entity_id': 'b'}])), r.or_([{'metric_id': 'x'}]))

它看起来应该给出我想要的结果,但是它返回表中的所有项,不管entity_idmetric_id。你知道吗

我哪里出错了?你知道吗


Tags: orandkeyidreturnresultfiltermetric
1条回答
网友
1楼 · 发布于 2024-09-28 19:21:16

r.or可以用作中缀运算符,或者所有参数都可以作为参数提供。您只传入一个参数:数组。你知道吗

由于数组的计算结果始终为True,因此此查询:

r.and_(r.and_(True, r.or_([{'entity_id': 'a'}, {'entity_id': 'b'}])), r.or_([{'metric_id': 'x'}]))

实际上变成:

r.and_(r.and_(True, r.or_(True)), r.or_(True))

我希望你能看到它对每一条记录的计算结果都是True。你知道吗

当需要将数组传递给数据库中需要参数的函数时,可以使用^{}。你知道吗

r.or函数中也不能使用字典速记。也就是说,我相信,你需要把它们转换成document['entity_id'] == 'a',而不是{ 'entity_id' : 'a' }。您可以通过lambda函数访问文档,请参见filter documentation上的示例。你知道吗

相关问题 更多 >