mirror of
https://github.com/block/buzz.git
synced 2026-11-30 21:21:48 +00:00
feat(search): order kind-0 hits by name match before body matches
Profile lookups (`kinds == [0]`) search the whole kind-0 JSON, so `about` text or an inline avatar's base64 can match the query on many rows that are not the person being looked for: the real "Wes" sat at row 121 behind 111 agent profiles whose shared avatar data URL happens to contain the lexeme `wes`. Add a `name_match` select column that applies the WHERE clause's own tsquery to the `name`, `display_name`, and `displayName` fields, guarded by `pg_input_is_valid` so rows that predate ingest-side JSON validation never raise on `::jsonb`, and order by it first. The existing one- or two-character exact-lexeme boost keeps its place after it. Gated on kinds alone so the WebSocket full-text path benefits as well as the bridge prefix typeahead. Adds `kind0_prefix_orders_name_match_before_newer_body_match`, which fails with the ORDER BY term removed (verified by mutation). The existing `short_kind0_prefix_prioritizes_exact_lexeme_on_a_noisy_page` and `kind0_search_by_display_name_works_without_flattening` pass unchanged. The test file's pre-existing local dev database URL gains the same `sadscan:disable` marker the buzz-db test modules carry, so the secrets pre-commit scan accepts the file. Verified against local PostgreSQL 17.9 with `scripts/postgres-test-run.sh -p buzz-search --tests` (21 passed), plus `cargo fmt` and `cargo clippy -p buzz-search --all-targets -D warnings`. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Signed-off-by: Matt Toohey <contact@matttoohey.com>
This commit is contained in:
@@ -199,17 +199,20 @@ fn normalized_search_text(q: &str) -> Option<String> {
|
||||
|
||||
/// Execute a community-scoped FTS query.
|
||||
///
|
||||
/// SQL shape (always):
|
||||
/// SQL shape (bracketed parts are emitted only for `kinds == [0]`):
|
||||
/// ```sql
|
||||
/// SELECT id, kind, pubkey, channel_id, EXTRACT(EPOCH FROM created_at)::bigint AS created_at_s,
|
||||
/// ts_rank_cd(search_tsv, query) AS rank
|
||||
/// [, <profile name fields as tsvector> @@ query AS name_match]
|
||||
/// FROM events,
|
||||
/// <mode-specific tsquery> AS query
|
||||
/// WHERE community_id = $ctx
|
||||
/// AND deleted_at IS NULL
|
||||
/// AND search_tsv @@ query
|
||||
/// [+ channel scope, kinds, authors, since, until]
|
||||
/// ORDER BY rank DESC, created_at DESC, id
|
||||
/// ORDER BY [name_match DESC,]
|
||||
/// [search_tsv @@ websearch_to_tsquery('simple', $q) DESC,] -- prefix mode, ≤ 2 chars
|
||||
/// rank DESC, created_at DESC, id
|
||||
/// LIMIT $per_page OFFSET (($page - 1) * $per_page)
|
||||
/// ```
|
||||
///
|
||||
@@ -232,21 +235,42 @@ pub async fn search(pool: &PgPool, query: &SearchQuery) -> Result<SearchResult,
|
||||
};
|
||||
let page = query.page.clamp(1, PAGE_MAX);
|
||||
let offset = ((page - 1) as i64) * (per_page_actual as i64);
|
||||
// Profile typeahead uses broad prefix matching. For one- and two-character
|
||||
// queries, a busy community can have enough newer prefix matches to push a
|
||||
// short exact display name off the bounded first page. Keep the same result
|
||||
// set and pagination contract, but put rows containing the whole lexeme
|
||||
// first for this one narrow caller shape.
|
||||
let prioritize_exact_profile_lexeme = query.mode == SearchMode::Prefix
|
||||
&& query.kinds.as_deref() == Some(&[0][..])
|
||||
&& search_text.chars().count() <= 2;
|
||||
// Profile lookups search the whole kind-0 JSON, so `about` text or an
|
||||
// inline avatar's base64 can match the query on many rows that are not the
|
||||
// person being looked for. Keep the same result set and pagination
|
||||
// contract, but order rows whose name fields match ahead of body-only
|
||||
// matches. Gated on kinds alone so the WebSocket full-text path benefits
|
||||
// as well as the prefix typeahead.
|
||||
let profile_query = query.kinds.as_deref() == Some(&[0][..]);
|
||||
// For one- and two-character prefix queries, a busy community can have
|
||||
// enough newer prefix matches to push a short exact display name off the
|
||||
// bounded first page. Put rows containing the whole lexeme first for this
|
||||
// one narrow caller shape.
|
||||
let prioritize_exact_profile_lexeme =
|
||||
profile_query && query.mode == SearchMode::Prefix && search_text.chars().count() <= 2;
|
||||
|
||||
let mut qb: QueryBuilder<sqlx::Postgres> = QueryBuilder::new(
|
||||
"SELECT id, kind, pubkey, channel_id, \
|
||||
EXTRACT(EPOCH FROM created_at)::bigint AS created_at_s, \
|
||||
ts_rank_cd(search_tsv, search_query.query) AS rank \
|
||||
FROM events CROSS JOIN LATERAL (SELECT ",
|
||||
ts_rank_cd(search_tsv, search_query.query) AS rank",
|
||||
);
|
||||
if profile_query {
|
||||
// The same tsquery as the WHERE clause, applied to the name fields
|
||||
// only, so both sides normalize identically. `CASE` skips the `THEN`
|
||||
// arm when the guard is false, so rows that predate ingest-side JSON
|
||||
// validation never raise on `::jsonb`; a non-object document yields
|
||||
// NULL from `->>`, an empty vector, and `false`. `pg_input_is_valid`
|
||||
// needs PostgreSQL 16 or later.
|
||||
qb.push(
|
||||
", CASE WHEN pg_input_is_valid(content, 'jsonb') \
|
||||
THEN to_tsvector('simple', concat_ws(' ', \
|
||||
content::jsonb ->> 'name', \
|
||||
content::jsonb ->> 'display_name', \
|
||||
content::jsonb ->> 'displayName')) @@ search_query.query \
|
||||
ELSE false END AS name_match",
|
||||
);
|
||||
}
|
||||
qb.push(" FROM events CROSS JOIN LATERAL (SELECT ");
|
||||
push_tsquery(&mut qb, query.mode, &search_text);
|
||||
qb.push(" AS query) AS search_query WHERE community_id = ");
|
||||
qb.push_bind(*query.community.as_uuid());
|
||||
@@ -306,13 +330,16 @@ pub async fn search(pool: &PgPool, query: &SearchQuery) -> Result<SearchResult,
|
||||
qb.push(")");
|
||||
}
|
||||
|
||||
if prioritize_exact_profile_lexeme {
|
||||
qb.push(" ORDER BY search_tsv @@ websearch_to_tsquery('simple', ");
|
||||
qb.push_bind(&search_text);
|
||||
qb.push(") DESC, rank DESC, created_at DESC, id LIMIT ");
|
||||
} else {
|
||||
qb.push(" ORDER BY rank DESC, created_at DESC, id LIMIT ");
|
||||
qb.push(" ORDER BY ");
|
||||
if profile_query {
|
||||
qb.push("name_match DESC, ");
|
||||
}
|
||||
if prioritize_exact_profile_lexeme {
|
||||
qb.push("search_tsv @@ websearch_to_tsquery('simple', ");
|
||||
qb.push_bind(&search_text);
|
||||
qb.push(") DESC, ");
|
||||
}
|
||||
qb.push("rank DESC, created_at DESC, id LIMIT ");
|
||||
qb.push_bind(per_page_actual as i64);
|
||||
qb.push(" OFFSET ");
|
||||
qb.push_bind(offset);
|
||||
|
||||
@@ -16,7 +16,7 @@ use buzz_search::{ChannelScope, SearchQuery, SearchService};
|
||||
use sqlx::{postgres::PgPoolOptions, PgPool};
|
||||
use uuid::Uuid;
|
||||
|
||||
const TEST_DB_URL: &str = "postgres://buzz:buzz_dev@localhost:5432/buzz";
|
||||
const TEST_DB_URL: &str = "postgres://buzz:buzz_dev@localhost:5432/buzz"; // sadscan:disable np.postgres.1 -- local test-only credentials
|
||||
async fn setup() -> (PgPool, String) {
|
||||
let url = std::env::var("BUZZ_TEST_DATABASE_URL").unwrap_or_else(|_| TEST_DB_URL.to_string());
|
||||
// The PostgreSQL lane supplies an isolated desired-state database. Outside
|
||||
@@ -302,6 +302,76 @@ async fn short_kind0_prefix_prioritizes_exact_lexeme_on_a_noisy_page() {
|
||||
teardown(pool, &schema).await;
|
||||
}
|
||||
|
||||
/// `search_tsv` tokenizes the whole profile JSON, so a profile whose `about`
|
||||
/// text repeats a matching word outranks a one-word display name on
|
||||
/// `ts_rank_cd` alone (twelve weight-D covers score 1.2 against 0.1). Kind-0
|
||||
/// queries order rows whose name fields match ahead of body-only matches so
|
||||
/// the person the typeahead is looking for lands on page 1.
|
||||
///
|
||||
/// Mutate-bite: drop the `name_match DESC` ORDER BY term in `query.rs` and Wes
|
||||
/// falls behind the four newer, higher-ranked body matches onto page 2.
|
||||
#[tokio::test]
|
||||
#[ignore = "requires Postgres"]
|
||||
async fn kind0_prefix_orders_name_match_before_newer_body_match() {
|
||||
let (pool, schema) = setup().await;
|
||||
|
||||
let c = mk_community(&pool, "profile-name-first.example").await;
|
||||
let wes_id = rand_bytes32();
|
||||
insert_event(
|
||||
&pool,
|
||||
c,
|
||||
wes_id,
|
||||
rand_bytes32(),
|
||||
0,
|
||||
r#"{"display_name":"Wes"}"#,
|
||||
None,
|
||||
1_700_000_000,
|
||||
)
|
||||
.await;
|
||||
|
||||
// Newer profiles that match wes:* only through body text, each with a
|
||||
// higher cover-density rank than a single name lexeme.
|
||||
let about = ["west"; 12].join(" ");
|
||||
for i in 0..4 {
|
||||
insert_event(
|
||||
&pool,
|
||||
c,
|
||||
rand_bytes32(),
|
||||
rand_bytes32(),
|
||||
0,
|
||||
&format!(r#"{{"name":"Pollen {i}","about":"{about}"}}"#),
|
||||
None,
|
||||
1_700_000_100 + i,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
let svc = SearchService::new(pool.clone());
|
||||
let first_page = svc
|
||||
.search(&SearchQuery {
|
||||
community: c,
|
||||
q: "wes".into(),
|
||||
channel_scope: ChannelScope::Any,
|
||||
kinds: Some(vec![0]),
|
||||
authors: None,
|
||||
since: None,
|
||||
until: None,
|
||||
page: 1,
|
||||
per_page: 3,
|
||||
mode: buzz_search::SearchMode::Prefix,
|
||||
})
|
||||
.await
|
||||
.expect("profile prefix search ok");
|
||||
|
||||
assert_eq!(first_page.hits.len(), 3);
|
||||
assert_eq!(
|
||||
first_page.hits[0].event_id, wes_id,
|
||||
"name match must outrank newer body-only matches"
|
||||
);
|
||||
|
||||
teardown(pool, &schema).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires Postgres"]
|
||||
async fn prefix_mode_matches_final_token_prefix_without_changing_full_text() {
|
||||
|
||||
Reference in New Issue
Block a user