简体   繁体   中英

Sqlalchemy query to array column using LIKE

I have table File with column file_names which is ARRAY type. W would like to build query searching records where any of array element is like "abc*" using wildcard.

I tried:

File.names.any("abc%", operator= operators.like_op).all()

but it doesn't work. It return sql:

SELECT file.id, file.names FROM file WHERE 'abc%' LIKE ANY(file.names)

but it return empty result. Do you have any suggestions, how to build such query?

the like operator applies to a text, not to an array, so you need to find a way to convert your array into text before applying the like operator. To do so in sql you can use array_to_string() function, see the manual .

I found solution in SQL:

SELECT file.id, file.names FROM file WHERE EXISTS (SELECT 1 FROM unnest(file.names) AS n
WHERE n LIKE 'abc%')

and it works. But I don't know how to ask such query in sqlalchemy. Any ideas?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM