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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
//! JSON-Surf
//! ## Features
//! * Full text search
//! * Serialize __**flat**__ JSON/Struct
//! * Easy write and read API
//! * Write multiple documents together
//! * Requires no runtime
//! * No unsafe block
//! * Run on rust stable (Please check the Rust version, 1.39 does not work)
//! * Coming Soon: Bigram suggestion & TF-IDF support
//!
//! ## Motivation
//! * Allow your existing simples flat rust structs to be searched
//! * Encoded/Decoded byte streams can be stored along side too as base64 encoded string
//! * The crate will support arbitary byte stream once it is supported by tantivy (see [here](https://github.com/tantivy-search/tantivy/issues/832))
//! * This can just act as a container to actual data in databases, keeping indexes light
//! * Create time-aware containers which could possibly updated/deleted
//! * Create ephemeral storage for request/response
//! * This can integrate with any web-server to index and search near real-time
//! * This crate is just a convenience crate over [tantivy](https://github.com/tantivy-search/tantivy).
//! * This crate will focus mostly on user-workflow(s) related problem(s)
//!
//! ## Quickstart
//!
//! ### Prerequisite:
//!
//!  ```toml
//!   [dependencies]
//!   json-surf = "*"
//! ```
//!
//! ### Example
//! ```rust
//! use std::convert::TryFrom;
//! use std::fs::remove_dir_all;
//! use std::cmp::{Ord, Ordering, Eq};
//!
//! use serde::{Serialize, Deserialize};
//!
//! use json_surf::prelude::*;
//!
//! /// Main struct
//! #[derive(Serialize, Debug, Deserialize, PartialEq, PartialOrd, Clone)]
//! struct UserInfo {
//!     first: String,
//!     last: String,
//!     age: u8,
//! }
//!
//! impl UserInfo {
//!     pub fn new(first: String, last: String, age: u8) -> Self {
//!         Self {
//!             first,
//!             last,
//!             age,
//!         }
//!     }
//! }
//!
//! impl Default for UserInfo {
//!     fn default() -> Self {
//!         let first = "".to_string();
//!         let last = "".to_string();
//!         let age = 0u8;
//!         UserInfo::new(first, last, age)
//!     }
//! }
//!
//!
//! fn main() {
//!     // Specify home location of indexes
//!     let home = ".store".to_string();
//!     let name = "users".to_string();
//!
//!     // Prepare builder
//!     let mut builder = SurferBuilder::default();
//!     builder.set_home(&home);
//!
//!     let data = UserInfo::default();
//!     builder.add_struct(name.clone(), &data);
//!
//!     // Prepare Surfer
//!     let mut surfer = Surfer::try_from(builder).unwrap();
//!
//!     // Prepare data to insert & search
//!
//!     // User 1: John Doe
//!     let first = "John".to_string();
//!     let last = "Doe".to_string();
//!     let age = 20u8;
//!     let john_doe = UserInfo::new(first, last, age);
//!
//!     // User 2: Jane Doe
//!     let first = "Jane".to_string();
//!     let last = "Doe".to_string();
//!     let age = 18u8;
//!     let jane_doe = UserInfo::new(first, last, age);
//!
//!     // User 3: Jonny Doe
//!     let first = "Jonny".to_string();
//!     let last = "Doe".to_string();
//!     let age = 10u8;
//!     let jonny_doe = UserInfo::new(first, last, age);
//!
//!     // User 4: Jinny Doe
//!     let first = "Jinny".to_string();
//!     let last = "Doe".to_string();
//!     let age = 10u8;
//!     let jinny_doe = UserInfo::new(first, last, age);
//!
//!     // Writing structs
//!
//!     // Option 1: One struct at a time
//!     let _ = surfer.insert_struct(&name, &john_doe).unwrap();
//!     let _ = surfer.insert_struct(&name, &jane_doe).unwrap();
//!
//!     // Option 2: Write all structs together
//!     let users = vec![jonny_doe.clone(), jinny_doe.clone()];
//!     let _ = surfer.insert_structs(&name, &users).unwrap();
//!
//!     // Reading structs
//!
//!     // Option 1: Full text search
//!     let expected = vec![john_doe.clone()];
//!     let computed = surfer.read_structs::<UserInfo>(&name, "John", None, None).unwrap().unwrap();
//!     assert_eq!(expected, computed);
//!
//!     let mut expected = vec![john_doe.clone(), jane_doe.clone(), jonny_doe.clone(), jinny_doe.clone()];
//!     expected.sort();
//!     let mut computed = surfer.read_structs::<UserInfo>(&name, "doe", None, None).unwrap().unwrap();
//!     computed.sort();
//!     assert_eq!(expected, computed);
//!
//!     // Option 2: Term search
//!     let mut expected = vec![jonny_doe.clone(), jinny_doe.clone()];
//!     expected.sort();
//!     let mut computed = surfer.read_stucts_by_field::<UserInfo>(&name, "age", "10", None, None).unwrap().unwrap();
//!     computed.sort();
//!     assert_eq!(expected, computed);
//!
//!     // Clean-up
//!     let path = surfer.which_index(&name).unwrap();
//!     let _ = remove_dir_all(&path);
//!     let _ = remove_dir_all(&home);
//! }
//!
//! /// Convenience method for sorting & likely not required in user code
//! impl Ord for UserInfo {
//!     fn cmp(&self, other: &Self) -> Ordering {
//!         if self.first == other.first && self.last == other.last {
//!             return Ordering::Equal;
//!         };
//!         if self.first == other.first {
//!             if self.last > self.last {
//!                 Ordering::Greater
//!             } else {
//!                 Ordering::Less
//!             }
//!         } else {
//!             if self.first > self.first {
//!                 Ordering::Greater
//!             } else {
//!                 Ordering::Less
//!             }
//!         }
//!     }
//! }
//!
//! /// Convenience method for sorting & likely not required in user code
//! impl Eq for UserInfo {}
//! ```

