halostatue
How do I use the PostgreSQL JSON ? operator in Ecto? Assume that I have a table users that has a JSONB field data, and I want to test (in PostgreSQL) whether it has a key honorific.
The SQL for this is:
SELECT *
FROM users
WHERE data ? 'honorific';
Neither of these work:
from u in :users, where: fragment("? \? ?", u.data, "honorific")
from u in :users, where: fragment("? ? ?", u.data, "?", "honorific")
The former fails with a compile error (not enough parameters to match the number of question marks) and the latter fails in the query because it produces SELECT u0.* FROM users WHERE u.data '?' 'honorific'.
I think that this is a bug, and I’d be interested to know how we would need to use such operators, because PostgreSQL has several:
┌──────┬─────────┬───────────┬─────────────┬────────────────────────────┐
│ Name │ Left arg│ Right arg │ Result type │ Description │
├──────┼─────────┼───────────┼─────────────┼────────────────────────────┤
│ <?> │ abstime │ tinterval │ boolean │ is contained by │
│ ? │ jsonb │ text │ boolean │ key exists │
│ ?# │ box │ box │ boolean │ deprecated, use && instead │
│ ?# │ line │ box │ boolean │ intersect │
│ ?# │ line │ line │ boolean │ intersect │
│ ?# │ lseg │ box │ boolean │ intersect │
│ ?# │ lseg │ line │ boolean │ intersect │
│ ?# │ lseg │ lseg │ boolean │ intersect │
│ ?# │ path │ path │ boolean │ intersect │
│ ?& │ jsonb │ text[] │ boolean │ all keys exist │
│ ?- │ point │ point │ boolean │ horizontally aligned │
│ ?- │ │ line │ boolean │ horizontal │
│ ?- │ │ lseg │ boolean │ horizontal │
│ ?-| │ line │ line │ boolean │ perpendicular │
│ ?-| │ lseg │ lseg │ boolean │ perpendicular │
│ ?| │ jsonb │ text[] │ boolean │ any key exists │
│ ?| │ point │ point │ boolean │ vertically aligned │
│ ?| │ │ line │ boolean │ vertical │
│ ?| │ │ lseg │ boolean │ vertical │
│ ?|| │ line │ line │ boolean │ parallel │
│ ?|| │ lseg │ lseg │ boolean │ parallel │
└──────┴─────────┴───────────┴─────────────┴────────────────────────────┘
Trending in Questions
Hello!
Suppose you are building workflow (order / task / payment) processing system with the following requirements:
Each workflow con...
New
I’m aware of 2 such projects, are there others?
git: GitHub - team-alembic/realworld: A fullstack Phoenix LiveView application with back...
New
Hi all,
I’m working on a Phoenix project where I need to make external HTTP requests and I’m trying to choose between Req and HTTPoison....
New
Hi everyone.
My team and I have been working on a fairly modest app based around video streaming and chat, but we’ve landed a customer t...
New
Hi,
we run different LLM models across a cluster, with each node loading a configurable subset. Model-specific queues let nodes consume ...
New
Hi all, I’m new here and would like to hear peoples views on my Elixir/Phoenix based game-engine! :smiley:
Mutonex gamedesign was finish...
New
Hello
I’ve been coding in Elixir for almost two years now because of my current job where we implemented Elixir in our application. But ...
New
Other Trending Topics
Hey there,
I haven’t seen a list of useful Elixir specific skills for the popular AI tools yet so I’m starting one here with my first.
...
New
I fully migrated to my own harness from Anthropic/Gemini and I think it’s time to share it. Welcome DSH, the DeepSeek Harness, fully writ...
New
Hey. Is there anyone here who creates agents in their apps? Not talking about using agents, but creating them. I’m finding it pretty diff...
New
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
With AI doing more of the implementation work, I’ve been wondering how much coding I should deliberately keep doing myself.
My main conc...
New
(I just needed to vent somewhere and LinkedIn is full of hope, or hype, I’m not sure which exactly)
AI dream has many faces, but general...
New
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #library
- #deployment
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #elixirconf
- #channels
- #exunit
- #discussion
- #code-sync
- #podcasts
- #javascript
- #onsite
- #dialyzer
- #docker
- #authentication
- #ai
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #blog-post
- #ecto-query
- #elixirconf-us
- #elixir-ls
- #phoenix_html
- #iex
- #graphql
- #genstage
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #elixirconf-eu
- #api
- #forms
- #security
- #hex










Showing Posts 1 to 7- Show Best Posts
- Show All (oldest first)
- Show All (newest first)
halostatue
This does not answer the question I raised above, but I have found two workarounds for this using PostgreSQL. Both of these depend on an undocumented function (only the
?operator is documented) and a bit of digging to produce something similar as needed.Use the underlying function of
?directly.fragment("jsonb_exists(?, ?)", u.data, "honorific"). The functions for?&and?|arejsonb_exists_allandjsonb_exists_any, so those can be used as well (but note that the types aretext[], so you would need to dofragment("jsonb_exists_any(?, ?)", u.data, ["honorific"])).Create a new operator analogous to
?,?&, and?|in your schema.Then you can construct these…
Unfortunately, no one in the PostgreSQL community will understand these operators against
json/jsonbtypes because you’ve created them, and you’re no longer writing standard PostgreSQL JSON queries. Unless you know these operators have been created, asking questions about these would cause confusion.halostatue
Third post on this for those following along, how I figured all of this out. I’ve been playing in
pg_catalogrecently because I’ve been building some tooling to automate the construction of monthly table partitioning in PostgreSQL 9.6, so I’m as apt to dig into this now as ever.If you need to figure out how to do this yourself,
psql -E <database>is your friend, because when you run something like\doS(describe operators in all schemas), it will output a query like the one below (the one below is one I copied and modified to find all operators with a question mark in them for the table in the first post).This will tell you the argument types for your aliased operator. In our case, left is
jsonband right istext. It still doesn’t tell you which function to use. For that, you need to look atpg_operatordirectly:This gives us the answer that the
?operator usesjsonb_exists. If the function/procedure you’re using does not exist in the same schema as the operator you’re defining (it probably doesn’t in this case), you must fully qualify it topg_catalog.jsonb_exists.This tells us that our
CREATE OPERATORstatement needs to look like:Be careful about overloading, as overloads require different types. You can qualify an operator by using the
OPERATOR()function in a query (seen above in the introspection query):If you wish to drop an operator, you must know the arg types as well.
pedromvieira
In my experience, I just dropped any attempts to use ECTO syntax and gone straight to Postgres JSON/B “normal queries”.
What are your thoughts regarding this direct approach?
PS: I use extensively Postgres advanced functions for JSON/B.
halostatue
The need to query into the JSONB is relatively rare for my applications, and I don’t recall what made me start looking at this particular issue. Most of my needs are met by straight queries, and on the rare occasion I need to query into JSONB it’s better to just use
fragment/1, which is why I was curious.michalmuskala
You can escape the question mark with
\, but you need it doubled - once for string and once for fragment. This should work fine:NobbZ
Instead of
"? \\? ?"one can also use~S"? \? ?", which removes one layer of escaping.halostatue
I should have tried that. This might be worth putting in the Ecto documentation.