silviurosu
Ecto JSONB array 'contains' query
I am facing an issues creating a query to exclude results if a jsonb array field contains specified value.
This works in plain sql and I am trying to generate it from Ecto:
If I run plain sql it works though:
AND (not o0.“exclusions” @> ‘[83055]’)
I tried more ideas including this two:
where: fragment(“not ? @> ‘[?]’”, c.exclusions, ^dish_id)
It generates this sql:
(not o0.“exclusions” @> ‘[$2]’)
This does not run:
** (Postgrex.Error) ERROR 22P02 (invalid_text_representation): invalid input syntax for type json
value = “‘[#{dish_id}]’”
where: fragment(“not ? @> ?”, c.exclusions, ^value)
This generates:
(not o0.“exclusions” @> $2) [10318, “‘[83055]’”]
It does not raise any error but the filter is not working.
Most Liked
ewout
We ran into the same problem and we solved it like this:
where: fragment("? @> ?::jsonb", c.exclusions, ^[dish_id])
silviurosu
It worked :). I lost a day struggling with this thing. You saved me.
We need more documentation regarding query on jsonb fields in Ecto. Maybe I’ll write some blog posts.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #metaprogramming
- #security
- #hex









