   "Import all existing messages into Lucene"
   []
   ;; Need to have an index created to make a reader, so just insert a dummy record
-  (index-message! {:content "hello" :group-id (java.util.UUID/randomUUID)
-                   :thread-id (java.util.UUID/randomUUID) :created-at (java.util.Date.)})
-  (with-open [reader (store/store-reader (store))
-              writer (store/store-writer (store) analyzer)]
+  (index-message!
+    (store)
+    {:content "hello" :group-id (java.util.UUID/randomUUID)
+     :thread-id (java.util.UUID/randomUUID) :created-at (java.util.Date.)})
+  (with-open [reader (store/store-reader (store))]
     (doseq [msg (->> (d/q '[:find [(pull ?m pull-pattern) ...]
                            :in $ pull-pattern
                            :where [?m :message/id _]]

                    (map common/db->message))]
      (when (and (:group-id msg) (:thread-id msg) (:content msg)
                 (:created-at msg))
        (index-message! writer reader msg)))))

(defonce -store (atom nil))
(defn store
  []
  (swap! -store
         (fn [s]
           (or s
               (if-let [store-path (config :lucene-store-location)]
                 (store/disk-store store-path)
                 (store/memory-store))))))

(defonce writers-cache (agent {}))
(defn writer
  [store]
  (send writers-cache update store
        (fn [writer]
          (or writer (store/store-writer store analyzer))))
  (await-for 1000 writers-cache)
  (get @writers-cache store))

(defn index-message!
  ([message] (index-message! (store) message))
  ([store message]
   (let [message (-> message
                     (update :created-at (memfn getTime))
                     (assoc :group-id (db.thread/thread-group-id (:thread-id message))))
         wrtr (writer store)]
     (if-let [existing (try
                         (first
                           (clucie/search store {:group-id (:group-id message)
                                                 :thread-id (:thread-id message)}
                                          1))
                         (catch IndexNotFoundException _
                           nil))]
       (clucie/update!
         wrtr
         (update existing :content str "\n" (:content message))
         [:group-id :thread-id :content]
         :thread-id (:thread-id message))
       (clucie/add!
         wrtr
         [message]
         [:group-id :thread-id :content])))))

