msw10100

msw10100

Ecto query of a JSONB column

When using postgres, I’d like to query a table where a JSONB column contains a JSON document with a field called members whose value is a list of strings. The query should return all rows where the members list in that column contains a string entry that matches a given string.

This SQL query works:

select * from typed_groups where members @> jsonb_build_object('members', jsonb_build_array('member_1'));

But I haven’t come up with an ecto query that works. I’ve tried this:

   query =
      from g in __MODULE__,
        where:
            fragment(
              "? @> ?",
              g.members,
              ^"jsonb_build_object('members', jsonb_build_array('#{member_id}'))::jsonb"
            ),
        select: g

And I’ve tried building the interpolated string outside the query. All return no rows.

Marked As Solved

LostKobrakai

LostKobrakai

You can either use one big fragment, where you put the whole sql in one string and have more parameters or you can also provide nested fragments as parameters of an outer fragment.

fragment("? @> jsonb_build_object(?, jsonb_build_array(?))", g.members, "members", member_id)
# or
fragment(
  "? @> ?", 
  g.members, 
  fragment(
    "jsonb_build_object(?, ?)", 
    "members", 
    fragment("jsonb_build_array(?)", member_id)
  )
)

The latter is useful because you can wrap fragment usage in macros and essentually extend the available APIs to use in query building: Ecto.Query.API — Ecto v3.11.2

Also Liked

LostKobrakai

LostKobrakai

That’s where postgres can no longer infer the type, because you started to use a paramter. You can use Ecto.Query.API — Ecto v3.11.2 to force a type.

msw10100

msw10100

Cool, thanks!! Both of those suggestions work great if I put in a literal string for member_id in that last fragment. If I pin it to a variable with ^member_id instead of a literal string, I get an indeterminate_datatype error.

To fix this, I had to add ::text after the final ? as a type hint.

Where Next?

Popular in Questions Top

mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
beno
I will often find my self writing things similar to: case some_value do nil -> something() "" -> something() _ -> somethi...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
komlanvi
Hi everyone, I was playing with phoenix liveView but I run into an issue. I have a form and want to validate each input text when the te...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New

Other popular topics Top

vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
hariharasudhan94
lets say i have a sample like a = 20; b = 10; if (a > b) do {:ok, "a"} end if (a < b) do {:ok, b} end if (a == b) do {:ok, "equa...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New
grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 52341 488
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New

We're in Beta

About us Mission Statement