Elixir Ecto JSONb 查询
Elixir Ecto JSONb Query
我是 Postgresql JSONb 和 Ecto 的新手。我有一个 table 列 "configuration" 是 jsonb。我能够插入,但是当我尝试使用片段函数在 where 条件下从它 select 时,我无法让它工作。这是示例和输出:
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
。
有效的查询使用 ->>
运算符,returns text
和 LIKE
(又名 ~~
)知道如何处理 text
在左边。
我是 Postgresql JSONb 和 Ecto 的新手。我有一个 table 列 "configuration" 是 jsonb。我能够插入,但是当我尝试使用片段函数在 where 条件下从它 select 时,我无法让它工作。这是示例和输出:
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
。
有效的查询使用 ->>
运算符,returns text
和 LIKE
(又名 ~~
)知道如何处理 text
在左边。