The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Search Indexing Improvements (#63099)
Nathan Voxlandc024186f79ed
diff --git a/enterprise/backend/test/metabase_enterprise/cache/strategies_test.clj b/enterprise/backend/test/metabase_enterprise/cache/strategies_test.cljindex 0bf95814afb..e84bcb7d6b3 100644--- a/enterprise/backend/test/metabase_enterprise/cache/strategies_test.clj+++ b/enterprise/backend/test/metabase_enterprise/cache/strategies_test.clj@@ -7,6 +7,7 @@[metabase.queries.models.query :as query][metabase.query-processor :as qp][metabase.query-processor.card :as qp.card]+ [metabase.search.ingestion :as search.ingestion][metabase.test :as mt]))(comment@@ -84,97 +85,99 @@(-> (qp/process-query query) (dissoc :data))))))))))))))(deftest e2e-advanced-caching- (mt/with-empty-h2-app-db!- (mt/with-premium-features #{:cache-granular-controls}- (mt/dataset (mt/dataset-definition "caching1"- [["table"- [{:field-name "value" :indexed? true :base-type :type/Text}]- [["a"] ["b"] ["c"]]]])- (mt/with-temp [:model/Card card1 {:dataset_query (mt/mbql-query table)}- :model/Card card2 {:dataset_query (mt/mbql-query table)}- :model/Card card3 {:dataset_query (mt/mbql-query table)}- :model/Card card4 {:dataset_query (mt/mbql-query table)}+ (binding [search.ingestion/*force-sync* true+ search.ingestion/*disable-updates* true]+ (mt/with-empty-h2-app-db!+ (mt/with-premium-features #{:cache-granular-controls}+ (mt/dataset (mt/dataset-definition "caching1"+ [["table"+ [{:field-name "value" :indexed? true :base-type :type/Text}]+ [["a"] ["b"] ["c"]]]])+ (mt/with-temp [:model/Card card1 {:dataset_query (mt/mbql-query table)}+ :model/Card card2 {:dataset_query (mt/mbql-query table)}+ :model/Card card3 {:dataset_query (mt/mbql-query table)}+ :model/Card card4 {:dataset_query (mt/mbql-query table)}- :model/CacheConfig _cr {:model "root"- :model_id 0- :strategy :ttl- :config {:multiplier 200- :min_duration_ms 10}}- :model/CacheConfig _c1 {:model "question"- :model_id (:id card1)- :strategy :ttl- :config {:multiplier 100- :min_duration_ms 0}}- :model/CacheConfig _c2 {:model "question"- :model_id (:id card2)- :strategy :duration- :config {:duration 1- :unit "minutes"}}- :model/CacheConfig _c3 {:model "question"- :model_id (:id card3)- :strategy :schedule- :config {:schedule "0 0/2 * * * ? *"}}]- (let [t (fn [seconds]- (t/plus #t "2024-02-13T10:00:00Z" (t/duration seconds :seconds)))- mkres (fn [input]- {:cache/details (if input- {:cached true, :updated_at input, :hash some?}- {:stored true, :hash some?})- :row_count 3- :status :completed})]- (testing "strategy = ttl"- (mt/with-model-cleanup [[:model/QueryCache :updated_at]]- (mt/with-clock (t 0)- (let [q (with-redefs [query/average-execution-time-ms (constantly 1000)]- (#'qp.card/query-for-card card1 [] {} {} {}))]- (is (=? {:type :ttl :multiplier 100}- (:cache-strategy q)))- (is (=? (mkres nil)- (-> (qp/process-query q) (dissoc :data))))- (testing "There is cache on second call"- (is (=? (mkres (t 0))- (-> (qp/process-query q) (dissoc :data)))))- (testing "No cache after expiration"- (mt/with-clock (t 101) ;; avg execution time 1s * multiplier 100 + 1- (is (=? (mkres nil)- (-> (qp/process-query q) (dissoc :data))))))))))+ :model/CacheConfig _cr {:model "root"+ :model_id 0+ :strategy :ttl+ :config {:multiplier 200+ :min_duration_ms 10}}+ :model/CacheConfig _c1 {:model "question"+ :model_id (:id card1)+ :strategy :ttl+ :config {:multiplier 100+ :min_duration_ms 0}}+ :model/CacheConfig _c2 {:model "question"+ :model_id (:id card2)+ :strategy :duration+ :config {:duration 1+ :unit "minutes"}}+ :model/CacheConfig _c3 {:model "question"+ :model_id (:id card3)+ :strategy :schedule+ :config {:schedule "0 0/2 * * * ? *"}}]+ (let [t (fn [seconds]+ (t/plus #t "2024-02-13T10:00:00Z" (t/duration seconds :seconds)))+ mkres (fn [input]+ {:cache/details (if input+ {:cached true, :updated_at input, :hash some?}+ {:stored true, :hash some?})+ :row_count 3+ :status :completed})]+ (testing "strategy = ttl"+ (mt/with-model-cleanup [[:model/QueryCache :updated_at]]+ (mt/with-clock (t 0)+ (let [q (with-redefs [query/average-execution-time-ms (constantly 1000)]+ (#'qp.card/query-for-card card1 [] {} {} {}))]+ (is (=? {:type :ttl :multiplier 100}+ (:cache-strategy q)))+ (is (=? (mkres nil)+ (-> (qp/process-query q) (dissoc :data))))+ (testing "There is cache on second call"+ (is (=? (mkres (t 0))+ (-> (qp/process-query q) (dissoc :data)))))+ (testing "No cache after expiration"+ (mt/with-clock (t 101) ;; avg execution time 1s * multiplier 100 + 1+ (is (=? (mkres nil)+ (-> (qp/process-query q) (dissoc :data))))))))))- (testing "strategy = duration"- (mt/with-model-cleanup [[:model/QueryCache :updated_at]]- (mt/with-clock (t 0)- (let [q (#'qp.card/query-for-card card2 [] {} {} {})]- (is (=? {:type :duration}- (:cache-strategy q)))- (is (=? (mkres nil)- (-> (qp/process-query q) (dissoc :data))))- (testing "There is cache on the next call"- (is (=? (mkres (t 0))- (-> (qp/process-query q) (dissoc :data)))))- (testing "No cache after expiration"- (mt/with-clock (t 61)- (is (=? (mkres nil)- (-> (qp/process-query q) (dissoc :data))))))))))+ (testing "strategy = duration"+ (mt/with-model-cleanup [[:model/QueryCache :updated_at]]+ (mt/with-clock (t 0)+ (let [q (#'qp.card/query-for-card card2 [] {} {} {})]+ (is (=? {:type :duration}+ (:cache-strategy q)))+ (is (=? (mkres nil)+ (-> (qp/process-query q) (dissoc :data))))+ (testing "There is cache on the next call"+ (is (=? (mkres (t 0))+ (-> (qp/process-query q) (dissoc :data)))))+ (testing "No cache after expiration"+ (mt/with-clock (t 61)+ (is (=? (mkres nil)+ (-> (qp/process-query q) (dissoc :data))))))))))- (testing "strategy = schedule"- (mt/with-model-cleanup [[:model/QueryCache :updated_at]]- (mt/with-clock (t 0)- (is (pos? (:schedule-invalidated (#'task.cache/refresh-cache-configs!))))- (let [q (#'qp.card/query-for-card card3 [] {} {} {})]- (is (=? {:type :schedule}- (:cache-strategy q)))- (is (=? (mkres nil)- (-> (qp/process-query q) (dissoc :data))))- (testing "There is cache on second call"- (is (=? (mkres (t 0))- (-> (qp/process-query q) (dissoc :data)))))))- (testing "No cache after job ran again"- (mt/with-clock (t 121)+ (testing "strategy = schedule"+ (mt/with-model-cleanup [[:model/QueryCache :updated_at]]+ (mt/with-clock (t 0)(is (pos? (:schedule-invalidated (#'task.cache/refresh-cache-configs!))))- (let [q (#'qp.card/query-for-card card3 {} {} {} {})]+ (let [q (#'qp.card/query-for-card card3 [] {} {} {})]+ (is (=? {:type :schedule}+ (:cache-strategy q)))(is (=? (mkres nil)- (-> (qp/process-query q) (dissoc :data)))))))))+ (-> (qp/process-query q) (dissoc :data))))+ (testing "There is cache on second call"+ (is (=? (mkres (t 0))+ (-> (qp/process-query q) (dissoc :data)))))))+ (testing "No cache after job ran again"+ (mt/with-clock (t 121)+ (is (pos? (:schedule-invalidated (#'task.cache/refresh-cache-configs!))))+ (let [q (#'qp.card/query-for-card card3 {} {} {} {})]+ (is (=? (mkres nil)+ (-> (qp/process-query q) (dissoc :data)))))))))- (testing "default strategy = ttl"- (let [q (#'qp.card/query-for-card card4 [] {} {} {})]- (is (=? {:type :ttl :multiplier 200}- (:cache-strategy q)))))))))))+ (testing "default strategy = ttl"+ (let [q (#'qp.card/query-for-card card4 [] {} {} {})]+ (is (=? {:type :ttl :multiplier 200}+ (:cache-strategy q))))))))))))diff --git a/src/metabase/search/appdb/core.clj b/src/metabase/search/appdb/core.cljindex d02f7a71593..e6416697c3a 100644--- a/src/metabase/search/appdb/core.clj+++ b/src/metabase/search/appdb/core.clj@@ -168,13 +168,13 @@(let [index-created (search.index/when-index-created)](if (and index-created (< 3 (t/time-between (t/instant index-created) (t/instant) :days)))(do- (log/debug "Forcing early reindex because existing index is old")+ (log/info "Forcing early reindex because existing index is old")(search.engine/reindex! :search.engine/appdb {}))(let [created? (search.index/ensure-ready! opts)](when (or created? re-populate?)- (log/debug "Populating index")- (populate-index! :search/updating))))))+ (log/info "Populating index")+ (populate-index! (if created? :search/reindexing :search/updating)))))))(defmethod search.engine/reindex! :search.engine/appdb[_ {:keys [in-place?]}]diff --git a/src/metabase/search/appdb/index.clj b/src/metabase/search/appdb/index.cljindex 799fb73a166..6fe43477a72 100644--- a/src/metabase/search/appdb/index.clj+++ b/src/metabase/search/appdb/index.clj@@ -11,6 +11,7 @@[metabase.search.appdb.specialization.postgres :as postgres][metabase.search.config :as search.config][metabase.search.engine :as search.engine]+ [metabase.search.ingestion :as search.ingestion][metabase.search.models.search-index-metadata :as search-index-metadata][metabase.search.spec :as search.spec][metabase.util :as u]@@ -34,10 +35,11 @@(def ^:private sync-tracking-period (long (* 5 #_minutes 60e9)))-(defonce ^:dynamic ^:private *index-version-id*- (if config/is-prod?- (:hash config/mb-version-info)- (u/lower-case-en (u/generate-nano-id))))+; The version ID MUST be updated whenever there is an incompatible change to the schema OR content the index table+; The id can be any string, but a simple incrementing number is normally easiest to manage while giving some semantic meaning.+; When this version changes, on startup metabase will not use the existing index table and instead reindex everything to a new table marked with the new version.+; It is dynamic to allow tests to override it+(defonce ^:dynamic ^:private *index-version-id* "2")(defonce ^:private next-sync-at (atom nil))@@ -258,7 +260,7 @@(throw e))))))(defn- batch-update!- "Create the given search index entries in bulk"+ "Create the given search index entries in bulk. Commits after each batch"[context documents];; Protect against tests that nuke the appdb(when config/is-test?@@ -274,10 +276,12 @@(let [active-table (active-table)entries (map document->entry documents);; No need to update the active index if we are doing a full index and it will be swapped out soon. Most updates are no-ops anyway.- active-updated? (when-not (and active-table (= context :search/reindexing)) (safe-batch-upsert! active-table entries))+ active-updated? (when-not (and active-table (pending-table) (= context :search/reindexing)) (safe-batch-upsert! active-table entries))pending-updated? (safe-batch-upsert! (pending-table) entries)](when (or active-updated? pending-updated?)(u/prog1 (->> entries (map :model) frequencies)+ (when (and (= :search/reindexing context) (not search.ingestion/*force-sync*))+ (t2/query ["commit"]))(log/trace "indexed documents for " <>)(when active-updated?(analytics/set! :metabase-search/appdb-index-size (t2/count (name active-table))))))))@@ -286,10 +290,15 @@"Indexes the documents. The context should be :search/updating or :search/reindexing.Context should be :search/updating or :search/reindexing to help control how to manage the updates"[context document-reducible]- (transduce (comp (partition-all insert-batch-size)- (map (partial batch-update! context)))- (partial merge-with +)- document-reducible))+ ;; New connection used for performing the updates which commit periodically without impacting any outer transactions.+ (letfn [(do-index []+ (transduce (comp (partition-all insert-batch-size)+ (map (partial batch-update! context)))+ (partial merge-with +)+ document-reducible))]+ (if (and (= :search/reindexing context) (not search.ingestion/*force-sync*))+ (t2/with-connection [_conn (mdb/data-source)] (do-index))+ (do-index))))(defmethod search.engine/update! :search.engine/appdb [_engine document-reducible](index-docs! :search/updating document-reducible))@@ -344,15 +353,22 @@[](log/infof "Resetting appdb index for version %s, active table: %s" *index-version-id*(pr-str (active-table)))- ;; stop tracking any pending table- (when-let [table-name (pending-table)]- (when-not *mocking-tables*- (let [deleted (search-index-metadata/delete-index! :appdb *index-version-id* table-name)]- (when (pos? deleted)- (log/infof "Deleted %d pending indices" deleted))))- (swap! *indexes* assoc :pending nil))- (maybe-create-pending!)- (activate-table!))+ (letfn [(reset-logic []+ ;; stop tracking any pending table+ (when-let [table-name (pending-table)]+ (when-not *mocking-tables*+ (let [deleted (search-index-metadata/delete-index! :appdb *index-version-id* table-name)]+ (when (pos? deleted)+ (log/infof "Deleted %d pending indices" deleted))))+ (swap! *indexes* assoc :pending nil))+ (maybe-create-pending!)+ (activate-table!))]+ (if search.ingestion/*force-sync*+ (reset-logic)+ ;; Creates and tracks tables with a unique transaction so the empty tables are available to other threads+ ;; even while the initial startup and data load may be happening+ (t2/with-connection [_ (mdb/data-source)]+ (reset-logic)))))(defn ensure-ready!"Ensure the index is ready to be populated. Return false if it was already ready."diff --git a/src/metabase/search/spec.clj b/src/metabase/search/spec.cljindex eb4c9eb105e..c4b1f1b06f4 100644--- a/src/metabase/search/spec.clj+++ b/src/metabase/search/spec.clj@@ -12,9 +12,12 @@[toucan2.tools.transformed :as t2.transformed]))(def search-models- "Set of search model string names."- (cond-> #{"dashboard" "table" "dataset" "segment" "collection" "database" "action" "indexed-entity" "metric" "card"}- config/ee-available? (conj "document")))+ "Set of search model string names. Sorted by order to index based on importance and amount of time to index"+ (cond-> ["collection" "dashboard" "segment" "database" "action"]+ config/ee-available? (conj "document")+ ;; metric/card/dataset moved to the end because they take a long time due to computing has_temporal_dim etc.+ ;; table and indexed-entity moved to the end because there can be a large number of them+ true (conj "table" "indexed-entity" "metric" "card" "dataset")))(def ^:private search-model->toucan-model(into {}diff --git a/test/metabase/search/appdb/index_test.clj b/test/metabase/search/appdb/index_test.cljindex 65e0baa1b52..2e7b84091e7 100644--- a/test/metabase/search/appdb/index_test.clj+++ b/test/metabase/search/appdb/index_test.clj@@ -493,7 +493,7 @@:state "initial":creator_id (mt/user->id :rasta)}](model-index/add-values! model-index)- (is (= "indexed-entity" (last (into [] (map :model) (search.ingestion/searchable-documents))))))))+ (is (= "dataset" (last (into [] (map :model) (search.ingestion/searchable-documents))))))))(deftest ^:synchronized table-cleanup-test(when (search/supports-index?)