Elixir + Ecto: How to do WHERE NOT IN [array]?
Asked Answered
C

3

18

I am trying to look for all Users that don't have a certain string element in their match_history field. I took a guess with this:

matched_user = User |> where([u], ^device_id not in u.match_history) |> limit(1) |> VideoChat.Repo.one

But it seems to break at the not part. Is there a way to do this?

Comenius answered 6/12, 2016 at 21:32 Comment(0)
G
26

Try

User |> where([u], not ^device_id in u.match_history)

Greenery answered 7/12, 2016 at 8:33 Comment(0)
S
1

For those who are looking for a "array does not contain any" behaviour.
For example "match_history does not contain device_1 device_2, device_3"

Given you're using PostgreSQL, can use a fragment with the array contains @> operator.

from t in queryable, where: not fragment("? @> ?::varchar[]", t.match_history, ^device_ids)

Or

from t in queryable, where: fragment("NOT ? @> ?::varchar[]", t.match_history, ^device_ids)
Summitry answered 11/2, 2019 at 12:30 Comment(0)
C
0

As of Elixir 1.7+ you should use:

User |> where([u], ^device_id not in u.match_history).

If you use the accepted answer you will get a compile time warning.

Cleanlimbed answered 10/8, 2022 at 18:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.