Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

Refactor appdb-based scorers in the semantic search backend (#62690)

appleby84763ca40d2a
diff --git a/enterprise/backend/src/metabase_enterprise/semantic_search/index.clj b/enterprise/backend/src/metabase_enterprise/semantic_search/index.clj
index dad354b6030..7f9760dc55f 100644
--- a/enterprise/backend/src/metabase_enterprise/semantic_search/index.clj
+++ b/enterprise/backend/src/metabase_enterprise/semantic_search/index.clj
@@ -593,11 +593,12 @@
"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]).
+ ;; what to call them (e.g. :model rather than [:coalesced :v.model :t.model]). Likewise, the :search_index alias
+ ;; allows us to re-use scoring expressions between the appdb and semantic backends without adjusting column names.
(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]
+ :from [[:hybrid_results :search_index]]
:limit (semantic-settings/semantic-search-results-limit)}]
(scoring/with-scores search-context scorers full-query)))
@@ -794,9 +795,10 @@
(mapv search/collapse-id))
filter-time-ms (u/since-ms filter-timer)
+ appdb-scorers (scoring/appdb-scorers search-context)
appdb-scores-timer (u/start-timer)
final-results (->> filtered-results
- (scoring/with-appdb-scores search-context))
+ (scoring/with-appdb-scores search-context appdb-scorers weights))
appdb-scores-time-ms (u/since-ms appdb-scores-timer)
total-time-ms (u/since-ms timer)]
diff --git a/enterprise/backend/src/metabase_enterprise/semantic_search/scoring.clj b/enterprise/backend/src/metabase_enterprise/semantic_search/scoring.clj
index f17a1d07ad0..c1951609a52 100644
--- a/enterprise/backend/src/metabase_enterprise/semantic_search/scoring.clj
+++ b/enterprise/backend/src/metabase_enterprise/semantic_search/scoring.clj
@@ -58,18 +58,6 @@
(into [:case] cat cases)
1))))
-(defn- model-rank-exp [{:keys [context]}]
- (let [search-order search.config/models-search-order
- n (double (count search-order))
- cases (map-indexed (fn [i sm]
- [[:= :model sm]
- (or (search.config/scorer-param context :model sm)
- [:inline (/ (- n i) n)])])
- search-order)]
- (-> (into [:case] cat (concat cases))
- ;; if you're not listed, get a very poor score
- (into [:else [:inline 0.01]]))))
-
(def ^:private rrf-rank-exp
(let [k 60
keyword-weight 0.51
@@ -87,14 +75,14 @@
{:model [:inline 1]}
;; NOTE: we calculate scores even if the weight is zero, so that it's easy to consider how we could affect any
;; given set of results. At some point, we should optimize away the irrelevant scores for any given context.
- {:rrf rrf-rank-exp
+ {:rrf rrf-rank-exp
:view-count (view-count-expr index-table search.config/view-count-scaling-percentile)
: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 :dashboardcard_count search.config/dashboard-count-ceiling)
- :model (model-rank-exp search-ctx)
+ :model (search.scoring/model-rank-expr 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
@@ -148,55 +136,31 @@
(defn- search-doc->values
[{:keys [id model]}]
- ;; :inline otherwise H2 can't deduce the types from the query params and the id is returned as text.
- [[:inline id] [:inline model]])
+ [[:cast [:inline id] :text] [:inline model]])
-(defn- user-recency-query
- [{:keys [current-user-id]} search-results]
- {:with [[[:search_docs {:columns [:model_id :model]}]
+(defn- search-index-query
+ [search-results]
+ {:with [[[:search_index {:columns [:model_id :model]}]
{:values (map search-doc->values search-results)}]]
- :select [[:sd.model_id :id]
- [:sd.model :model]
- [(search.scoring/inverse-duration [:max :rv.timestamp] [:now] search.config/stale-time-in-days)
- :user_recency]]
- :from [[:search_docs :sd]]
- :join [[:recent_views :rv]
- [:and
- [:= :rv.user_id current-user-id]
- [:= :rv.model_id :sd.model_id]
- [:=
- :rv.model
- [:case
- [:in :sd.model [[:inline "dataset"] [:inline "metric"]]]
- [:inline "card"]
- :else
- :sd.model]]]]
- :group-by [:sd.model_id :sd.model]})
-
-(defn- execute-user-recency-query!
- [search-ctx search-results]
- (t2/query (user-recency-query search-ctx search-results)))
-
-(defn- update-result-with-user-recency
- [weight grouped-recency-results search-result]
+ :select [[[:cast :search_index.model_id :int] :id]
+ [:search_index.model :model]]
+ :from [:search_index]})
+
+(defn- update-with-appdb-score
+ [weights scorers grouped-appdb-results search-result]
(let [id-model-key ((juxt :id :model) search-result)
- user-recency-row (get grouped-recency-results id-model-key)
- user-recency (:user_recency user-recency-row 0)
- contribution (* weight user-recency)]
+ appdb-row (get grouped-appdb-results id-model-key)
+ appdb-score (:total_score appdb-row 0)]
(-> search-result
- (update :score + contribution)
- (update :all-scores conj {:score user-recency
- :name :user-recency
- :weight weight
- :contribution contribution}))))
-
-(defn- update-results-with-user-recency
- [search-ctx search-results user-recency-results]
- (if-not (seq user-recency-results)
+ (update :score + appdb-score)
+ (update :all-scores concat (all-scores weights scorers appdb-row)))))
+
+(defn- update-with-appdb-scores
+ [weights scorers search-results appdb-scorer-results]
+ (if-not (seq appdb-scorer-results)
search-results
- (map (let [weight (search.config/weight (:context search-ctx) :user-recency)
- grouped-recency-results (m/index-by (juxt :id :model) user-recency-results)]
- (partial update-result-with-user-recency weight grouped-recency-results))
+ (map (let [grouped-recency-results (m/index-by (juxt :id :model) appdb-scorer-results)]
+ (partial update-with-appdb-score weights scorers grouped-recency-results))
search-results)))
(def ^:private recent-views-models
@@ -208,6 +172,15 @@
;; #{"segment" "database" "action" "indexed-entity"}
(set/difference search.spec/search-models recent-views-models))
+(defn appdb-scorers
+ "The appdb-based scorers for search ranking results. Like `base-scorers`, but for scorers that need to query the appdb."
+ [{:keys [limit-int] :as search-ctx}]
+ (when-not (and limit-int (zero? limit-int))
+ (when-not (= :mysql (mdb/db-type))
+ ;; The :user-recency scorer needs to be modified to work with mysql / mariadb (BOT-360)
+ {:user-recency (search.scoring/inverse-duration
+ (search.scoring/user-recency-expr search-ctx) [:now] search.config/stale-time-in-days)})))
+
(defn with-appdb-scores
"Add appdb-based scores to `search-results` and re-sort the results based on the new combined scores.
@@ -216,21 +189,23 @@
This will extract required info from `search-results`, make an appdb query to select additional scorers, combine
those with the existing `:score` and `:all-scores` in the `search-results`, then re-sort the results by the new
combined `:score`."
- [search-ctx search-results]
+ [search-ctx app-db-scorers weights search-results]
;; filtered-search-results are the search-results that have models that are tracked in the recent_views table,
;; i.e. results that might possibly have user-recency info.
(let [filtered-search-results (filter (comp recent-views-models :model) search-results)]
(if-not (and (seq filtered-search-results)
- ;; The user-recency-query needs to be modified to work with mysql / mariadb (BOT-360)
- (#{:postgres :h2} (mdb/db-type)))
+ (seq app-db-scorers))
search-results
- (->> (execute-user-recency-query! search-ctx filtered-search-results)
- (update-results-with-user-recency search-ctx search-results)
+ (->> (search-index-query filtered-search-results)
+ (search.scoring/with-scores search-ctx app-db-scorers)
+ t2/query
+ (update-with-appdb-scores weights (keys app-db-scorers) search-results)
(sort-by :score >)
vec))))
(comment
- (def search-ctx {:current-user-id 3})
+ (def search-ctx {:current-user-id 3
+ :context :default})
(def search-docs (-> (map-indexed
(fn [idx doc]
(assoc doc :score idx :all-scores []))
@@ -241,6 +216,6 @@
{:id 4 :model "indexed-entity"}
{:id 7 :model "card"}])
vec))
- (with-appdb-scores search-ctx search-docs)
- (->> (execute-user-recency-query! search-ctx search-docs)
- (update-results-with-user-recency search-ctx search-docs)))
+ (def weights (search.config/weights (:context search-ctx)))
+ (def app-db-scorers (appdb-scorers search-ctx))
+ (with-appdb-scores search-ctx (appdb-scorers search-ctx) weights search-docs))
diff --git a/src/metabase/search/appdb/scoring.clj b/src/metabase/search/appdb/scoring.clj
index be55ab6eaa9..1da5ca11650 100644
--- a/src/metabase/search/appdb/scoring.clj
+++ b/src/metabase/search/appdb/scoring.clj
@@ -30,18 +30,6 @@
[:inline 1]])]
(into [:case] (concat (mapcat (comp match-clause name) bookmarked-models) [:else [:inline 0]]))))
-(defn- user-recency-expr [{:keys [current-user-id]}]
- {:select [[[:max :recent_views.timestamp] :last_viewed_at]]
- :from [:recent_views]
- :where [:and
- [:= :recent_views.user_id current-user-id]
- [:= [:cast :recent_views.model_id :text] :search_index.model_id]
- [:= :recent_views.model
- [:case
- [:= :search_index.model [:inline "dataset"]] [:inline "card"]
- [:= :search_index.model [:inline "metric"]] [:inline "card"]
- :else :search_index.model]]]})
-
(defn- view-count-percentiles*
[p-value]
(into {} (for [{:keys [model vcp]} (t2/query (specialization/view-count-percentile-query
@@ -65,18 +53,6 @@
(into [:case] cat cases)
1))))
-(defn- model-rank-exp [{:keys [context]}]
- (let [search-order search.config/models-search-order
- n (double (count search-order))
- cases (map-indexed (fn [i sm]
- [[:= :search_index.model sm]
- (or (search.config/scorer-param context :model sm)
- [:inline (/ (- n i) n)])])
- search-order)]
- (-> (into [:case] cat (concat cases))
- ;; if you're not listed, get a very poor score
- (into [:else [:inline 0.01]]))))
-
(defn base-scorers
"The default constituents of the search ranking scores."
[{:keys [search-string limit-int] :as search-ctx}]
@@ -89,9 +65,9 @@
:pinned (search.scoring/truthy :pinned)
:bookmarked bookmark-score-expr
:recency (search.scoring/inverse-duration [:coalesce :last_viewed_at :model_updated_at] [:now] search.config/stale-time-in-days)
- :user-recency (search.scoring/inverse-duration (user-recency-expr search-ctx) [:now] search.config/stale-time-in-days)
+ :user-recency (search.scoring/inverse-duration (search.scoring/user-recency-expr search-ctx) [:now] search.config/stale-time-in-days)
:dashboard (search.scoring/size :dashboardcard_count search.config/dashboard-count-ceiling)
- :model (model-rank-exp search-ctx)
+ :model (search.scoring/model-rank-expr search-ctx)
:mine (search.scoring/equal :search_index.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
diff --git a/src/metabase/search/scoring.clj b/src/metabase/search/scoring.clj
index dbf2e788f84..d8d4a2c94c4 100644
--- a/src/metabase/search/scoring.clj
+++ b/src/metabase/search/scoring.clj
@@ -36,7 +36,7 @@
[:cast ceiling :float])]]])
(defn inverse-duration
- "Score at item based on the duration between two dates, where less is better."
+ "Score an item based on the duration between two dates, where less is better."
[from-column to-column ceiling-in-days]
(let [ceiling [:inline ceiling-in-days]]
[:/
@@ -50,6 +50,34 @@
[:inline 0]]
ceiling]))
+(defn user-recency-expr
+ "Expression to select the `:user-recency` timestamp for the `current-user-id`."
+ [{:keys [current-user-id]}]
+ {:select [[[:max :recent_views.timestamp] :last_viewed_at]]
+ :from [:recent_views]
+ :where [:and
+ [:= :recent_views.user_id current-user-id]
+ [:= [:cast :recent_views.model_id :text] :search_index.model_id]
+ [:= :recent_views.model
+ [:case
+ [:= :search_index.model [:inline "dataset"]] [:inline "card"]
+ [:= :search_index.model [:inline "metric"]] [:inline "card"]
+ :else :search_index.model]]]})
+
+(defn model-rank-expr
+ "Score an item based on its :model type."
+ [{:keys [context]}]
+ (let [search-order search.config/models-search-order
+ n (double (count search-order))
+ cases (map-indexed (fn [i sm]
+ [[:= :search_index.model sm]
+ (or (search.config/scorer-param context :model sm)
+ [:inline (/ (- n i) n)])])
+ search-order)]
+ (-> (into [:case] cat (concat cases))
+ ;; if you're not listed, get a very poor score
+ (into [:else [:inline 0.01]]))))
+
(defn sum-columns
"Sum the columns in `column-names`."
[column-names]
@@ -82,7 +110,6 @@
"Scoring stats for each `index-row`."
[weights scorers index-row]
(mapv (fn [k]
- ;; we shouldn't get null scores, but just in case (i.e., because there are bugs)
(let [score (or (get index-row k) 0)
weight (or (weights k) 0)]
{:score score