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

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

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


  "Import all existing messages into Lucene"
  []
  ;; Need to have an index created to make a reader, so just insert a dummy record
  (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 _]]
