凡是數據庫中,索引的存在就是為了提高查詢速度的,數據庫的索引有點類似於書本上面的目錄的概念,因為在英文中都是index,事實上也就是目錄。
其算法應該叫做“倒排索引”,這個其實也類似於搜索引擎里面的基本算法。
測試:10w條數據,沒有索引的情況下,查詢一條數據大約需要550ms以上。
建立索引后,數據庫的體積增大了3倍左右,但是同樣的查詢卻減少到8ms的級別,提升了70倍
有時候關於sqlite數據庫出錯或者沒法用的情況看這里
下面是在android手機上面的測試代碼
02 |
SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase(databaseFile, "test123" , null ); |
03 |
database.execSQL( "create table if not exists t1(a,b)" ); |
05 |
database.execSQL( "create index if not exists ia on t1(a,b)" ); |
07 |
for ( int i = 0 ; i < 100000 ; i++) { |
08 |
database.execSQL( "insert into t1(a, b) values(?, ?)" , new String[] { "" + i, "name" + Math.random() * i }); |
12 |
Cursor cursor = database.rawQuery( "select * from t1 where a='88980'" , null ); |
13 |
while (cursor.moveToNext()){ |
14 |
String a = cursor.getString(cursor.getColumnIndex( "a" )); |
15 |
String b = cursor.getString(cursor.getColumnIndex( "b" )); |
16 |
Log.v( "test" , "查找結果---------->" + "a: " +a+ " " + "b: " +b); |
18 |
Log.v( "test" , "查找結束" ); |
本文地址http://tweetyf.org/2012/06/sqlite_optimization_using_index.html