Line data Source code
1 4 : (ns matchscore.domain.player-follow.search
2 : "Finding players of the imported tours (PSA, ESF) by name, so users
3 : can follow them without browsing a ranking first.
4 :
5 : Matching ignores case, accents and punctuation: every word of the query has to
6 : start a word of the name (\"elias\" and \"die eli\" find \"Diego Elías\"). Names that
7 : start with the query come first, then ranked players by their best current rank.
8 : ESF players can also be found by ESF id (\"ES662969162\").
9 :
10 : Each result's :player-id is the follow key of its source, so results can be
11 : followed and opened as profiles (/players/<source>/<id>) directly. ESF players
12 : without ESF membership (no ESID) and players from excluded countries are left out."
13 : (:require
14 : [clojure.string :as str]
15 : [matchscore.domain.country-exclusion :as country-exclusion]
16 : [next.jdbc :as jdbc]
17 : [next.jdbc.result-set :as rs]))
18 :
19 :
20 16 : (def sources #{"psa" "esf"})
21 :
22 :
23 8 : (def default-limit 20)
24 :
25 :
26 8 : (def max-limit 50)
27 :
28 :
29 8 : (def min-query-length 2)
30 :
31 :
32 4 : (defn- norm
33 : "SQL expression: `expr` lower-cased, without accents (NFD marks dropped), with the
34 : letters that don't decompose (ø, ł, ß...) spelled in plain Latin, apostrophes
35 : dropped and other punctuation turned into single spaces (\"O'Connor\" → \"oconnor\",
36 : \"Osborne - Wylde\" → \"osborne wylde\")."
37 : [expr]
38 6 : (str
39 : "trim(regexp_replace(regexp_replace("
40 1 : "replace(replace(replace(translate(regexp_replace(normalize(lower(coalesce(" expr
41 : ", '')), NFD), '[\\u0300-\\u036f]', '', 'g'), 'øłđıðþ', 'oldidp'), 'æ', 'ae'), 'œ', 'oe'), 'ß', 'ss')"
42 : ", '[''’`]', '', 'g'), '[-.,_/()[:space:]]+', ' ', 'g'))"))
43 :
44 :
45 4 : (defn query-terms
46 : "Words of the user's query, without LIKE wildcards, at most 4; nil when the query
47 : is too short to search."
48 : [raw]
49 72 : (let [cleaned (some->
50 3 : raw
51 3 : str
52 9 : (str/replace #"[%_\\]" " ")
53 3 : str/trim)]
54 31 : (when (and cleaned (>= (count cleaned) min-query-length))
55 6 : (->>
56 12 : (str/split cleaned #"\s+")
57 9 : (remove str/blank?)
58 9 : (take 4)
59 3 : vec
60 3 : not-empty))))
61 :
62 :
63 4 : (defn parse-esid
64 : "The ESF id typed as \"ES662969162\" or \"662969162\", else nil."
65 : [raw]
66 58 : (when-let [[_ digits] (some->>
67 2 : raw
68 2 : str
69 2 : str/trim
70 2 : (re-matches #"(?i)(?:ES)?([0-9]{5,12})"))]
71 6 : (parse-long digits)))
72 :
73 :
74 4 : (defn- name-filter
75 : "WHERE fragment and params: every term starts a word of the normalised `name-col`
76 : (\"eli\" finds \"Diego Elías\", but \"ali\" doesn't find \"Walid\")."
77 : [name-col terms]
78 5 : [(str
79 : "("
80 3 : (str/join
81 : " AND "
82 2 : (repeat
83 2 : (count terms)
84 11 : (str "' ' || " (norm name-col) " LIKE '% ' || " (norm "?::text") " || '%'")))
85 : ")")
86 1 : terms])
87 :
88 :
89 4 : (defn- prefix-score
90 : "ORDER BY fragment and params: 0 when the name starts with the query, else 1."
91 : [name-col terms]
92 12 : [(str "CASE WHEN " (norm name-col) " LIKE " (norm "?::text") " || '%' THEN 0 ELSE 1 END")
93 5 : [(str/join " " terms)]])
94 :
95 :
96 4 : (def ^:private psa-sql
97 : "PSA players with their best rank in the newest snapshot of each list."
98 36 : {:with
99 : "WITH latest AS (
100 : SELECT list, max(snapshot_date) AS snapshot_date FROM psa_ranking_entries GROUP BY list),
101 : best AS (
102 : SELECT DISTINCT ON (r.psa_player_id) r.psa_player_id, r.rank, r.list
103 : FROM psa_ranking_entries r
104 : JOIN latest l ON l.list = r.list AND l.snapshot_date = r.snapshot_date
105 : ORDER BY r.psa_player_id, r.rank)"
106 : :name "pp.full_name"
107 : :query
108 : "SELECT pp.psa_id::text AS player_id, pp.full_name, pp.country_code, pp.photo_url,
109 : b.rank, b.list AS ranking
110 : FROM psa_players pp
111 : LEFT JOIN best b ON b.psa_player_id = pp.psa_id
112 : WHERE %s AND %s"
113 : :country "pp.country_code"})
114 :
115 :
116 4 : (def ^:private esf-sql
117 : "ESF members (ESID) from the rankings and the imported draws. The rank is the best
118 : one in the newest publication of each circuit, preferring an age category over
119 : the Overall list. The photo comes from an imported draw."
120 44 : {:with
121 : "WITH latest AS (
122 : SELECT circuit, max(publication_id) AS publication_id
123 : FROM esf_ranking_categories GROUP BY circuit),
124 : best AS (
125 : SELECT DISTINCT ON (e.esid) e.esid, e.rank, c.name AS ranking
126 : FROM esf_ranking_entries e
127 : JOIN esf_ranking_categories c
128 : ON c.publication_id = e.publication_id AND c.category_id = e.category_id
129 : JOIN latest l ON l.circuit = c.circuit AND l.publication_id = c.publication_id
130 : WHERE e.esid ~ '^ES[0-9]{1,12}$'
131 : ORDER BY e.esid, (c.name ILIKE '%overall%'), e.rank),
132 : draw_users AS (
133 : SELECT DISTINCT ON (rankedin_id) rankedin_id AS esid,
134 : NULLIF(trim(concat_ws(' ', first_name, last_name)), '') AS full_name,
135 : country_code, photo_url
136 : FROM rankedin_users
137 : WHERE source = 'esf' AND rankedin_id > 0
138 : ORDER BY rankedin_id, (photo_url IS NULL), created_datetime DESC),
139 : ranked AS (
140 : SELECT DISTINCT ON (esid) substr(esid, 3)::bigint AS esid, full_name, country_code
141 : FROM esf_ranking_entries
142 : WHERE esid ~ '^ES[0-9]{1,12}$'
143 : ORDER BY esid, publication_id DESC),
144 : people AS (
145 : SELECT COALESCE(r.esid, d.esid) AS esid,
146 : COALESCE(r.full_name, d.full_name) AS full_name,
147 : COALESCE(r.country_code, d.country_code) AS country_code,
148 : d.photo_url
149 : FROM ranked r
150 : FULL JOIN draw_users d ON d.esid = r.esid)"
151 : :name "p.full_name"
152 : :id-col "p.esid"
153 : :query
154 : "SELECT p.esid::text AS player_id, p.full_name, p.country_code, p.photo_url,
155 : b.rank, b.ranking
156 : FROM people p
157 : LEFT JOIN best b ON b.esid = 'ES' || p.esid::text
158 : WHERE p.full_name IS NOT NULL AND %s AND %s"
159 : :country "p.country_code"})
160 :
161 :
162 4 : (def ^:private source-sql
163 16 : {"psa" psa-sql
164 4 : "esf" esf-sql})
165 :
166 :
167 4 : (defn clamp-limit
168 : [limit]
169 3 : (->
170 17 : (or limit default-limit)
171 6 : (max 1)
172 3 : (min max-limit)))
173 :
174 :
175 4 : (defn all-players
176 : "Every searchable player of `source` (psa, esf) with the same fields as
177 : `search-players`, for building the search index. Empty for an unknown source."
178 : [ds source]
179 8 : (if-let [{:keys [with query country]} (source-sql source)]
180 3 : (mapv
181 5 : #(assoc % :source source)
182 2 : (jdbc/execute!
183 1 : ds
184 12 : [(str with " " (format query "TRUE" (country-exclusion/allowed-sql country)))]
185 3 : {:builder-fn rs/as-unqualified-kebab-maps}))
186 0 : []))
187 :
188 :
189 4 : (defn search-players
190 : "Players of `source` whose name matches `raw-query`, best matches first, at most
191 : `limit`: [{:source :player-id :full-name :country-code :photo-url :rank :ranking}].
192 : Empty for an unknown source or a query shorter than two characters."
193 : [ds source raw-query limit]
194 4 : (let [terms (query-terms raw-query)
195 3 : spec (source-sql source)]
196 9 : (if-not (and terms spec)
197 1 : []
198 2 : (let [{:keys [with name id-col query country]} spec
199 6 : id (when id-col (parse-esid raw-query))
200 13 : [filter-sql filter-params] (if id [(str id-col " = ?") [id]] (name-filter name terms))
201 4 : [score-sql score-params] (prefix-score "found.full_name" terms)
202 7 : sql (str
203 1 : with
204 : " SELECT * FROM ("
205 7 : (format query filter-sql (country-exclusion/allowed-sql country))
206 : ") found"
207 1 : " ORDER BY " score-sql
208 : ", found.rank IS NULL, found.rank, found.full_name, found.player_id" " LIMIT ?")]
209 3 : (mapv
210 5 : #(assoc % :source source)
211 2 : (jdbc/execute!
212 1 : ds
213 12 : (into [sql] (concat filter-params score-params [(clamp-limit limit)]))
214 3 : {:builder-fn rs/as-unqualified-kebab-maps}))))))
|