Using `.orderBy` in JSON
Hey,
I have a schema that roughly looks like this
and I want to query the db like that it gives me the top 10 Members with the highest
activity.messages
count. I figured out how I can orderBy but not inside of a json.Solution:Jump to solution
try something like:
```ts
const rows = await kysely
.selectFrom("member")...
25 Replies
Hey 👋
Are you using Kysely 0.26.x? what dialect are you using?
pg (postgres) and I use newest Kysely
In 0.26.x we've introduced type-safe JSON traversal, it's not documented yet in kysely.dev site, only in API docs and in the IDE.
Lemme know if this works for you:
https://kyse.link/?p=s&i=hKiV5qAL1BLLi3tvlwEq
will try when I’m home, than you :)
nvm was just vs code having it's moment
did it work?
process crashes with
If I comment the
.orderBy
away it workswhat postgres version?
pg (npm package) or postgres on the server?
server
PostgreSQL 14.8 (Ubuntu 14.8-0ubuntu0.22.04.1) on x86_64-pc-linux-gnu, compiled by gcc (Ubuntu 11.3.0-1ubuntu1~22.04.1) 11.3.0, 64-bit
I've added some test cases for json traversal in order by clauses https://github.com/kysely-org/kysely/pull/621 and everything seems to be OK.
we use pg 8.11.0 and postgres 15.x images.
@Igal I found the issue, in your example you used the
->
operator but it's ->>
, it works nowit should work with
->
too.
how's the column defined? json
or jsonb
?.addColumn("activity", "json", (col)
bingo, when changing the data type to
json
in tests it errors for order by with:
error: could not identify an ordering operator for type json
and works again when changing to ->>
.I already paniced because I didn't know what I should do and just randomly was scrolling through the test file and found the
->>
, tried it and worked lol
thanks anywayhttps://c.lunish.nl/r/4hU8WT.mp4 I am kind of lost here, why are the
activity.messages
higher on page 1 than on page 0? (each page only adds an offset [page] * 10
)->>
casts the thing you access to a string. The sorting is done using a stringified number. You probably need to explicitly cast to integerah okey, how do I do that (lol)
(@Igal^)
Solution
try something like:
yey that seems to work!! thank you