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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
extern crate mycelium_command;
extern crate mycelium_core;
extern crate mycelium_experimental;
extern crate rayon;
#[macro_use]
extern crate serde;

use mycelium_core::prelude::*;
use rayon::prelude::*;

use crate::index::SkipIndex;
use mycelium_command::prelude::*;
use mycelium_experimental::crossbeam_skiplist::map::SkipMap;

mod index;
pub mod prelude;

///
/// # Index
/// Will hold multiple types of indexes back into Db
///
pub struct Index {
    pub db: Db,
    // tag, index for tag
    idx_map: SkipMap<String, SkipIndex>,
}

impl Index {
    ///
    /// # Init
    /// Initialize containers. If first run a system folder will be
    /// created otherwise nothing else is done.
    ///
    /// * Parameters
    ///     - config: Config for Db defaults to Config::default()
    ///
    /// * Return
    ///     - Result: Index
    ///
    /// ```
    /// use crate::mycelium_index::prelude::*;
    ///
    /// match Index::init(None) {
    ///     Ok(_) => assert!(true),
    ///     Err(_) => assert!(false, "Error creating db")
    /// }
    /// ```
    ///
    pub fn init(config: Option<Config>) -> std::io::Result<Index> {
        let db = match mycelium_core::Db::init(config) {
            Ok(s) => s,
            Err(e) => panic!("Failed to initialize stew: {:?}", e),
        };
        let db_dir = db.get_working_dir();
        let tags = db.list_tags();

        let map: SkipMap<String, SkipIndex> = SkipMap::new();
        // Init empty index containers for all tags
        for cont in tags {
            map.insert(cont.to_string(), SkipIndex::new(cont.as_str(), &db_dir));
        }

        Ok(Index { db, idx_map: map })
    }

    ///
    /// # Add
    /// Add item to database
    ///
    /// * Parameters
    ///     - tag: container id to add item to
    ///     - item: byte array of item
    ///     - type_name: optional type id
    ///
    /// * Return
    ///     - Result: [u8;16] id of item added to db/index
    ///
    /// ```
    /// use crate::mycelium_index::prelude::*;
    ///
    /// // new db
    /// let idb = Index::init(None).expect("Failed to create idb");
    /// // add item
    /// let id = idb.add("dog", b"shepard").expect("Failed to add item");
    ///
    /// assert!(id != [0;16])
    ///
    /// ```
    ///
    pub fn add(&self, tag: &str, item: &[u8]) -> std::io::Result<DbId> {
        let id: DbId = self.db.add(item, tag).expect("Failed to soup.");
        Ok(id)
    }

    ///
    /// # Add Indexed
    /// Add an item to the database and any implemented indexes with given
    /// association.
    ///
    /// * Parameters
    ///     - tag: container id to put item in
    ///     - item: byte array of item
    ///     - hit_box: index terms this item should be associated
    ///         with ["fish", "dog"]
    ///
    /// * Return
    ///     - Result: [u8; 16] unique db id of item added
    ///
    /// ```
    /// use crate::mycelium_index::prelude::*;
    ///
    /// // new db
    /// let idb = Index::init(None).expect("Failed to create idb");
    /// // add item with index associates
    /// let id = idb.add_indexed("dog",
    ///         b"good boy",
    ///         &["shepherd", "working dog", "pet"])
    ///     .expect("Failed to add item");
    ///
    /// assert!(id != [0 as u8;16])
    /// ```
    ///
    pub fn add_indexed(&self, tag: &str, item: &[u8], hit_box: &[&str]) -> std::io::Result<DbId> {
        let id: DbId = self.db.add(item, tag).expect("Failed to soup.");
        if !self.idx_map.contains_key(tag) {
            let path = self.db.get_working_dir();
            self.idx_map
                .insert(tag.to_string(), SkipIndex::new(tag, &path));
        }
        let map = self.idx_map.get(tag);
        if map.is_some() {
            let map = map.unwrap();
            for hit in hit_box {
                map.value().upsert((hit, id))?;
            }
        }

        Ok(id)
    }

