如何从 Clickhouse ORM 合并多个查询集

How to do a union of multiple queryset from a clickhouse ORM

在 Django 搜索应用程序中,我想查询 clickhouse 数据库(使用 infi.clickhouse_orm 库)以获取成对的值,例如 (a=1 AND b>=1.5) OR (a=2 AND b>=1).在 SQL 这可以用

完成
select * from table where a == 1 and b >= 1.5 UNION ALL select * from table where a == 2 and b >= 1

查看我尝试过的其他示例:

查询集定义为

qs = TABLE.objects_in(db)
qs_1 = qs.filter(A__eq=1, B__gte=1.5)
qs_2 = qs.filter(A__eq=2, B__gte=1)

的|运算符

qs_union = qs_1 | qs_2

哪个returns

unsupported operand type(s) for |: 'QuerySet' and 'QuerySet'

UNION 运算符

qs_union = qs_1.union(qs_2)

哪个returns

'QuerySet' object has no attribute 'union'

和Q对象

qs_union = qs.filter(Q(A__eq=1, B__gte=1.5) | Q(A__eq=2, B__gte=1))

哪个returns

'Q' object has no attribute 'to_sql'

在 clickhouse 模型中,如何执行 2 个或更多查询集的并集?

谢谢!

简答:你应该使用infi.clickhouse_orm.queryQclass,比如:

from infi.clickhouse_orm.query import <b>Q</b>

Q-class in info.clickhouse_orm [GitHub]有一个to_sql方法:

class Q(object):

    # ...

    def to_sql(self, model_cls):
        if self._fovs:
            sql = ' {} '.format(self._mode).join(fov.to_sql(model_cls) for fov in self._fovs)
        else:
            if self._l_child and self._r_child:
                sql = '({} {} {})'.format(
                        self._l_child.to_sql(model_cls), self._mode, self._r_child.to_sql(model_cls))
            else:
                return '1'
        if self._negate:
            sql = 'NOT (%s)' % sql
        return sql

因为错误说它找不到 to_sql,看起来你没有使用那个 Q-class,但是 Django 的 Q class.