Skip to content

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

Add view_count scorer to semantic search backend (#62086)

appleby861d7bf0291a
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.edn
index e2db34921d1..efd2718951d 100644
--- a/.clj-kondo/config/modules/config.edn
+++ b/.clj-kondo/config/modules/config.edn
@@ -1831,6 +1831,7 @@
metabase-enterprise.semantic-search.init}
:uses #{analytics
api
+ config
connection-pool
models
permissions
diff --git a/enterprise/backend/src/metabase_enterprise/semantic_search/index.clj b/enterprise/backend/src/metabase_enterprise/semantic_search/index.clj
index c7b2ecf5475..b06471731d3 100644
--- a/enterprise/backend/src/metabase_enterprise/semantic_search/index.clj
+++ b/enterprise/backend/src/metabase_enterprise/semantic_search/index.clj
@@ -742,7 +742,7 @@
db-timer (u/start-timer)
weights (search.config/weights (:context search-context))
- scorers (scoring/semantic-scorers 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))
xform (comp (map decode-metadata)
diff --git a/enterprise/backend/src/metabase_enterprise/semantic_search/scoring.clj b/enterprise/backend/src/metabase_enterprise/semantic_search/scoring.clj
index 6323bdd057d..07cf6016f73 100644
--- a/enterprise/backend/src/metabase_enterprise/semantic_search/scoring.clj
+++ b/enterprise/backend/src/metabase_enterprise/semantic_search/scoring.clj
@@ -1,10 +1,16 @@
(ns metabase-enterprise.semantic-search.scoring
(:require
+ [clojure.core.memoize :as memoize]
+ [honey.sql :as sql]
[honey.sql.helpers :as sql.helpers]
+ [metabase-enterprise.semantic-search.db.datasource :as semantic.db.datasource]
+ [metabase.config.core :as config]
[metabase.premium-features.core :as premium-features]
[metabase.search.config :as search.config]
[metabase.search.scoring :as search.scoring]
- [toucan2.util :as u]))
+ [metabase.util :as u]
+ [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.
@@ -14,6 +20,44 @@
(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)"]]
+ {:select [:search_index.model [expr :vcp]]
+ :from [[(keyword index-table) :search_index]]
+ :group-by [:search_index.model]
+ :having [:is-not expr nil]}))
+
+(defn- view-count-percentiles*
+ [index-table p-value]
+ (into {} (for [{:keys [model vcp]}
+ ;; Get the db data-source directly rather than passing it in as an argument to this function to
+ ;; side-step potential issues with using the db as a cache key for the memoized version.
+ ;; https://github.com/metabase/metabase/pull/62086#discussion_r2272790618
+ (jdbc/execute! (semantic.db.datasource/ensure-initialized-data-source!)
+ (-> (view-count-percentile-query
+ index-table
+ p-value)
+ (sql/format {:quoted true}))
+ {:builder-fn jdbc.rs/as-unqualified-lower-maps})]
+ [(keyword model) vcp])))
+
+(def ^{:private true
+ :arglists '([index-table p-value])}
+ view-count-percentiles
+ (if config/is-prod?
+ (memoize/ttl view-count-percentiles*
+ :ttl/threshold (u/hours->ms 1))
+ view-count-percentiles*))
+
+(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))))
+
(defn- model-rank-exp [{:keys [context]}]
(let [search-order search.config/models-search-order
n (double (count search-order))
@@ -38,29 +82,30 @@
(defn base-scorers
"The default constituents of the search ranking scores."
- [{:keys [search-string limit-int] :as search-ctx}]
+ [index-table {:keys [search-string limit-int] :as search-ctx}]
(if (and limit-int (zero? limit-int))
{: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
- :pinned (search.scoring/truthy (->col-expr :pinned))
- :recency (search.scoring/inverse-duration [:coalesce
- (->col-expr :last_viewed_at)
- (->col-expr :model_updated_at)]
- [:now]
- search.config/stale-time-in-days)
- :dashboard (search.scoring/size (->col-expr :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))
- :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])
- [: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))
- [:inline 0])}))
+ :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)]
+ [:now]
+ search.config/stale-time-in-days)
+ :dashboard (search.scoring/size (->col-expr :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))
+ :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])
+ [: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))
+ [:inline 0])}))
(def ^:private enterprise-scorers
{:official-collection {:expr (search.scoring/truthy (->col-expr :official_collection))
@@ -79,8 +124,8 @@
(defn semantic-scorers
"Return the select-item expressions used to calculate the score for semantic search results."
- [search-ctx]
- (merge (base-scorers search-ctx)
+ [index-table search-ctx]
+ (merge (base-scorers index-table search-ctx)
(additional-scorers)))
(defn with-scores
@@ -93,3 +138,8 @@
"Score stats for each scorer"
[weights scorers index-row]
(search.scoring/all-scores weights scorers index-row))
+
+(comment
+ (def embedding-model ((requiring-resolve 'metabase-enterprise.semantic-search.embedding/get-configured-model)))
+ (def index ((requiring-resolve 'metabase-enterprise.semantic-search.index/default-index) embedding-model))
+ (def index-table (:table-name index)))
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 7cf35e1a023..c2e796e86e5 100644
--- a/enterprise/backend/test/metabase_enterprise/semantic_search/scoring_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/semantic_search/scoring_test.clj
@@ -1,9 +1,12 @@
(ns metabase-enterprise.semantic-search.scoring-test
(:require
+ [clojure.core.memoize :as memoize]
[clojure.test :refer :all]
[metabase-enterprise.semantic-search.index :as semantic.index]
+ [metabase-enterprise.semantic-search.scoring :as semantic.scoring]
[metabase-enterprise.semantic-search.test-util :as semantic.tu]
[metabase.search.appdb.scoring-test :refer [with-weights]]
+ [metabase.search.config :as search.config]
[metabase.test :as mt])
(:import
(java.time Instant)
@@ -34,15 +37,20 @@
(semantic.tu/upsert-index! (map add-doc-defaults ~documents))
~@body))
+(defn search-results**
+ [search-string raw-ctx]
+ (memoize/memo-clear! #'semantic.scoring/view-count-percentiles)
+ ;; side-step filter-read-permitted for these tests
+ (mt/with-dynamic-fn-redefs [semantic.index/filter-read-permitted identity]
+ (semantic.tu/query-index (merge {:search-string search-string
+ :search-engine "semantic"
+ :current-user-id (mt/user->id :rasta)}
+ raw-ctx))))
+
(defn search-results*
[search-string & {:as raw-ctx}]
(mapv (juxt :model :id :name)
- ;; side-step permissions for these tests
- (mt/with-dynamic-fn-redefs [semantic.index/filter-read-permitted identity]
- (semantic.tu/query-index (merge {:search-string search-string
- :search-engine "semantic"
- :current-user-id (mt/user->id :rasta)}
- raw-ctx)))))
+ (search-results** search-string raw-ctx)))
(defn search-results
"Like search-results* but with a sanity check that search without weights returns a different result."
@@ -152,6 +160,34 @@
["card" 1 "card ancient"]]
(search-results :recency "card"))))))))
+(deftest view-count-test
+ (mt/with-premium-features #{:semantic-search}
+ (testing "the more view count the better"
+ (with-index-contents!
+ [{:model "card" :id 1 :name "card well known" :view_count 10}
+ {:model "card" :id 2 :name "card famous" :view_count 100}
+ {:model "card" :id 3 :name "card popular" :view_count 50}]
+ (is (= [["card" 2 "card famous"]
+ ["card" 3 "card popular"]
+ ["card" 1 "card well known"]]
+ (search-results :view-count "card")))))))
+
+(deftest view-count-test-2
+ (mt/with-premium-features #{:semantic-search}
+ (testing "don't error on fresh instances with no view count"
+ (with-index-contents!
+ [{:model "card" :id 1 :name "view card" :view_count 0}
+ {:model "dashboard" :id 2 :name "view dashboard" :view_count 0}
+ {:model "dataset" :id 3 :name "view dataset" :view_count 0}]
+ ;; fix some test flakes where dataset 3 exists and has some sort of recent views
+ (with-weights (assoc (search.config/weights :default)
+ :user-recency 0
+ :rrf 0)
+ (is (=? [{:model "dashboard", :id 2, :name "view dashboard"}
+ {:model "card", :id 1, :name "view card"}
+ {:model "dataset", :id 3, :name "view dataset"}]
+ (search-results** "view" {}))))))))
+
(deftest dashboard-count-test
(mt/with-premium-features #{:semantic-search}
(testing "cards used in dashboard have higher rank"