2017-09-26 60 views
0

我是Postgresql JSONb和Ecto的新手。我有一个列“配置”,是jsonb的表。我能够插入,但是当我尝试从中选择使用片段函数的条件时,我无法使其工作。下面是示例输出:Elixir 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

你的第一个查询使用-> operator和用于:通过关键

获取JSON对象字段,以便它给你jsonb背部和错误告诉你,有没有~~运营商( AKA LIKE),在左侧需要jsonb

的作品查询使用->>操作返回textLIKE(AKA ~~)不知道该怎么左侧与text做。

+0

一路走来,我有 - - 在某些时候,可能还有一些其他错误,除了没有阅读所有的文档和了解 - >操作符。我很欣赏清晰度。 – bexley

+0

关于'~~'而不是'LIKE'的错误信息会引起混淆,除非您已经知道'~~'和'LIKE'是相同的东西。别客气。 –