    ///
    /// # Get
    /// Get an item/items from container
    ///
    /// * Parameters
    ///     - tag: container id
    ///     - ids: array of ids to retrieve [[u8;16],[u8;16]
    ///
    /// * Return
    ///     - Option: Vector of matches
    ///
    /// ```
    /// use crate::mycelium_index::prelude::*;
    ///
    /// // new db
    /// let idb = Index::init(None).expect("Failed to create idb");
    /// // add item
    /// let id = idb.add("tag", b"some stuff").expect("Failed to add to idb");
    /// let id2 = idb.add("tag", b"some stuff 2").expect("Failed to add to idb");
    /// let id3 = idb.add("tag", b"some stuff 3").expect("Failed to add to idb");
    /// // get item
    /// let f_item = idb.get("tag", &[id, id3]).expect("Failed to get item from idb");
    ///
    /// assert!(f_item.len() == 2);
    /// let ids: Vec<[u8;16]> = f_item.iter().map(|node| node.get_id()).collect();
    /// assert!(ids.contains(&id) && ids.contains(&id3) && !ids.contains(&id2));
    ///
    /// ```
    ///
    pub fn get(&self, tag: &str, ids: &[DbId]) -> Option<Vec<Node>> {
        let mut result = vec![];
        for id in ids {
            let q = self.db.get(tag, *id);
            if q.is_some() {
                result.push(q.unwrap());
            }
        }

        if result.is_empty() {
            None
        } else {
            Some(result)
        }
    }

    pub fn get_system_id(&self) -> DbId {
        self.db.get_system_id()
    }

    pub fn list_tags(&self) -> Vec<String> {
        self.db.list_tags()
    }

    ///
    /// # Load Tag
    /// Load a tag before performing operations over it.
    /// Destructive if called over loaded tag drop current and load from disk.
    ///
    pub fn load_tag(&mut self, tag: &str) -> std::io::Result<()> {
        let map = self.idx_map.get(tag);
        if map.is_some() {
            let map = map.unwrap();
            if map.value().not_ready() {
                let update = map.value().fetch_self();
                self.idx_map.insert(tag.to_string(), update);
            }
        }
        self.db.load_tag(tag)
    }

    ///
    /// # Search
    /// Search for items in container
    ///
    /// * Parameters:
    ///     - tag: container id
    ///     - hit_list: search items
    ///
    /// * Result:
    ///     - Option: List of nodes that are associated with hit_list items.
    ///         TODO: Order by match count
    ///
    /// ```
    /// use crate::mycelium_index::prelude::*;
    ///
    /// // new db
    /// let idb = Index::init(None).expect("Failed to create db");
    /// // add some nodes
    /// let id_mut = idb.add_indexed("tag", b"Zippy", &["Shepherd", "Husky", "Akita", "Lab"])
    ///     .expect("Failed to add item to idb");
    /// let id_boxer = idb.add_indexed("tag", b"Trip", &["Boxer"])
    ///     .expect("Failed to add item to idb");
    /// let id_mut2 = idb.add_indexed("tag", b"Buddy", &["Boxer", "Lab"])
    ///     .expect("Failed to add item to idb");
    /// let id_pointer = idb.add_indexed("tag", b"Sam", &["Pointer"])
    ///     .expect("Failed to add item to idb");
    ///
    /// let dogs = idb.search("tag", &["Boxer", "Lab"]).unwrap();
    /// assert!(dogs.len() == 3);
    /// // not case sensitive
    /// let dog = idb.search("tag", &["pointer"]).unwrap();
    /// assert!(dog.len() == 1);
    ///
    /// ```
    ///
    pub fn search(&self, tag: &str, hit_list: &[&str]) -> Option<Vec<Node>> {
        let items = self.search_indexed(tag, hit_list);

        // If no results shortcut method
        if items.is_none() {
            return None;
        }
        let items = items.unwrap();

        let mut result: Vec<Node> = items
            .par_iter()
            .map(|id| self.db.get(tag, *id).expect("Id in index not found."))
            .collect();

        if result.is_empty() {
            None
        } else {
            result.sort();
            result.dedup();
            Some(result)
        }
    }

    fn search_indexed(&self, tag: &str, hit_list: &[&str]) -> Option<Vec<DbId>> {
        let cont = self.idx_map.get(tag);
        if cont.is_some() {
            let cont = cont.unwrap();
            let result = hit_list
                .par_iter()
                .flat_map(|hit| cont.value().get(hit))
                .collect();

            return Some(result);
        }

        None
    }

    pub fn save_all(&self) -> std::io::Result<()> {
        self.db.save_all()?;
        self.idx_map.iter().for_each(|x| match x.value().save() {
            Ok(_) => (),
            Err(e) => eprintln!("Error: {:?}", e),
        });
        Ok(())
    }
}

///
/// # Indexing
///
pub trait Indexed {
    /// Add a relationship between this item_id and this term for search and relations.
    fn add(&mut self, idx: &str, item_id: [u8; 16]) -> std::io::Result<()>;

    /// Check that container has index
    fn contains(&self, idx: &str) -> bool;

    /// Remove indexing for this term from container
    fn remove(&mut self, idx: &str) -> std::io::Result<()>;

    /// Remove item from indexed term.
    fn remove_for(&mut self, idx: &str, item_id: [u8; 16]) -> std::io::Result<()>;
}