postgresql - Elixir Ecto JSONb 查询

标签 postgresql elixir phoenix-framework ecto

我是 Postgresql JSONb 和 Ecto 的新手。我有一个表,其中有一列“配置”是 jsonb。我能够插入,但是当我尝试使用片段函数在 where 条件下从中选择时,我无法让它工作。这是示例和输出:

iex> Repo.all(from i in Instance, select: i.configuration, where: 
fragment("?->'testing' LIKE '%hey%'", i.configuration))

[debug] QUERY ERROR source="instances" db=0.4ms
SELECT i0."configuration" FROM "instances" AS i0 WHERE 
(i0."configuration"->'testing' LIKE '%hey%') []
** (Postgrex.Error) ERROR 42883 (undefined_function): operator does not 
exist: jsonb ~~ unknown
(ecto) lib/ecto/adapters/sql.ex:431: 
Ecto.Adapters.SQL.execute_and_cache/7
(ecto) lib/ecto/repo/queryable.ex:133: Ecto.Repo.Queryable.execute/5
(ecto) lib/ecto/repo/queryable.ex:37: Ecto.Repo.Queryable.all/4

如果我这样执行原始查询:

iex> query = """
select configuration FROM instances where configuration->>'testing' 
LIKE '%hey%'
"""
iex> Ecto.Adapters.SQL.query!(Repo, query)
[debug] QUERY OK db=1.0ms
select configuration FROM instances where configuration->>'testing' 
LIKE '%hey%' []
%Postgrex.Result{columns: ["configuration"], command: :select,
connection_id: 28581, num_rows: 1, rows: [[%{"testing" => "some test 
hey?"}]]}

它有效,同样在 psql 中以下查询有效:

select configuration FROM instances where configuration->>'tsting' LIKE '%hey%';

对于我在 Repo.all(... 查询中做错了什么的任何帮助将不胜感激,因为我已经尝试了很多无济于事并且不明白我做错了什么。

最佳答案

您的第一个查询使用 -> operator这用于:

Get JSON object field by key

所以它给你 jsonb 并且错误告诉你没有 ~~ 运算符( AKA LIKE )接受 jsonb 在左侧。

有效的查询使用返回 textLIKE->> 运算符(又名 ~~ ) 确实知道如何处理左侧的 text

关于postgresql - Elixir Ecto JSONb 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46417251/

相关文章:

postgresql - 转换时间戳给出 future 的结果

sql - 使用 Group By 从多个表中获取数据

postgresql - 使用 PostgreSQL 计算相关系数?

elixir - Brunch 没有为 Phoenix 1.3 项目中的 VueJS 组件编译 CSS?

javascript - 如何在 Firefox 扩展中使用模块?

sql - 空间数据查询

phoenix-framework - Phoenix + Addict - POST 操作的跨域错误

elixir - 如何添加条件必填字段?

elixir - 如何在行为中使用 typespecs 和 Dialyzer?

iis - 在 Windows 上的 IIS 中运行 Phoenix 时内存泄漏/CPU 使用率持续居高不下