简体   繁体   English

如何使用Elixir / Ecto在jsonb PostgreSQL中查询空数组

[英]How to query for empty array in jsonb PostgreSQL using Elixir / Ecto

I have an Ecto schema with embeds_many defined like this: 我有一个定义为embeds_many的Ecto模式:

  schema "rounds" do
    embeds_many :growth_cycles, SomeModule.GrowthCycle, on_replace: :delete
  end

This translates to a jsonb field in PostgreSQL. 这将转换为PostgreSQL中的jsonb字段。 The default value is an empty array - []. 默认值为空数组-[]。 I'd like to write an Ecto query that returns only Rounds that have growth_cycles = [] (growth_cycles are not set/empty). 我想编写一个Ecto查询,该查询仅返回具有growth_cycles = [](growth_cycles未设置/为空)的回合。

The simplest thing I tried was: 我尝试过的最简单的事情是:

    from(r in Round, where: r.growth_cycles == [])

But this gives the following error: 但这会产生以下错误:

** (Postgrex.Error) ERROR 42P18 (indeterminate_datatype) cannot determine type of empty array
...
hint: Explicitly cast to the desired type, for example ARRAY[]::integer[].

I've also tried: 我也尝试过:

    from(r in Round, where: length(r.growth_cycles) == 0)

But this gives an error saying that length isn't a valid query expression. 但这给出了一个错误,指出长度不是有效的查询表达式。

I see references to using fragments to drop down to raw PostgreSQL, but I'm not sure how to do this. 我看到了使用片段将其下拉到原始PostgreSQL的参考,但是我不确定如何执行此操作。

You can try using fragment/1 to interject raw SQL into your queries. 您可以尝试使用fragment / 1将原始SQL插入查询中。

In this case, something like 在这种情况下,

(from r in Round, where: fragment("? = '{}'", r.growth_cycles)) |> Repo.all

should work 应该管用

From the documentation: 从文档中:

It is not possible to represent all possible database queries using Ecto's query syntax. 无法使用Ecto的查询语法表示所有可能的数据库查询。 When such is required, it is possible to use fragments to send any expression to the database: 需要时,可以使用片段将任何表达式发送到数据库:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM