attribute_search_engine/
engine.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
use regex::Regex;
use std::collections::{HashMap, HashSet};
use std::hash::Hash;

use crate::error::*;
use crate::index::*;
use crate::query::*;

/// A SearchEngine is a wrapper around a collection of [search indices](SearchIndex)
/// that can process complex [queries](Query) involving multiple indices.
///
/// It can also create [queries](Query) from strings that are tailored to the
/// existing [indices](SearchIndex).
///
/// # Example
/// A complete example can be found on the [front page of this crate](crate).
pub struct SearchEngine<P> {
    indices: HashMap<String, Box<dyn SearchIndex<P>>>,
}

impl<P: Eq + Hash + Clone> Default for SearchEngine<P> {
    fn default() -> Self {
        Self::new()
    }
}

impl<P: Eq + Hash + Clone> SearchEngine<P> {
    /// Creates a new `SearchEngine`.
    ///
    /// # Example
    /// ```rust
    /// use attribute_search_engine::SearchEngine;
    ///
    /// let engine = SearchEngine::<usize>::new();
    /// ```
    pub fn new() -> Self {
        Self {
            indices: HashMap::new(),
        }
    }

    /// Add a new index to this search engine.
    ///
    /// # Example
    /// ```rust
    /// use attribute_search_engine::{SearchEngine, SearchIndexHashMap};
    ///
    /// let mut index = SearchIndexHashMap::<_, String>::new();
    ///
    /// // Fill index here...
    ///
    /// let mut engine = SearchEngine::<usize>::new();
    /// engine.add_index("attribute", index);
    /// ```
    pub fn add_index<T: SearchIndex<P> + 'static>(&mut self, name: &str, index: T) {
        self.indices.insert(name.into(), Box::new(index));
    }

    /// Run a query on the search engine.
    ///
    /// The result is a HashSet of all row ids / primary ids
    /// with rows that matched the query.
    pub fn search(&self, query: &Query) -> Result<HashSet<P>> {
        match query {
            Query::Exact(attr, _)
            | Query::Prefix(attr, _)
            | Query::InRange(attr, _, _)
            | Query::OutRange(attr, _, _)
            | Query::Minimum(attr, _)
            | Query::Maximum(attr, _) => {
                let index = self
                    .indices
                    .get(attr)
                    .ok_or(SearchEngineError::UnknownAttribute)?;
                index.search(query)
            }
            Query::Or(vec) => {
                let mut result_set = HashSet::<P>::new();
                for pred in vec.iter() {
                    let attribute_set = self.search(pred)?;
                    result_set = result_set.union(&attribute_set).cloned().collect();
                }
                Ok(result_set)
            }
            Query::And(vec) => {
                let mut result_set = HashSet::<P>::new();
                for (i, pred) in vec.iter().enumerate() {
                    let attribute_set = self.search(pred)?;
                    if i == 0 {
                        result_set = attribute_set;
                    } else {
                        result_set = result_set.intersection(&attribute_set).cloned().collect();
                    }
                    if result_set.is_empty() {
                        return Ok(result_set);
                    }
                }
                Ok(result_set)
            }
            Query::Exclude(base, exclude) => {
                let mut result_set = self.search(base)?;
                for pred in exclude.iter() {
                    let attribute_set = self.search(pred)?;
                    result_set = result_set.difference(&attribute_set).cloned().collect();
                    if result_set.is_empty() {
                        return Ok(result_set);
                    }
                }
                Ok(result_set)
            }
        }
    }

    pub fn query_from_str(&self, query_str: &str) -> Result<Query> {
        let attr_re = Regex::new(r"(\+|-)(\w+):(\S*)").expect("the regex to compile");

        let mut include = vec![];
        let mut exclude = vec![];
        for (_, [modifier, attribute, value]) in
            attr_re.captures_iter(query_str).map(|c| c.extract())
        {
            let new_predicate = Query::Exact(attribute.to_owned(), value.to_owned());
            if modifier == "+" {
                include.push(new_predicate);
            } else {
                exclude.push(new_predicate);
            }
        }

        let base_query = Query::And(include);
        if !exclude.is_empty() {
            Ok(Query::Exclude(base_query.into(), exclude))
        } else {
            Ok(base_query)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn query_parser() {
        let engine = SearchEngine::<usize>::new();

        let q = engine.query_from_str("").unwrap();
        assert_eq!(q, Query::And(vec![]));

        let q = engine
            .query_from_str("+zipcode:12345 +pet:Dog -name:Hans")
            .unwrap();
        assert_eq!(
            q,
            Query::Exclude(
                Box::new(Query::And(vec![
                    Query::Exact("zipcode".into(), "12345".into()),
                    Query::Exact("pet".into(), "Dog".into())
                ])),
                vec![Query::Exact("name".into(), "Hans".into())]
            )
        );
    }
}