我是 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
在左侧。
有效的查询使用返回 text
和 LIKE
的 ->>
运算符(又名 ~~
) 确实知道如何处理左侧的 text
。
关于postgresql - Elixir Ecto JSONb 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46417251/