Skip to main content

uqa_engine/search/
top_k.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! WAND/BMW planning, block-max lifecycle, and profiled text leaves.
8
9use super::{
10    storage_sql_error, Engine, OperatorTree, SQLError, ScoredEntry, ScoringMode, TextScoringMode,
11    TextSearchAlgorithm, TextSearchProfile, TextTopKPlan, TextTopKStrategy,
12};
13
14impl Engine {
15    pub(crate) fn plan_text_top_k_tree(
16        &self,
17        table: &str,
18        field: &str,
19        query: &str,
20        scoring: TextScoringMode,
21        top_k: usize,
22    ) -> Result<OperatorTree, SQLError> {
23        uqa_planner::retrieval_planning::plan_text_top_k_tree(
24            self, table, field, query, scoring, top_k,
25        )
26    }
27
28    /// Materialize scorer-versioned block bounds for one text field. `SQLite`
29    /// persists them across reopen; when a backend returns `false`, execution
30    /// falls back from the planned BMW strategy to exact WAND.
31    pub fn rebuild_text_block_max(
32        &self,
33        table: &str,
34        field: &str,
35        mode: &ScoringMode,
36    ) -> Result<bool, SQLError> {
37        self.validate_text_search_field(table, field)?;
38        self.with_implicit_transaction(|engine| {
39            let Some(table_state) = engine
40                .try_table(table)
41                .map_err(|error| storage_sql_error("resolve text-search table", error))?
42            else {
43                return Err(SQLError::UnknownTable(table.to_string()));
44            };
45            let mut index = table_state.inverted_index.write();
46            uqa_scoring::rebuild_text_block_max(index.as_mut(), field, mode)
47                .map_err(super::helpers::scoring_sql_error)
48        })
49    }
50
51    pub(super) fn search_leaf_profiled(
52        &self,
53        table: &str,
54        field: &str,
55        query: &str,
56        mode: &ScoringMode,
57        top_k: usize,
58        physical_top_k: Option<TextTopKPlan>,
59    ) -> Result<TextSearchProfile, SQLError> {
60        let table_state = self
61            .try_query_table(table)
62            .map_err(|error| storage_sql_error("resolve text-search table", error))?
63            .ok_or_else(|| SQLError::UnknownTable(table.to_string()))?;
64        let index = table_state.inverted_index.read();
65        let index = uqa_execution::serializable::text::ObservedTextIndex::new(
66            index.as_ref(),
67            self.serializable_table_read(table)?,
68            table_state.columns.snapshot(),
69        );
70        let (limit, strategy) = match physical_top_k {
71            Some(plan) => (
72                plan.k,
73                match plan.strategy {
74                    TextTopKStrategy::Wand => TextSearchAlgorithm::Wand,
75                    TextTopKStrategy::BlockMaxWand => TextSearchAlgorithm::BlockMaxWand,
76                },
77            ),
78            None => (top_k, TextSearchAlgorithm::Exhaustive),
79        };
80        uqa_scoring::score_text_query(&index, table, field, query, mode, limit, strategy)
81            .map_err(super::helpers::scoring_sql_error)
82    }
83
84    /// Physical text-search leaf. Only [`crate::operator_tree_bridge::EngineDriver`]
85    /// calls this; public callers enter through [`Self::search`] below.
86    pub(crate) fn search_leaf(
87        &self,
88        table: &str,
89        field: &str,
90        query: &str,
91        mode: &ScoringMode,
92        top_k: usize,
93        physical_top_k: Option<TextTopKPlan>,
94    ) -> Result<Vec<ScoredEntry>, SQLError> {
95        Ok(self
96            .search_leaf_profiled(table, field, query, mode, top_k, physical_top_k)?
97            .entries)
98    }
99}