Ecto 查询中 Regex 的正确语法是什么?
What's the correct syntax for Regex in an Ecto Query?
这些都不起作用:
from m in Model, where: m.name == ^~r(/.*#{query}.*/i)
from m in Model, where: m.name =~ ^~r(/.*#{query}.*/i)
正确的语法是什么?我在文档中找不到任何内容。
由于您要匹配不区分大小写的短语,因此您应该使用 ilike/2
which uses the SQL LIKE operator:
from m in Model, where: ilike(m.name, "%#{query}%")
like/2
将用于区分大小写的搜索。
Ecto 不支持开箱即用的正则表达式,因为数据库之间的实现差异很大。您需要做的是查看您所针对的数据库的正则表达式语法,并使用 Ecto fragment/1
. The following example, which searches for all models that match /^Peter [A-Z]$/
, uses PostgreSQL's POSIX regex feature:
自行构建查询的那一部分
from m in Model, where: fragment('? ~ ?', m.name, '^Peter [A-Z]$')
这些都不起作用:
from m in Model, where: m.name == ^~r(/.*#{query}.*/i)
from m in Model, where: m.name =~ ^~r(/.*#{query}.*/i)
正确的语法是什么?我在文档中找不到任何内容。
由于您要匹配不区分大小写的短语,因此您应该使用 ilike/2
which uses the SQL LIKE operator:
from m in Model, where: ilike(m.name, "%#{query}%")
like/2
将用于区分大小写的搜索。
Ecto 不支持开箱即用的正则表达式,因为数据库之间的实现差异很大。您需要做的是查看您所针对的数据库的正则表达式语法,并使用 Ecto fragment/1
. The following example, which searches for all models that match /^Peter [A-Z]$/
, uses PostgreSQL's POSIX regex feature:
from m in Model, where: fragment('? ~ ?', m.name, '^Peter [A-Z]$')