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)
< sup> 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?
如果要处理 array列,并想测试是否在该列中包含给定元素(或给定数组的所有元素),则可以利用 PostgreSQL数组运算符 @>
(包含
)或更合适的是反同级 < @
(包含在
中)。
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
值y,您可以忽略它。
If you are not going to query for NULL
values, you can ignore this.
这篇关于SQLAlchemy:如何筛选PgArray列类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!