mardi 29 septembre 2015

Android SQLite sort order optimization

I'm trying to optimise query to database. I use sqliteBrowser to experiment with indexes and queries. Here is my query:

SELECT song._id AS _id, artist.artist_id AS artist_id, song.name AS song_name, artist.name AS artist_name, 
song.date_add AS date_add, song.favorite AS favourite, artist.photo AS photo, 1 AS layout_type 
FROM artist INNER JOIN song ON artist.artist_id = song.artist_id 
WHERE (song.status = 1  AND artist.main = 1 ) ORDER BY song._id DESC LIMIT 200;

And my tables:

CREATE TABLE artist ( _id INTEGER PRIMARY KEY,artist_id INTEGER NOT 
NULL, date_add INTEGER NOT NULL, date_update INTEGER NOT NULL, name 
TEXT NOT NULL, search_name TEXT NOT NULL, main INTEGER NOT NULL,
 favorite INTEGER, status INTEGER NOT NULL, songs INTEGER NOT NULL, 
tematika INTEGER NOT NULL, photo TEXT NOT NULL)

and

CREATE TABLE song ( _id INTEGER PRIMARY KEY, artist_id INTEGER NOT 
NULL, date_add INTEGER NOT NULL, date_update INTEGER NOT NULL, 
date_view INTEGER DEFAULT 0, favorite INTEGER, stored INTEGER DEFAULT
 0, status INTEGER NOT NULL, name TEXT NOT NULL,search_name TEXT NOT 
NULL,text TEXT,tone INTEGER DEFAULT 0, font_size INTEGER DEFAULT 0)

The problem is when I use indexes - SQLite applies them to WHERE statement and execution speed is about 686.000ms. But in this particular query ORDER BY has most impact on speed. So I've tried to not to use indexes at all. In which case EXPLAIN QUERY PLAN states:

"0" "0" "1" "SCAN TABLE song"
"0" "1" "0" "SEARCH TABLE artist USING AUTOMATIC PARTIAL COVERING INDEX
 (main=? AND artist_id=?)"

and speed increases to 45 - 55 ms. This works fine in SQLiteBrowser but when I was trying to apply this to my app I got speed for this query 1400.000 ms and this error:

The connection pool for database has been unable to grant a connection to thread 1 (main) with flags 0x5 for 30.001001 seconds.

if I try to execute same query twice.

So I wonder what cause this error and if there any simple way to force SQLite to not to use USE TEMP B-TREE FOR ORDER BY because I think this is important in this case. Maybe some other approach to increase speed of this query?

Aucun commentaire:

Enregistrer un commentaire