views:

190

answers:

2

I am using pythons built-in sqlite3 module to access a database. My query executes a join between a table of 150000 entries and a table of 40000 entries, the result contains about 150000 entries again. If I execute the query in the SQLite Manager it takes a few seconds, but if I execute the same query from python, it has not finished after a minute. Here is the code I use:

cursor = self._connection.cursor()
annotationList = cursor.execute("SELECT PrimaryId, GOId " + 
                                "FROM Proteins, Annotations " +
                                "WHERE Proteins.Id = Annotations.ProteinId")
annotations = defaultdict(list)
for protein, goterm in annotationList:
    annotations[protein].append(goterm)

I did the fetchall just to measure the execution time. Does anyone have an explanation for the huge difference in performance? I am using Python 2.6.1 on Mac OS X 10.6.4.

EDIT

I implemented the join manually, and this works much faster. The code looks like this:

cursor = self._connection.cursor()
proteinList = cursor.execute("SELECT Id, PrimaryId FROM Proteins ").fetchall()
annotationList = cursor.execute("SELECT ProteinId, GOId FROM Annotations").fetchall()
proteins = dict(proteinList)
annotations = defaultdict(list)
for protein, goterm in annotationList:
    annotations[proteins[protein]].append(goterm)

So when I fetch the tables myself and then do the join in python, it takes about 2 seconds. The code above takes forever. Am I missing something here?

2nd EDIT I tried the same with apsw now, and it works just fine (the code does not need to be changed at all), the performance it great. I'm still wondering why this is so slow with the sqlite3-module.

+3  A: 

There is a discussion about it here: http://www.mail-archive.com/[email protected]/msg253067.html

It seems that there is a performance bottleneck in the sqlite3 module. There is an advice how to make your queries faster:

  • make sure that you do have indices on the join columns
  • use pysqlite
Yorirou
I am using python 2.6.5. It says on the PySqlite homepage that the `sqlite3` package that comes with Python is the same as `PySqlite`, but it doesn't say which version.
Space_C0wb0y
try to get a newer version
Yorirou
+1  A: 

You haven't posted the schema of the tables in question, but I think there might be a problem with indexes, specifically not having an index on Proteins.Id or Annotations.ProteinId (or both).

Create the SQLite indexes like this

CREATE INDEX IF NOT EXISTS index_Proteins_Id ON Proteins (Id)
CREATE INDEX IF NOT EXISTS index_Annotations_ProteinId ON Annotations (ProteinId)
Nick Craig-Wood
The Ids are create as `INTEGER PRIMARY KEYS`, meaning there are indexes on them by default. The identical schema yields way better performance when I use `apsw` instead of Pythons `sqlite3` module, so I doubt that the schema is the issue.
Space_C0wb0y