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
Reduce coupling between semantic.index and semantic.scoring (#62089)
applebybe23df0964a1
diff --git a/enterprise/backend/src/metabase_enterprise/semantic_search/index.clj b/enterprise/backend/src/metabase_enterprise/semantic_search/index.cljindex b06471731d3..1204a11c011 100644--- a/enterprise/backend/src/metabase_enterprise/semantic_search/index.clj+++ b/enterprise/backend/src/metabase_enterprise/semantic_search/index.clj@@ -546,6 +546,16 @@(update base-query :where #(into [:and] [% filters]))base-query)))+(defn- hybrid-select+ "For a given `col-name` return a :coalesce expression to reference it from the outer hybrid search query.++ (hybrid-coalesce :model_id) -> [:coalesce :v.model_id :t.model_id]"+ ([col-name-and-alias]+ (hybrid-select col-name-and-alias "v." "t."))+ ([[col-name col-alias] vector-prefix text-prefix]+ (let [prefix #(keyword (str %1 (name %2)))]+ [[:coalesce (prefix vector-prefix col-name) (prefix text-prefix col-name)] col-alias])))+(defn- hybrid-search-query"Build a hybrid search query using vector + keyword based searches and reranking with RRF"[index embedding search-context]@@ -553,19 +563,27 @@keyword-results (keyword-search-query index search-context)full-query {:with [[:vector_results semantic-results][:text_results keyword-results]]- :select [[[:coalesce :v.id :t.id] :id]- [[:coalesce :v.model_id :t.model_id] :model_id]- [[:coalesce :v.model :t.model] :model]- [[:coalesce :v.content :t.content] :content]- [[:coalesce :v.verified :t.verified] :verified]- [[:coalesce :v.metadata :t.metadata] :metadata]- [[:coalesce :v.semantic_rank -1] :semantic_rank]- [[:coalesce :t.keyword_rank -1] :keyword_rank]]+ :select (into+ (mapv hybrid-select common-search-columns)+ [[:v.semantic_rank :semantic_rank]+ [:t.keyword_rank :keyword_rank]]):from [[:vector_results :v]]:full-join [[:text_results :t] [:= :v.id :t.id]]:limit (semantic-settings/semantic-search-results-limit)}]full-query))+(defn- scored-search-query+ "Build a hybrid search query with additional `scorers`"+ [index embedding search-context scorers]+ ;; The purpose of this query is just to project the coalesced hybrid columns with standard names so the scorers know+ ;; what to call them (e.g. :model rather than [:coalesced :v.model :t.model]).+ (let [hybrid-query (hybrid-search-query index embedding search-context)+ full-query {:with [[:hybrid_results hybrid-query]]+ :select [:id :model_id :model :content :verified :metadata :semantic_rank :keyword_rank]+ :from [:hybrid_results]+ :limit (semantic-settings/semantic-search-results-limit)}]+ (scoring/with-scores search-context scorers full-query)))+(defn- legacy-input-with-score"Fetches the legacy_input field from a result's metadata and attaches a score based on theembedding distance."@@ -743,8 +761,7 @@db-timer (u/start-timer)weights (search.config/weights (:context search-context))scorers (scoring/semantic-scorers (:table-name index) search-context)- query (->> (hybrid-search-query index embedding search-context)- (scoring/with-scores search-context scorers))+ query (scored-search-query index embedding search-context scorers)xform (comp (map decode-metadata)(map (partial legacy-input-with-score weights (keys scorers))))reducible (jdbc/plan db (sql-format-quoted query) {:builder-fn jdbc.rs/as-unqualified-lower-maps})@@ -787,6 +804,7 @@(def index (default-index embedding-model))(def search-ctx {:search-string "pasta"})(def embed (embedding/get-embedding embedding-model (:search-string search-ctx)))+ (def scorers (scoring/semantic-scorers (:table-name index) search-ctx))(keyword-search-query index search-ctx)(sql-format-quoted (keyword-search-query index search-ctx))@@ -800,6 +818,10 @@(sql-format-quoted (hybrid-search-query index embed search-ctx))(jdbc/execute! db (sql-format-quoted (hybrid-search-query index embed search-ctx)))+ (scored-search-query index embed search-ctx scorers)+ (sql-format-quoted (scored-search-query index embed search-ctx scorers))+ (jdbc/execute! db (sql-format-quoted (scored-search-query index embed search-ctx scorers)))+(query-index db index search-ctx))(defn- delete-from-index-batch-sql@@ -866,16 +888,19 @@(def search-context {:search-string search-string})(def embedding (embedding/get-embedding (:embedding-model index) search-string))+ (def scorers (scoring/semantic-scorers (:table-name index) search-context));; Format queries for execution(def semantic-sql (sql-format-quoted (semantic-search-query index embedding search-context)))(def keyword-sql (sql-format-quoted (keyword-search-query index search-context)))(def hybrid-sql (sql-format-quoted (hybrid-search-query index embedding search-context)))+ (def scored-sql (sql-format-quoted (scored-search-query index embedding search-context scorers)));; do in repl ->#_(explain-analyze-query db semantic-sql)#_(explain-analyze-query db keyword-sql)#_(explain-analyze-query db hybrid-sql)+ #_(explain-analyze-query db scored-sql)(def existing-sql (sql-format-quoted (existing-embedding-query index ["Some Text"])))#_(explain-analyze-query db existing-sql)diff --git a/enterprise/backend/src/metabase_enterprise/semantic_search/scoring.clj b/enterprise/backend/src/metabase_enterprise/semantic_search/scoring.cljindex 07cf6016f73..e56cfd09aad 100644--- a/enterprise/backend/src/metabase_enterprise/semantic_search/scoring.clj+++ b/enterprise/backend/src/metabase_enterprise/semantic_search/scoring.clj@@ -12,14 +12,6 @@[next.jdbc :as jdbc][next.jdbc.result-set :as jdbc.rs]))-(defn- ->col-expr- "For a given `col-name` return a :coalesce expression to reference it from the outer hybrid search query.-- (->col-expr :model_id) -> [:coalesce :v.model_id :t.model_id]"- [col-name]- (let [prefix #(keyword (str %1 (name %2)))]- [:coalesce (prefix "v." col-name) (prefix "t." col-name)]))-(defn- view-count-percentile-query[index-table p-value](let [expr [:raw "percentile_cont(" [:lift p-value] ") WITHIN GROUP (ORDER BY view_count)"]]@@ -53,16 +45,16 @@(defn- view-count-expr [index-table percentile](let [views (view-count-percentiles index-table percentile)cases (for [[sm v] views]- [[:= (->col-expr :model) [:inline (name sm)]] (max (or v 0) 1)])]- (search.scoring/size (->col-expr :view_count) (if (seq cases)- (into [:case] cat cases)- 1))))+ [[:= :model [:inline (name sm)]] (max (or v 0) 1)])]+ (search.scoring/size :view_count (if (seq cases)+ (into [:case] cat cases)+ 1))))(defn- model-rank-exp [{:keys [context]}](let [search-order search.config/models-search-ordern (double (count search-order))cases (map-indexed (fn [i sm]- [[:= (->col-expr :model) sm]+ [[:= :model sm](or (search.config/scorer-param context :model sm)[:inline (/ (- n i) n)])])search-order)]@@ -76,9 +68,9 @@semantic-weight 0.49][:+[:* [:cast semantic-weight :float]- [:coalesce [:/ 1.0 [:+ k [:. :v :semantic_rank]]] 0]]+ [:coalesce [:/ 1.0 [:+ k :semantic_rank]] 0]][:* [:cast keyword-weight :float]- [:coalesce [:/ 1.0 [:+ k [:. :t :keyword_rank]]] 0]]]))+ [:coalesce [:/ 1.0 [:+ k :keyword_rank]] 0]]]))(defn base-scorers"The default constituents of the search ranking scores."@@ -89,28 +81,26 @@;; given set of results. At some point, we should optimize away the irrelevant scores for any given context.{:rrf rrf-rank-exp:view-count (view-count-expr index-table search.config/view-count-scaling-percentile)- :pinned (search.scoring/truthy (->col-expr :pinned))- :recency (search.scoring/inverse-duration [:coalesce- (->col-expr :last_viewed_at)- (->col-expr :model_updated_at)]+ :pinned (search.scoring/truthy :pinned)+ :recency (search.scoring/inverse-duration [:coalesce :last_viewed_at :model_updated_at][:now]search.config/stale-time-in-days)- :dashboard (search.scoring/size (->col-expr :dashboardcard_count) search.config/dashboard-count-ceiling)+ :dashboard (search.scoring/size :dashboardcard_count search.config/dashboard-count-ceiling):model (model-rank-exp search-ctx)- :mine (search.scoring/equal (->col-expr :creator_id) (:current-user-id search-ctx))+ :mine (search.scoring/equal :creator_id (:current-user-id search-ctx)):exact (if search-string;; perform the lower casing within the database, in case it behaves differently to our helper- (search.scoring/equal [:lower (->col-expr :name)] [:lower search-string])+ (search.scoring/equal [:lower :name] [:lower search-string])[:inline 0]):prefix (if search-string;; in this case, we need to transform the string into a pattern in code, so forced to use helper- (search.scoring/prefix [:lower (->col-expr :name)] (u/lower-case-en search-string))+ (search.scoring/prefix [:lower :name] (u/lower-case-en search-string))[:inline 0])}))(def ^:private enterprise-scorers- {:official-collection {:expr (search.scoring/truthy (->col-expr :official_collection))+ {:official-collection {:expr (search.scoring/truthy :official_collection):pred #(premium-features/has-feature? :official-collections)}- :verified {:expr (search.scoring/truthy (->col-expr :verified))+ :verified {:expr (search.scoring/truthy :verified):pred #(premium-features/has-feature? :content-verification)}})(defn- additional-scorers