How do I get the result size of a query in Ecto?

Originally sent in Elixir Chat
la_219

Just a quick question from an Elixir & Ecto beginner: How do I get the result size of a query? I worked with pagination and that worked like a charm but I also need to give the total size to the frontend. Do I need another query for that or is there a more elegant solution?

kartheek

You are using any specific pagination library ? Scrivener has those details in the result.

la_219

No, so far not. But if it has enough perks, it might be worth it

kartheek
la_219

thank you!

zachallaun

@la_219 it might be worth thinking through the problem even if you use scrivener, just as a learning exercise! The critical thing is that everything boils down to a SQL query, which returns rows of records. Barring something like array_agg and building the structs yourself, you’d need/want to include the count on every row of the returned result. In Ecto, that means you’d add a virtual field to your schema definition, something like total_count. You could then join each returned row on every row, selecting a count of those rows.

Another thing to consider is the database you’re using. If you’re over a network, like Postgres, it’s usually better to jam everything into one query. If you’re using SQLite though, since the DB is local, you can sort of ignore the cost of multiple requests and just structure things in whatever way is easiest to reason about!

la_219

Thank you! That's exactly what I ended up doing. I totally agree that it's worth to solve a problem (at least in theory) first before using a library. I'm working with postgres so getting everything into one query is definitely the preferred way

1 Like

Repo.aggregate(query, :count, :id) should work in most cases (unless your query does not include an id field in its select statement, in which case replace it with another column).

Link to Repo.aggregate docs.

3 Likes

thank you, that works like a charm! :slight_smile:

1 Like