--- xapian.module.orig	2008-05-31 20:18:57.000000000 -0400
+++ xapian.module	2008-05-31 22:55:58.000000000 -0400
@@ -273,13 +273,23 @@
  * Enter description here...
  *
  * @param bool $writable
+ * @param bool $flush
+ *   If set, instead of initializing the database we close it, flushing the
+ *   buffers to disk.
  * @return object
  */
-function _xapian_init_database($writable = FALSE) {
-  // This appears to stop the database getting built correctly, although it does
-  // make things a lot faster. Need to investigate using flush() perhaps.
-  //static $database;
-  //static $writable_database;
+function _xapian_init_database($writable = FALSE, $flush = FALSE) {
+  static $database;
+  static $writable_database;
+
+  if ($flush) {
+    if (is_object($writable_database)) {
+      // Set the database handle to NULL to ensure that it gets flushed to
+      // disk.
+      $writable_database = NULL;
+    }
+    return;
+  }
 
   if (!$writable && is_object($database)) {
     return $database;
@@ -567,9 +585,6 @@
   }
   
   db_query('DELETE FROM {xapian_reindex_queue} WHERE nid = %d', $node->nid);
-  
-  // close database and flush changes
-  unset($db); 
 }
 
 /**
@@ -612,6 +627,8 @@
       break;
     case FALSE:
       _xapian_reindex_node($node);
+      // Flush the changes to disk.
+      _xapian_init_database(TRUE, TRUE);
   }
 }
 
@@ -626,6 +643,8 @@
     if (is_object($node)) {
       if ($node->nid) {
         $db->delete_document('Q'. $node->nid);
+        // Flush the changes to disk.
+        _xapian_init_database(TRUE, TRUE);
       }
     }
   }
@@ -663,6 +682,8 @@
       $failed++;
     }
   }
+  // Flush the changes to disk.
+  _xapian_init_database(TRUE, TRUE);
   
   if (variable_get('xapian_log_queries', FALSE)) {
     $time_taken = (microtime(TRUE) - $start_time) * 1000;
