Skip to content

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

Add bookmarked scorer to semantic search backend (#62709)

appleby7227b7d97c29
diff --git a/enterprise/backend/src/metabase_enterprise/semantic_search/scoring.clj b/enterprise/backend/src/metabase_enterprise/semantic_search/scoring.clj
index c1951609a52..7403c4e791e 100644
--- a/enterprise/backend/src/metabase_enterprise/semantic_search/scoring.clj
+++ b/enterprise/backend/src/metabase_enterprise/semantic_search/scoring.clj
@@ -166,20 +166,24 @@
(def ^:private recent-views-models
(into #{} (map name activity-feed/rv-models)))
+(def ^:private appdb-scorer-models
+ (into recent-views-models (map name search.scoring/bookmarked-models-and-sub-models)))
+
(comment
(require '[clojure.set :as set]
'[metabase.search.spec :as search.spec])
;; #{"segment" "database" "action" "indexed-entity"}
- (set/difference search.spec/search-models recent-views-models))
+ (set/difference search.spec/search-models appdb-scorer-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)})))
+ (merge {:bookmarked search.scoring/bookmark-score-expr}
+ (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.
@@ -189,17 +193,19 @@
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 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)
- (seq app-db-scorers))
+ [search-ctx appdb-scorers weights search-results]
+ ;; search-results-to-score are the search-results that have models that are relevant to the appdb-scorers.
+ (let [{:keys [current-user-id]} search-ctx
+ search-results-to-score (filter (comp appdb-scorer-models :model) search-results)
+ maybe-join-bookmarks #(cond-> % (:bookmarked appdb-scorers) (search.scoring/join-bookmarks current-user-id))]
+ (if-not (and (seq search-results-to-score)
+ (seq appdb-scorers))
search-results
- (->> (search-index-query filtered-search-results)
- (search.scoring/with-scores search-ctx app-db-scorers)
+ (->> (search-index-query search-results-to-score)
+ (search.scoring/with-scores search-ctx appdb-scorers)
+ maybe-join-bookmarks
t2/query
- (update-with-appdb-scores weights (keys app-db-scorers) search-results)
+ (update-with-appdb-scores weights (keys appdb-scorers) search-results)
(sort-by :score >)
vec))))
diff --git a/enterprise/backend/test/metabase_enterprise/semantic_search/scoring_test.clj b/enterprise/backend/test/metabase_enterprise/semantic_search/scoring_test.clj
index c317266eca6..24fa7dfe0d3 100644
--- a/enterprise/backend/test/metabase_enterprise/semantic_search/scoring_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/semantic_search/scoring_test.clj
@@ -160,37 +160,6 @@
["card" 1 "card ancient"]]
(search-results :recency "card"))))))))
-(deftest user-recency-test
- (let [user-id (mt/user->id :crowberto)
- right-now (Instant/now)
- long-ago (.minus right-now 10 ChronoUnit/DAYS)
- forever-ago (.minus right-now 30 ChronoUnit/DAYS)
- recent-view (fn [model-id timestamp]
- {:model "card"
- :model_id model-id
- :user_id user-id
- :timestamp timestamp})]
- (mt/with-temp [:model/Card {c1 :id} {}
- :model/Card {c2 :id} {}
- :model/Card {c3 :id} {}
- :model/Card {c4 :id} {}
- :model/RecentViews _ (recent-view c1 forever-ago)
- :model/RecentViews _ (recent-view c2 right-now)
- :model/RecentViews _ (recent-view c2 forever-ago)
- :model/RecentViews _ (recent-view c4 forever-ago)
- :model/RecentViews _ (recent-view c4 long-ago)]
- (with-index-contents!
- [{:model "card" :id c1 :name "card ancient"}
- {:model "metric" :id c2 :name "card recent"}
- {:model "dataset" :id c3 :name "card unseen"}
- {:model "dataset" :id c4 :name "card old"}]
- (testing "We prefer results more recently viewed by the current user"
- (is (= [["metric" c2 "card recent"]
- ["dataset" c4 "card old"]
- ["card" c1 "card ancient"]
- ["dataset" c3 "card unseen"]]
- (search-results :user-recency "card" {:current-user-id user-id}))))))))
-
(deftest view-count-test
(mt/with-premium-features #{:semantic-search}
(testing "the more view count the better"
@@ -242,3 +211,73 @@
[{:model "card" :id 1 :name "card popular" :dashboardcard_count 200}
{:model "card" :id 2 :name "card" :dashboardcard_count 201}]
(is (indifferent? :dashboard "card"))))))
+
+(deftest bookmark-test
+ (let [crowberto (mt/user->id :crowberto)
+ rasta (mt/user->id :rasta)]
+ (mt/with-temp [:model/Card {c1 :id} {}
+ :model/Card {c2 :id} {}]
+ (testing "bookmarked items are ranker higher"
+ (with-index-contents!
+ [{:model "card" :id c1 :name "card normal"}
+ {:model "card" :id c2 :name "card crowberto loved"}]
+ (mt/with-temp [:model/CardBookmark _ {:card_id c2 :user_id crowberto}
+ :model/CardBookmark _ {:card_id c1 :user_id rasta}]
+ (is (= [["card" c2 "card crowberto loved"]
+ ["card" c1 "card normal"]]
+ (search-results :bookmarked "card" {:current-user-id crowberto})))))))
+
+ (mt/with-temp [:model/Dashboard {d1 :id} {}
+ :model/Dashboard {d2 :id} {}]
+ (testing "bookmarked dashboard"
+ (with-index-contents!
+ [{:model "dashboard" :id d1 :name "dashboard normal"}
+ {:model "dashboard" :id d2 :name "dashboard crowberto loved"}]
+ (mt/with-temp [:model/DashboardBookmark _ {:dashboard_id d2 :user_id crowberto}
+ :model/DashboardBookmark _ {:dashboard_id d1 :user_id rasta}]
+ (is (= [["dashboard" d2 "dashboard crowberto loved"]
+ ["dashboard" d1 "dashboard normal"]]
+ (search-results :bookmarked "dashboard" {:current-user-id crowberto})))))))
+
+ (mt/with-temp [:model/Collection {c1 :id} {}
+ :model/Collection {c2 :id} {}]
+ (testing "bookmarked collection"
+ (with-index-contents!
+ [{:model "collection" :id c1 :name "collection normal"}
+ {:model "collection" :id c2 :name "collection crowberto loved"}]
+ (mt/with-temp [:model/CollectionBookmark _ {:collection_id c2 :user_id crowberto}
+ :model/CollectionBookmark _ {:collection_id c1 :user_id rasta}]
+ (is (= [["collection" c2 "collection crowberto loved"]
+ ["collection" c1 "collection normal"]]
+ (search-results :bookmarked "collection" {:current-user-id crowberto})))))))))
+
+(deftest user-recency-test
+ (let [user-id (mt/user->id :crowberto)
+ right-now (Instant/now)
+ long-ago (.minus right-now 10 ChronoUnit/DAYS)
+ forever-ago (.minus right-now 30 ChronoUnit/DAYS)
+ recent-view (fn [model-id timestamp]
+ {:model "card"
+ :model_id model-id
+ :user_id user-id
+ :timestamp timestamp})]
+ (mt/with-temp [:model/Card {c1 :id} {}
+ :model/Card {c2 :id} {}
+ :model/Card {c3 :id} {}
+ :model/Card {c4 :id} {}
+ :model/RecentViews _ (recent-view c1 forever-ago)
+ :model/RecentViews _ (recent-view c2 right-now)
+ :model/RecentViews _ (recent-view c2 forever-ago)
+ :model/RecentViews _ (recent-view c4 forever-ago)
+ :model/RecentViews _ (recent-view c4 long-ago)]
+ (with-index-contents!
+ [{:model "card" :id c1 :name "card ancient"}
+ {:model "metric" :id c2 :name "card recent"}
+ {:model "dataset" :id c3 :name "card unseen"}
+ {:model "dataset" :id c4 :name "card old"}]
+ (testing "We prefer results more recently viewed by the current user"
+ (is (= [["metric" c2 "card recent"]
+ ["dataset" c4 "card old"]
+ ["card" c1 "card ancient"]
+ ["dataset" c3 "card unseen"]]
+ (search-results :user-recency "card" {:current-user-id user-id}))))))))
diff --git a/src/metabase/search/appdb/scoring.clj b/src/metabase/search/appdb/scoring.clj
index 1da5ca11650..cb2807afc63 100644
--- a/src/metabase/search/appdb/scoring.clj
+++ b/src/metabase/search/appdb/scoring.clj
@@ -16,20 +16,6 @@
[weights scorers index-row]
(search.scoring/all-scores weights scorers index-row))
-;; TODO move these to the spec definitions
-(def ^:private bookmarked-models [:card :collection :dashboard])
-
-(def ^:private sub-models {:card [:card :metric :dataset]})
-
-(def ^:private bookmark-score-expr
- (let [match-clause (fn [m] [[:and
- (if-let [sms (sub-models (keyword m))]
- [:in :search_index.model (mapv (fn [k] [:inline (name k)]) sms)]
- [:= :search_index.model [:inline m]])
- [:!= nil (keyword (str m "_bookmark." m "_id"))]]
- [:inline 1]])]
- (into [:case] (concat (mapcat (comp match-clause name) bookmarked-models) [:else [:inline 0]]))))
-
(defn- view-count-percentiles*
[p-value]
(into {} (for [{:keys [model vcp]} (t2/query (specialization/view-count-percentile-query
@@ -63,7 +49,7 @@
{:text (specialization/text-score)
:view-count (view-count-expr search.config/view-count-scaling-percentile)
:pinned (search.scoring/truthy :pinned)
- :bookmarked bookmark-score-expr
+ :bookmarked search.scoring/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 (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)
@@ -84,23 +70,9 @@
[search-ctx]
(base-scorers search-ctx))
-(defn- bookmark-join [model user-id]
- (let [model-name (name model)
- table-name (str model-name "_bookmark")]
- [(keyword table-name)
- [:and
- (if-let [sms (sub-models model)]
- [:in :search_index.model (mapv (fn [m] [:inline (name m)]) sms)]
- [:= :search_index.model [:inline model-name]])
- [:= (keyword (str table-name ".user_id")) user-id]
- [:= :search_index.model_id [:cast (keyword (str table-name "." model-name "_id")) :text]]]]))
-
-(defn- join-bookmarks [qry user-id]
- (apply sql.helpers/left-join qry (mapcat #(bookmark-join % user-id) bookmarked-models)))
-
(defn with-scores
"Add a bunch of SELECT columns for the individual and total scores, and a corresponding ORDER BY."
[{:keys [current-user-id] :as search-ctx} scorers qry]
(-> (search.scoring/with-scores search-ctx scorers qry)
- (join-bookmarks current-user-id)
+ (search.scoring/join-bookmarks current-user-id)
(sql.helpers/order-by [:total_score :desc])))
diff --git a/src/metabase/search/scoring.clj b/src/metabase/search/scoring.clj
index d8d4a2c94c4..b5091ad3582 100644
--- a/src/metabase/search/scoring.clj
+++ b/src/metabase/search/scoring.clj
@@ -78,6 +78,41 @@
;; if you're not listed, get a very poor score
(into [:else [:inline 0.01]]))))
+;; TODO move these to the spec definitions
+(def ^:private bookmarked-models [:card :collection :dashboard])
+
+(def ^:private bookmarked-sub-models {:card [:card :metric :dataset]})
+
+(def bookmarked-models-and-sub-models
+ "Set that is the union of all bookmarked-models and bookmarked-sub-models"
+ (into (set bookmarked-models) cat (vals bookmarked-sub-models)))
+
+(def bookmark-score-expr
+ "Score an item based on whether it has been bookmarked."
+ (let [match-clause (fn [m] [[:and
+ (if-let [sms (bookmarked-sub-models (keyword m))]
+ [:in :search_index.model (mapv (fn [k] [:inline (name k)]) sms)]
+ [:= :search_index.model [:inline m]])
+ [:!= nil (keyword (str m "_bookmark." m "_id"))]]
+ [:inline 1]])]
+ (into [:case] (concat (mapcat (comp match-clause name) bookmarked-models) [:else [:inline 0]]))))
+
+(defn- bookmark-join [model user-id]
+ (let [model-name (name model)
+ table-name (str model-name "_bookmark")]
+ [(keyword table-name)
+ [:and
+ (if-let [sms (bookmarked-sub-models model)]
+ [:in :search_index.model (mapv (fn [m] [:inline (name m)]) sms)]
+ [:= :search_index.model [:inline model-name]])
+ [:= (keyword (str table-name ".user_id")) user-id]
+ [:= :search_index.model_id [:cast (keyword (str table-name "." model-name "_id")) :text]]]]))
+
+(defn join-bookmarks
+ "Add join clause to bookmark tables for :bookmarked scorer."
+ [qry user-id]
+ (apply sql.helpers/left-join qry (mapcat #(bookmark-join % user-id) bookmarked-models)))
+
(defn sum-columns
"Sum the columns in `column-names`."
[column-names]