Elixir Ecto JSONb查询

时间:2017-09-26 03:10:47

标签: postgresql elixir phoenix-framework ecto

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

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所做错误的任何帮助(...查询都会受到赞赏,因为我尝试了一堆无效但不明白我做错了什么。

1 个答案:

答案 0 :(得分:2)

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

  

按键获取JSON对象字段

因此它会向您提供jsonb,错误会告诉您没有~~运算符(AKA LIKE)在左侧显示jsonb

有效的查询使用返回->>的{​​{1}}运算符和text(AKA LIKE)确实知道如何处理左侧的~~侧。