pub mod prelude;
pub mod seed;
pub mod errors;
pub mod utils;
pub mod registry;
pub mod fuzzy;

#[cfg(test)]
mod tests {
    use super::*;
    use serde::{Serialize};
    use serde_value;
    use std::collections::BTreeMap;
    use std::fmt;
    use tantivy::schema::{Schema, IntOptions, TEXT, STORED};
    use std::ops::{Deref, DerefMut};
    use std::fmt::Debug;

    #[derive(Serialize, Clone, PartialEq)]
    struct SchemaTest(Schema);

    impl Deref for SchemaTest {
        type Target = Schema;
        fn deref(&self) -> &Self::Target {
            &self.0
        }
    }

    impl DerefMut for SchemaTest {
        fn deref_mut(&mut self) -> &mut Self::Target {
            &mut self.0
        }
    }

    impl Debug for SchemaTest {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            let schema = &self.0;
            let x = schema.fields();
            let mut fields = Vec::new();
            for (field,_) in x {
                fields.push(field);
            }
            f.write_str(format!("{:?}", fields).as_str())
        }
    }

    impl SchemaTest {
        fn new(schema: Schema) -> Self {
            Self(schema)
        }
    }

    #[derive(Serialize)]
    struct Dummy {
        x: String,
        y: String,
        z: u64,
    }

    #[derive(Serialize)]
    struct Giant {
        a: String,
        b: bool,
        c: u64,
        d: u32,
        e: u16,
        f: u8,
        g: i64,
        h: i32,
        i: i16,
        j: i8,
        k: f64,
        l: f32,
        m: Vec<u8>,
    }


    #[test]
    fn validate_field_names() {
        let data = Dummy {
            x: "A".to_owned(),
            y: "B".to_owned(),
            z: 100,
        };

        let value = utils::as_value(&data).unwrap();
        let computed = utils::field_names(&value).unwrap();
        let expected = vec!["x", "y", "z"];
        assert_eq!(expected, computed);
    }

    #[test]
    fn validate_as_value() {
        let data = Dummy {
            x: "X".to_owned(),
            y: "Y".to_owned(),
            z: 100,
        };

        let mut bmap = BTreeMap::new();
        bmap.insert(serde_value::Value::String("x".to_owned()), serde_value::Value::String("X".to_owned()));
        bmap.insert(serde_value::Value::String("y".to_owned()), serde_value::Value::String("Y".to_owned()));
        bmap.insert(serde_value::Value::String("z".to_owned()), serde_value::Value::U64(100));

        let expected = serde_value::Value::Map(bmap);
        let computed = utils::as_value(&data).unwrap();

        assert_eq!(expected, computed);
    }

    #[test]
    fn validate_basic_schema() {
        let data = Dummy {
            x: "X".to_owned(),
            y: "Y".to_owned(),
            z: 100u64,
        };

        let data = utils::as_value(&data).unwrap();

        let (computed, _) = utils::to_schema(&data, None).unwrap();
        let computed = SchemaTest::new(computed);

        let mut expected = Schema::builder();
        expected.add_text_field("x", TEXT | STORED);
        expected.add_text_field("y", TEXT | STORED);

        let options = IntOptions::default();
        let options = options.set_stored();
        let options = options.set_indexed();
        expected.add_u64_field("z", options);

        let expected = expected.build();
        let expected = SchemaTest::new(expected);

        assert_eq!(expected, computed);
    }

    #[test]
    fn validate_full_schema() {
        let a: String = "Empire Of The Clouds".to_string();
        let b: bool = true;
        let c: u64 = 1;
        let d: u32 = 1;
        let e: u16 = 1;
        let f: u8 = 1;
        let g: i64 = 1;
        let h: i32 = 1;
        let i: i16 = 1;
        let j: i8 = 1;
        let k: f64 = 1.0;
        let l: f32 = 1.0;
        let m: Vec<u8> = "The book of souls".as_bytes().to_vec();
        let data = Giant {
            a,
            b,
            c,
            d,
            e,
            f,
            g,
            h,
            i,
            j,
            k,
            l,
            m,
        };
        let data = utils::as_value(&data).unwrap();
        let (computed, _) = utils::to_schema(&data, None).unwrap();
        let computed = SchemaTest::new(computed);

        let mut expected = Schema::builder();
        expected.add_text_field("a", TEXT | STORED);
        expected.add_text_field("b", TEXT | STORED);

        let options = IntOptions::default();
        let options = options.set_stored();
        let options = options.set_indexed();
        expected.add_u64_field("c", options.clone());
        expected.add_u64_field("d", options.clone());
        expected.add_u64_field("e", options.clone());
        expected.add_u64_field("f", options.clone());

        expected.add_i64_field("g", options.clone());
        expected.add_i64_field("h", options.clone());
        expected.add_i64_field("i", options.clone());
        expected.add_i64_field("j", options.clone());
        expected.add_f64_field("k", options.clone());
        expected.add_f64_field("l", options.clone());
        expected.add_bytes_field("m");
        let expected = expected.build();
        let expected = SchemaTest::new(expected);
        assert_eq!(format!("{:?}", expected), format!("{:?}", computed));
        assert_eq!(expected, computed);
    }
}