SQLAlchemy:如何过滤 PgArray 列类型? [英] SQLAlchemy: how to filter on PgArray column types?
问题描述
在纯 postgres 中我们可以这样写:
In pure postgres we can write:
SELECT * FROM my_table WHERE 10000 = ANY (array_field);
或
SELECT * FROM my_table WHERE 10000 = ALL (array_field);
如何在没有原始 sql 的情况下借助 sqlalchemy 做同样的事情?
How to do the same with the help of sqlalchemy without raw sql?
推荐答案
a = ANY(b_array)
等价于 a
IN
(elements_of_b_array)代码>1.
因此您可以使用 <代码>in_() 方法.
Therefore you can use the in_()
method.
我不记得在我使用 PostgreSQL 的这些年里曾经使用过 a = ALL(b_array)
.你有吗?
I can't remember ever having used a = ALL(b_array)
in all my years with PostgreSQL. Have you?
如果您正在处理一个数组列并想测试它是否包含该列中的给定元素(或给定数组的所有元素),那么您可以使用 PostgreSQL 数组运算符 @>
(contains
) 或者更合适的反向兄弟 <@
(被包含
).
If you are dealing with an array column and want to test whether it contains a given element (or all elements of a given array) in that column, then you can utilize PostgreSQL array operators @>
(contains
) or more appropriately the inverse sibling <@
(is contained by
).
数组运算符的优势在于它们可以通过数组列上的 GIN 索引 来支持(与 ANY
构造不同).
Array operators carry the advantage that they can be supported with a GIN index on the array column (unlike the ANY
construct).
您的 SQL 语句:
SELECT * FROM my_table WHERE 10000 = ANY (array_field);
(几乎)1 等价于
SELECT * FROM my_table WHERE 10000 <@ array_field;
我不是 SQLAlchemy 的专家,但根据 SQLAlchemy 手册中的 教程,您可以使用任何运算符:
I am no expert with SQLAlchemy, but according to the tutorial in the SQLAlchemy manual, you can use any operator:
如果您遇到了真正不可用的接线员,您可以一直使用 op()
方法;这会产生任何您需要的操作员:
If you have come across an operator which really isn’t available, you can always use the
op()
method; this generates whatever operator you need:
>>> print users.c.name.op('tiddlywinks')('foo') users.name tiddlywinks :name_1
粗体强调我的.您的语句在 SQLA 中可能如下所示:
Bold emphasis mine. Your statement could look like this in SQLA:
s = select([my_table], array_field.op('@>')('ARRAY[10000]'))
或者使用 PostgreSQL 数组值的替代输入语法:
Or with alternative input syntax for PostgreSQL array values:
s = select([my_table], array_field.op('@>') (cast('{10000}', int[])))
<小时>
1 NULL 处理有一个细微的区别:
1 There is a subtle difference with NULL handling:
SELECT '{NULL}'::int[] <@ ... -- that's an array with a single NULL element
总是产生 FALSE
.
SELECT NULL IN (...)
SELECT NULL = ANY (...)
SELECT NULL::int[] <@ ...
总是产生 NULL
.
如果您不打算查询 NULL
值,则可以忽略这一点.
If you are not going to query for NULL
values, you can ignore this.
这篇关于SQLAlchemy:如何过滤 PgArray 列类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!