cd-slash

cd-slash

Ecto not using indexes in SQLite causing slow query

I have a relatively large table (~350k rows and ~50 columns) in an existing GADM database that I’m connecting to with Ecto.

I’ve created indexes on the table with the migration below:

defmodule GADM.Migrations.AddIndexes do
  use Ecto.Migration

  def up do
    create(index(:gadm_410, [:gid_0]))
    create(index(:gadm_410, [:gid_1]))
    create(index(:gadm_410, [:gid_2]))
    create(index(:gadm_410, [:gid_3]))
    create(index(:gadm_410, [:gid_4]))
    create(index(:gadm_410, [:gid_5]))
    create(index(:gadm_410, [:country]))
  end

  def down do
    drop(index(:gadm_410, [:gid_0]))
    drop(index(:gadm_410, [:gid_1]))
    drop(index(:gadm_410, [:gid_2]))
    drop(index(:gadm_410, [:gid_3]))
    drop(index(:gadm_410, [:gid_4]))
    drop(index(:gadm_410, [:gid_5]))
    drop(index(:gadm_410, [:country]))
  end
end

Ecto.Migrator.down(GADMRepo, 0, GADM.Migrations.AddIndexes)
Ecto.Migrator.up(GADMRepo, 0, GADM.Migrations.AddIndexes)

I’m then making a relatively simple query using Ecto:

import Ecto.Query

id_field_name = String.to_atom("gid_3")
child_id_field_name = String.to_atom("gid_4")
name_field_name = String.to_atom("name_3")

GADM.Region
|> where([r], field(r, ^id_field_name) != "")
|> where([r], field(r, ^child_id_field_name) == "")
|> select([r], %{
  gid: field(r, ^id_field_name),
  name: field(r, ^name_field_name)
})
|> distinct(true)
|> GADMRepo.all()

This works, but is very slow:


10:26:39.908 [debug] QUERY OK source="gadm_410" db=2820.3ms queue=0.1ms idle=1446.3ms
SELECT DISTINCT g0."gid_3", g0."name_3" FROM "gadm_410" AS g0 WHERE (g0."gid_3" != '') AND (g0."gid_4" = '') []
↳ :elixir.eval_external_handler/3, at: src/elixir.erl:386

In contrast, when I paste exactly the same SQL as the output shows into SQLIte Studio, it executes in ~1ms, which is what I’d have anticipated with indexes available for all of the columns I’m working with.

To diagnose, firstly I’ve tried to use explain but can’t see any straightforward way to get Ecto to explain a query like this. Is there a function for that?

Secondly, since the indexes are clearly being built and then used when I execute the query elsewhere, why would Ecto not be using them? Even without the explain I can intuit that this is what’s happening as deleting the indexes yields almost identical execution times, so it seems they’re not having any effect.

Most Liked

ruslandoga

ruslandoga

:wave: @cd-slash

Just a guess: gid_4 might be picked because your query uses the equality operator with it, and on gid_3 it uses != which probably gets ignored.

Possible workarounds:

LostKobrakai

LostKobrakai

https://hexdocs.pm/ecto_sql/3.12.0/Ecto.Adapters.SQL.html#explain/3

Ecto has no influence on the db using an index or not. You’d want to make sure the queries are indeed the same (including using parameters and prepared queries or not).

cd-slash

cd-slash

Ecto.Adapters.SQL — Ecto SQL v3.12.0

Thanks, I’d tried that but couldn’t get it working for SQLite, seemed to only be for Postgres / MySQL?

Ecto has no influence on the db using an index or not. You’d want to make sure the queries are indeed the same (including using parameters and prepared queries or not).

Noted, I’ll try to ensure the queries are identical and continue trying to find a way to profile the query from Ecto

LostKobrakai

LostKobrakai

Use the Repo.explain variant as documented. This exists for the sqlite driver as well.

joey_the_snake

joey_the_snake

Is everything exactly the same when you query outside of Ecto? For example, the table has the same data inside of it?

If the query text is 100% the same in both places the only way they can choose different plans is if the estimated amount of work is different. The most obvious ways this can happen is if the data is different or it can change between analyze runs because those are based on samples. Or maybe your SQL CLI is using a different version of SQLite than Ecto is.

Where Next?

Popular in Questions Top

pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
sacepums
Hey guys. I'm new to elixir and im really stocked about it. But I ran into a bit of problem - I need to convert a date sting, for examp...
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
vac
Hi, I'm quite new in Elixir and I'm trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and ...
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list....
New
LegitStack
I’m trying to make a websocket server in Phoenix or raw Elixir. I heard about gun, I think I could use cowboy, but since I’m not that sma...
New
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New

Other popular topics Top

jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
Jim
As a follow up to my earlier question: I have the code compiling and running but not getting a successful login from the rest server. ...
New
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
New
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list....
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 42633 214
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New

We're in Beta

About us Mission Statement