attribute_search_engine/index/
mod.rs

1use crate::{Query, Result, SearchEngineError, SupportedQueries};
2use std::{collections::HashSet, str::FromStr};
3
4mod btree_range;
5mod hashmap;
6mod prefix;
7
8pub use btree_range::*;
9pub use hashmap::*;
10pub use prefix::*;
11
12/// This trait describes the minimum features an Index must support to be
13/// usable as a SearchIndex, for example in a [SearchEngine](crate::engine::SearchEngine).
14pub trait SearchIndex<P> {
15    /// Perform a search on an index.
16    ///
17    /// This function returns an HashSet of all matching results.
18    /// It may not accept all enum values of [Query] but only
19    /// a small subset. If a [Query] is not supported,
20    /// this function returns [UnsupportedQuery](crate::error::SearchEngineError::UnsupportedQuery).
21    ///
22    /// If the strings in the [Query] cannot be parsed to
23    /// the expected payload type, this function returns
24    /// [MismatchedQueryType](crate::error::SearchEngineError::MismatchedQueryType).
25    fn search(&self, query: &Query) -> Result<HashSet<P>>;
26
27    /// Returns which queries are directly supported by an index.
28    ///
29    /// This function may be used for some features and optimizations by
30    /// a [SearchEngine](crate::engine::SearchEngine). For example, it
31    /// signals which operators (=,>,<,-) in the query parser are supported
32    /// by an index.
33    fn supported_queries(&self) -> SupportedQueries;
34}
35
36/// Tries to parse a string into a payload value.
37///
38/// This is an internal function. If it fails it returns
39/// [MismatchedQueryType](crate::error::SearchEngineError::MismatchedQueryType)
40/// to signal failure.
41fn string_to_payload_type<T: FromStr>(value: &str) -> Result<T> {
42    value
43        .parse()
44        .map_err(|_| SearchEngineError::MismatchedQueryType)
45}
46
47#[cfg(test)]
48mod tests {
49    use super::*;
50
51    #[test]
52    fn test_string_to_payload_type() {
53        assert_eq!(string_to_payload_type("1234"), Ok(1234i32));
54        assert_eq!(string_to_payload_type("123456"), Ok(123456usize));
55        assert_eq!(string_to_payload_type("true"), Ok(true));
56        assert_eq!(
57            string_to_payload_type::<usize>("Hello"),
58            Err(SearchEngineError::MismatchedQueryType)
59        );
60    }
61}