├── .gitignore ├── scripts └── get_wiki_dump.sh ├── .cargo └── config.toml ├── .github └── workflows │ ├── release.yml │ └── rust.yml ├── Cargo.toml ├── README.md ├── examples └── index_wiki_local.rs ├── LICENSE └── src └── lib.rs /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /Cargo.lock 3 | -------------------------------------------------------------------------------- /scripts/get_wiki_dump.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | wget https://dumps.wikimedia.org/simplewiki/20230720/simplewiki-20230720-pages-articles-multistream.xml.bz2 4 | bzip2 -d simplewiki-20230720-pages-articles-multistream.xml.bz2 5 | 6 | wget https://raw.githubusercontent.com/powerlanguage/word-lists/master/1000-most-common-words.txt -------------------------------------------------------------------------------- /.cargo/config.toml: -------------------------------------------------------------------------------- 1 | [target.'cfg(all())'] 2 | rustflags = [ 3 | "-Wclippy::all", 4 | # "-Wclippy::style", 5 | "-Wclippy::fallible_impl_from", 6 | "-Wclippy::manual_let_else", 7 | "-Wclippy::redundant_pub_crate", 8 | "-Wclippy::string_add_assign", 9 | "-Wclippy::string_add", 10 | "-Wclippy::string_lit_as_bytes", 11 | "-Wclippy::string_to_string", 12 | "-Wclippy::use_self", 13 | ] 14 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Publish Rust crate 2 | 3 | on: 4 | release: 5 | types: [published] 6 | 7 | env: 8 | # This env var is used by Swatinem/rust-cache@v2 for the cache 9 | # key, so we set it to make sure it is always consistent. 10 | CARGO_TERM_COLOR: always 11 | 12 | jobs: 13 | build: 14 | runs-on: ubuntu-22.04 15 | timeout-minutes: 30 16 | defaults: 17 | run: 18 | working-directory: . 19 | steps: 20 | - uses: actions/checkout@v3 21 | - uses: Swatinem/rust-cache@v2 22 | with: 23 | workspaces: . 24 | - uses: katyo/publish-crates@v2 25 | with: 26 | registry-token: ${{ secrets.TANTIVY_OBJECT_STORE_RELEASE_TOKEN }} 27 | args: '--all-features' 28 | path: . 29 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "tantivy-object-store" 3 | version = "0.1.0" 4 | edition = "2021" 5 | authors = ["Lance Devs "] 6 | description = "A tantivy Directory implementation against object stores (S3, GCS, etc.)" 7 | license = "Apache-2.0" 8 | repository = "https://github.com/lancedb/tantivy-object-store" 9 | readme = "README.md" 10 | rust-version = "1.65" 11 | keywords = [ 12 | "full-text-search", 13 | "search", 14 | "search-engine", 15 | ] 16 | categories = [ 17 | "data-structures", 18 | "text-processing", 19 | "filesystem", 20 | ] 21 | 22 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 23 | 24 | [dependencies] 25 | # 0.20 is when file handle started to return Arc instead of Box + when the method is ungated from feature flag 26 | # https://github.com/quickwit-oss/tantivy/commit/775e936f7d8e461b7267bb13763db37c1c45afb8 27 | tantivy = "0.20" 28 | object_store = "0.9.0" 29 | async-trait = "0" 30 | tokio = { version = "1", features = ["full"] } 31 | uuid = "1" 32 | bytes = "1" 33 | log = "0" 34 | tempfile = "3" 35 | 36 | [dev-dependencies] 37 | env_logger = "0" 38 | wikidump = "0.2.2" 39 | stop-words = "0" 40 | 41 | [[example]] 42 | name = "index_wiki_local" 43 | -------------------------------------------------------------------------------- /.github/workflows/rust.yml: -------------------------------------------------------------------------------- 1 | name: Build and run Rust tests 2 | on: 3 | push: 4 | branches: 5 | - main 6 | pull_request: 7 | paths: 8 | - "**/*" 9 | 10 | env: 11 | # This env var is used by Swatinem/rust-cache@v2 for the cache 12 | # key, so we set it to make sure it is always consistent. 13 | CARGO_TERM_COLOR: always 14 | # Disable full debug symbol generation to speed up CI build and keep memory down 15 | # "1" means line tables only, which is useful for panic tracebacks. 16 | RUSTFLAGS: "-C debuginfo=1" 17 | RUST_BACKTRACE: "1" 18 | # according to: https://matklad.github.io/2021/09/04/fast-rust-builds.html 19 | # CI builds are faster with incremental disabled. 20 | CARGO_INCREMENTAL: "0" 21 | CARGO_BUILD_JOBS: "1" 22 | 23 | jobs: 24 | linux-build: 25 | runs-on: ubuntu-22.04 26 | timeout-minutes: 30 27 | defaults: 28 | run: 29 | working-directory: . 30 | steps: 31 | - uses: actions/checkout@v3 32 | - uses: Swatinem/rust-cache@v2 33 | with: 34 | workspaces: rust 35 | - name: Install dependencies 36 | run: | 37 | sudo apt update 38 | sudo apt install -y libssl-dev 39 | - name: Run cargo fmt 40 | run: cargo fmt --check 41 | - name: Clippy 42 | run: | 43 | cargo clippy --all-features --tests -- -D warnings 44 | - name: Build 45 | run: | 46 | cargo build --all-features 47 | - name: Build test 48 | run: | 49 | cargo test --all-features --no-run 50 | - name: Run tests 51 | run: | 52 | cargo test --all-features 53 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Tantivy Object Store 2 | This repo contains an implementation of a `tantivy::directory::Directory` using an `object_store::ObjectStore`. 3 | 4 | This implementation supports both read and write, but does not support locking or file watch. The index building process is responsible for making sure that there are no concurrent index writers. 5 | 6 | A few notable behavior differences from tantivy's directory implementations: 7 | 8 | ## Versioning 9 | Tantivy uses a file called `meta.json` which is a list of all the files that make up the index, effectively keeping track of a snapshot of the index. However, vanilla tantivy doesn't support versioning, meaning every time we update the index, meta.json is overwritten. This PR allows the caller to set a read_version and write_version. These version numbers are appended to the end of the file name when caller attempts to atomic_read or atomic_write. 10 | 11 | ### Copy on Write (CoW) 12 | When creating a `ObjectStoreDirectory`, user may set `read_version` and `write_version`. `read_version` is used when user calls `atomic_read`. Instead of reading `meta.json`, we will try to read `meta.json.{read_version}`. Same when user calls `atomic_write`, we will try to write `meta.json.{write_version}` 13 | 14 | NOTE: The `write_version` take precedence over `read_version`. This means, after first write, `atomic_read` will read from `meta.json.{write_version}` NOT `meta.json.{read_version}`. This is needed because tantivy modifies `meta.json` file quite a few times during indexing, the CoW impl here needs have read-after-write consistency. 15 | 16 | ## Index Reloading 17 | This implementation does not support reloading. If a `watch` callback is registered, the callback will never be called. User needs to handle reloading via other mechanisms for now. 18 | 19 | It maybe possible to use something like object store's native change notification to trigger reload, but that's for future work. 20 | 21 | ## Deletion 22 | Since tantivy attempts to garbage collect and merge index files during indexing, we had to change `delete` operation to noop. This is because we don't want tantivy to garbage collect files from past versions, as those files maybe in use by other readers. We will implement a garbage collection processes separately. 23 | 24 | ## Threading 25 | This implementation contains a `tokio::Runtime` for running the IO jobs. This means, when calling functions from this implementation from inside another tokio runtime the caller should always use `tokio::task::spawn_blocking` so the task can be scheduled on a thread without tokio runtime. (This is needed because nesting tokio runtimes causes panic) 26 | 27 | ## Concurrency Safety 28 | This implementation is concurrency safe within a single instance, as the `atomic_read|write` mechanism is a lock object in the returned trait object. 29 | 30 | ## Performance 31 | TBD 32 | -------------------------------------------------------------------------------- /examples/index_wiki_local.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2023 Lance Developers. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | use std::{collections::HashSet, sync::Arc, time::Instant}; 16 | 17 | use log::info; 18 | use object_store::local::LocalFileSystem; 19 | use tantivy::{ 20 | doc, 21 | schema::{STORED, TEXT}, 22 | IndexSettings, 23 | }; 24 | use tantivy_object_store::new_object_store_directory; 25 | use wikidump::{config, Parser}; 26 | 27 | fn main() { 28 | env_logger::init(); 29 | info!("Straring indexing Wikipedia dump"); 30 | let parser = Parser::new().use_config(config::wikipedia::english()); 31 | let site = parser 32 | .parse_file("./simplewiki-20230720-pages-articles-multistream.xml") 33 | .expect("Could not parse wikipedia dump file."); 34 | 35 | // use linux words file for query 36 | let words = std::fs::read_to_string("./1000-most-common-words.txt").unwrap(); 37 | let mut stop_words = stop_words::get(stop_words::LANGUAGE::English) 38 | .into_iter() 39 | .map(|s| s.replace("\"", "")) 40 | .collect::>(); 41 | 42 | for w in vec!["I", "you", "me", "it", "he", "she", "her", "his", "its"] { 43 | stop_words.insert(w.to_string()); 44 | } 45 | let words = words.split("\n").collect::>(); 46 | let words = words 47 | .into_iter() 48 | .filter(|w| !stop_words.contains(&w.to_string()) && w.len() >= 5) 49 | .collect::>(); 50 | 51 | let dir = tempfile::tempdir().unwrap(); 52 | let mut schema_builder = tantivy::schema::Schema::builder(); 53 | let id_field = schema_builder.add_u64_field("id", STORED); 54 | let title_field = schema_builder.add_text_field("title", TEXT | STORED); 55 | let text_field = schema_builder.add_text_field("text", TEXT | STORED); 56 | let schema = schema_builder.build(); 57 | 58 | let index = tantivy::Index::create_in_dir(dir.path(), schema.clone()).unwrap(); 59 | 60 | // 1 GB 61 | let mut writer = index.writer(1024 * 1024 * 1024).unwrap(); 62 | 63 | let start = Instant::now(); 64 | info!("starting indexing using native tantivy diretory"); 65 | for (idx, page) in site.pages.iter().enumerate() { 66 | let doc = doc! { 67 | id_field => idx as u64, 68 | title_field => page.title.clone(), 69 | text_field => page.revisions[page.revisions.len() - 1].text.to_string(), 70 | }; 71 | 72 | writer.add_document(doc).unwrap(); 73 | } 74 | 75 | info!("waiting for index to fully commit"); 76 | writer.commit().unwrap(); 77 | writer.wait_merging_threads().unwrap(); 78 | info!("indexing took {:?}", start.elapsed()); 79 | 80 | let searcher = index.reader().unwrap().searcher(); 81 | let query_parser = tantivy::query::QueryParser::for_index(&index, vec![title_field]); 82 | 83 | info!("starting search using native tantivy diretory"); 84 | let start = Instant::now(); 85 | for (idx, word) in words.iter().enumerate() { 86 | if idx % 1000 == 0 { 87 | info!("searched {} words in {:?}", idx, start.elapsed()); 88 | } 89 | searcher 90 | .search( 91 | &query_parser.parse_query(word).unwrap(), 92 | &tantivy::collector::TopDocs::with_limit(10), 93 | ) 94 | .unwrap(); 95 | } 96 | info!("search took {:?}", start.elapsed()); 97 | 98 | let dir = tempfile::tempdir().unwrap(); 99 | 100 | let dir = new_object_store_directory( 101 | Arc::new(LocalFileSystem::new()), 102 | dir.path().to_str().unwrap(), 103 | None, 104 | 0, 105 | None, 106 | None, 107 | ) 108 | .unwrap(); 109 | 110 | let index_using_object_store = 111 | tantivy::Index::create(dir, schema.clone(), IndexSettings::default()).unwrap(); 112 | 113 | let mut writer = index_using_object_store.writer(1024 * 1024 * 1024).unwrap(); 114 | 115 | let start = Instant::now(); 116 | info!("starting indexing using object store tantivy diretory"); 117 | for (idx, page) in site.pages.iter().enumerate() { 118 | let doc = doc! { 119 | id_field => idx as u64, 120 | title_field => page.title.clone(), 121 | text_field => page.revisions[page.revisions.len() - 1].text.to_string(), 122 | }; 123 | 124 | writer.add_document(doc).unwrap(); 125 | } 126 | 127 | info!("waiting for index to fully commit"); 128 | writer.commit().unwrap(); 129 | writer.wait_merging_threads().unwrap(); 130 | info!("indexing took {:?}", start.elapsed()); 131 | 132 | let searcherusing_object_store = index_using_object_store.reader().unwrap().searcher(); 133 | // only search title as text is too noisy 134 | let query_parser = tantivy::query::QueryParser::for_index(&index, vec![text_field]); 135 | 136 | info!("starting search using object store tantivy diretory"); 137 | let start = Instant::now(); 138 | for (idx, word) in words.iter().enumerate() { 139 | if idx % 1000 == 0 { 140 | info!("searched {} words in {:?}", idx, start.elapsed()); 141 | } 142 | searcherusing_object_store 143 | .search( 144 | &query_parser.parse_query(word).unwrap(), 145 | &tantivy::collector::TopDocs::with_limit(10), 146 | ) 147 | .unwrap(); 148 | } 149 | info!("search took {:?}", start.elapsed()); 150 | 151 | info!("checking if results are the same"); 152 | let start = Instant::now(); 153 | let mut total_overlap = 0; 154 | let mut total = 0; 155 | for (idx, word) in words.iter().enumerate() { 156 | if idx % 1000 == 0 { 157 | info!("searched {} words in {:?}", idx, start.elapsed()); 158 | } 159 | let mut top_docs = searcher 160 | .search( 161 | &query_parser.parse_query(word).unwrap(), 162 | &tantivy::collector::TopDocs::with_limit(100), 163 | ) 164 | .unwrap(); 165 | top_docs.sort_by(|(score_a, _), (score_b, _)| score_b.partial_cmp(score_a).unwrap()); 166 | let top_docs = top_docs 167 | .into_iter() 168 | .take(10) 169 | .map(|(_, doc)| { 170 | searcher 171 | .doc(doc) 172 | .unwrap() 173 | .get_first(id_field) 174 | .cloned() 175 | .unwrap() 176 | .as_u64() 177 | .unwrap() 178 | }) 179 | .collect::>(); 180 | 181 | let mut top_docs_using_object_store = searcherusing_object_store 182 | .search( 183 | &query_parser.parse_query(word).unwrap(), 184 | &tantivy::collector::TopDocs::with_limit(100), 185 | ) 186 | .unwrap(); 187 | top_docs_using_object_store 188 | .sort_by(|(score_a, _), (score_b, _)| score_b.partial_cmp(score_a).unwrap()); 189 | let top_docs_using_object_store = top_docs_using_object_store 190 | .into_iter() 191 | .take(10) 192 | .map(|(_, doc)| { 193 | searcherusing_object_store 194 | .doc(doc) 195 | .unwrap() 196 | .get_first(id_field) 197 | .cloned() 198 | .unwrap() 199 | .as_u64() 200 | .unwrap() 201 | }) 202 | .collect::>(); 203 | 204 | let min_size = std::cmp::min(top_docs_using_object_store.len(), top_docs.len()); 205 | total += min_size; 206 | 207 | let overlap = top_docs.intersection(&top_docs_using_object_store).count(); 208 | total_overlap += overlap; 209 | 210 | // At least 1 overlap 211 | assert!( 212 | top_docs.intersection(&top_docs_using_object_store).count() > 0 213 | || (top_docs_using_object_store.is_empty() && top_docs.is_empty()), 214 | "results are not the same for word {}, {}, {}, {}", 215 | word, 216 | overlap, 217 | top_docs.len(), 218 | top_docs_using_object_store.len() 219 | ); 220 | } 221 | 222 | // Tantivy index build is non-deterministic, so we can't expect the results to be exactly the same 223 | // check that overall the results are the very similar 224 | assert!( 225 | total_overlap > (total * 99 / 100), 226 | "results are not the same" 227 | ); 228 | } 229 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2023 Lance Developers. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | //! Object store (S3, GCS, etc.) support for tantivy. 16 | 17 | use async_trait::async_trait; 18 | use log::debug; 19 | use object_store::{local::LocalFileSystem, ObjectStore}; 20 | use std::{ 21 | fs::File, 22 | io::Write, 23 | ops::Range, 24 | path::{Path, PathBuf}, 25 | sync::{ 26 | atomic::{AtomicBool, Ordering}, 27 | Arc, 28 | }, 29 | }; 30 | use tantivy::{ 31 | directory::{ 32 | self, 33 | error::{DeleteError, LockError, OpenReadError, OpenWriteError}, 34 | AntiCallToken, Directory, DirectoryLock, FileHandle, OwnedBytes, TerminatingWrite, 35 | WatchCallback, WatchHandle, WritePtr, 36 | }, 37 | HasLen, 38 | }; 39 | 40 | use tokio::io::{AsyncReadExt, AsyncWriteExt}; 41 | 42 | use std::sync::Mutex; 43 | 44 | #[derive(Debug, Clone)] 45 | struct ObjectStoreDirectory { 46 | store: Arc, 47 | base_path: String, 48 | read_version: Option, 49 | write_version: u64, 50 | 51 | cache_loc: Arc, 52 | 53 | local_fs: Arc, 54 | 55 | rt: Arc, 56 | atomic_rw_lock: Arc>, 57 | } 58 | 59 | #[derive(Debug)] 60 | struct ObjectStoreFileHandle { 61 | store: Arc, 62 | path: object_store::path::Path, 63 | // We need to store this becasue the HasLen trait doesn't return a Result 64 | // We need to do the IO at construction time 65 | len: usize, 66 | 67 | rt: Arc, 68 | } 69 | 70 | impl ObjectStoreFileHandle { 71 | pub fn new( 72 | store: Arc, 73 | path: object_store::path::Path, 74 | len: usize, 75 | rt: Arc, 76 | ) -> Self { 77 | Self { 78 | store, 79 | path, 80 | len, 81 | rt, 82 | } 83 | } 84 | } 85 | 86 | impl HasLen for ObjectStoreFileHandle { 87 | fn len(&self) -> usize { 88 | self.len 89 | } 90 | } 91 | 92 | #[async_trait] 93 | impl FileHandle for ObjectStoreFileHandle { 94 | fn read_bytes(&self, range: Range) -> std::io::Result { 95 | let handle = self.rt.handle(); 96 | handle.block_on(async { self.read_bytes_async(range).await }) 97 | } 98 | 99 | #[doc(hidden)] 100 | async fn read_bytes_async(&self, byte_range: Range) -> std::io::Result { 101 | debug!("read_bytes_async: {:?} {:?}", self.path, byte_range); 102 | let bytes = self.store.get_range(&self.path, byte_range).await?; 103 | 104 | Ok(OwnedBytes::new(bytes.to_vec())) 105 | } 106 | } 107 | 108 | // super dumb implementation of a write handle 109 | // write to local and upload at once 110 | struct ObjectStoreWriteHandle { 111 | store: Arc, 112 | location: object_store::path::Path, 113 | local_path: Arc, 114 | 115 | write_handle: File, 116 | shutdown: AtomicBool, 117 | rt: Arc, 118 | } 119 | 120 | impl ObjectStoreWriteHandle { 121 | pub fn new( 122 | store: Arc, 123 | location: object_store::path::Path, 124 | cache_loc: Arc, 125 | rt: Arc, 126 | ) -> Result { 127 | let local_path = cache_loc.join(location.as_ref()); 128 | debug!("creating write handle for {:?}", local_path); 129 | let path = Path::new(&local_path); 130 | // create the necessary dir path for caching 131 | std::fs::create_dir_all(path.parent().ok_or(std::io::Error::new( 132 | std::io::ErrorKind::Other, 133 | "unable to create parent dir for cache", 134 | ))?)?; 135 | let f = File::create(local_path.clone())?; 136 | 137 | Ok(Self { 138 | store, 139 | location, 140 | local_path: Arc::new(local_path), 141 | write_handle: f, 142 | shutdown: AtomicBool::new(false), 143 | rt, 144 | }) 145 | } 146 | } 147 | 148 | impl Write for ObjectStoreWriteHandle { 149 | fn write(&mut self, buf: &[u8]) -> std::io::Result { 150 | if self.shutdown.load(Ordering::SeqCst) { 151 | return Err(std::io::Error::new( 152 | std::io::ErrorKind::BrokenPipe, 153 | "write handle has been shutdown", 154 | )); 155 | } 156 | 157 | self.write_handle.write(buf) 158 | } 159 | 160 | fn flush(&mut self) -> std::io::Result<()> { 161 | if self.shutdown.load(Ordering::SeqCst) { 162 | return Err(std::io::Error::new( 163 | std::io::ErrorKind::BrokenPipe, 164 | "write handle has been shutdown", 165 | )); 166 | } 167 | 168 | self.write_handle.flush() 169 | } 170 | } 171 | 172 | impl TerminatingWrite for ObjectStoreWriteHandle { 173 | fn terminate_ref(&mut self, _: AntiCallToken) -> std::io::Result<()> { 174 | let res = self.flush(); 175 | self.shutdown.store(true, Ordering::SeqCst); 176 | 177 | let result: Result<(), std::io::Error> = self.rt.block_on(async { 178 | let mut f = tokio::fs::File::open(self.local_path.as_path()).await?; 179 | 180 | let (_, mut sink) = self.store.put_multipart(&self.location).await?; 181 | // 1 mb blocks 182 | let mut buf = vec![0; 1024 * 1024]; 183 | 184 | loop { 185 | let n = f.read(&mut buf).await?; 186 | if n == 0 { 187 | break; 188 | } 189 | sink.write_all(&buf[..n]).await?; 190 | } 191 | 192 | sink.shutdown().await?; 193 | 194 | Ok(()) 195 | }); 196 | 197 | result?; 198 | 199 | res 200 | } 201 | } 202 | 203 | impl ObjectStoreDirectory { 204 | fn to_object_path(&self, path: &Path) -> Result { 205 | let p = path 206 | .to_str() 207 | .ok_or(std::io::Error::new( 208 | std::io::ErrorKind::InvalidInput, 209 | "non-utf8 path", 210 | ))? 211 | .to_string(); 212 | 213 | Ok(object_store::path::Path::from(format!( 214 | "{}/{}", 215 | self.base_path.clone(), 216 | p 217 | ))) 218 | } 219 | 220 | fn head(&self, path: &Path) -> Result { 221 | let location = self 222 | .to_object_path(path) 223 | .map_err(|e| OpenReadError::wrap_io_error(e, path.to_path_buf()))?; 224 | let handle = self.rt.handle(); 225 | handle 226 | .block_on(async { self.store.head(&location).await }) 227 | .map_err(|e| match e { 228 | object_store::Error::NotFound { .. } => { 229 | OpenReadError::FileDoesNotExist(path.to_path_buf()) 230 | } 231 | _ => OpenReadError::wrap_io_error( 232 | std::io::Error::new(std::io::ErrorKind::Other, format!("{:?}", e)), 233 | path.to_path_buf(), 234 | ), 235 | }) 236 | } 237 | } 238 | 239 | trait Lock: Send + Sync + 'static {} 240 | struct NoOpLock {} 241 | impl NoOpLock { 242 | pub fn new() -> Box { 243 | Box::new(Self {}) 244 | } 245 | } 246 | impl Lock for NoOpLock {} 247 | 248 | impl Directory for ObjectStoreDirectory { 249 | fn get_file_handle(&self, path: &Path) -> Result, OpenReadError> { 250 | debug!("get_file_handle({:?})", path); 251 | let location = self 252 | .to_object_path(path) 253 | .map_err(|e| OpenReadError::wrap_io_error(e, path.to_path_buf()))?; 254 | 255 | // Check if the file is in local upload cache 256 | let cache_path = self.cache_loc.join(location.as_ref()); 257 | let cache_path = object_store::path::Path::from(cache_path.to_string_lossy().as_ref()); 258 | if let Ok(meta) = self 259 | .rt 260 | .block_on(async { self.local_fs.head(&cache_path).await }) 261 | { 262 | debug!("upload cache hit: {:?}", path); 263 | return Ok(Arc::new(ObjectStoreFileHandle::new( 264 | self.local_fs.clone(), 265 | cache_path, 266 | meta.size, 267 | self.rt.clone(), 268 | ))); 269 | } 270 | 271 | let len = self.head(path)?.size; 272 | 273 | Ok(Arc::new(ObjectStoreFileHandle::new( 274 | self.store.clone(), 275 | location, 276 | len, 277 | self.rt.clone(), 278 | ))) 279 | } 280 | 281 | fn atomic_read(&self, path: &Path) -> Result, OpenReadError> { 282 | debug!("atomic_read({:?})", path); 283 | if path != Path::new("meta.json") && path != Path::new(".managed.json") { 284 | // Just blow up 285 | unimplemented!("Only meta.json is supported, but got {:?}", path) 286 | } 287 | 288 | // Inject versioning into path -- we want to enforce CoW here 289 | // if the write verison exist, read version has no effect 290 | // if the write version doesn't exist we read from the old version 291 | 292 | let buf = path.to_string_lossy(); 293 | let path_str = format!("{}.{}", buf, self.write_version); 294 | 295 | // Found write version already valid, read from the write version 296 | if let Ok(f) = self.get_file_handle(Path::new(&path_str)) { 297 | return Ok(f 298 | .read_bytes(0..f.len()) 299 | .map_err(|e| OpenReadError::wrap_io_error(e, path.to_path_buf()))? 300 | .to_vec()); 301 | } 302 | 303 | // No read version to copy from, return DNE 304 | if self.read_version.is_none() { 305 | return Err(OpenReadError::FileDoesNotExist(path.to_path_buf())); 306 | } 307 | 308 | let buf = path.to_string_lossy(); 309 | let path_str = format!( 310 | "{}.{}", 311 | buf, 312 | self.read_version.expect("already checked exists") 313 | ); 314 | let path = Path::new(&path_str); 315 | 316 | // lock so no one can write a dirty version 317 | let _lock = self.atomic_rw_lock.lock().unwrap(); 318 | let f = self.get_file_handle(path)?; 319 | Ok(f.read_bytes(0..f.len()) 320 | .map_err(|e| OpenReadError::wrap_io_error(e, path.to_path_buf()))? 321 | .to_vec()) 322 | } 323 | 324 | fn exists(&self, path: &std::path::Path) -> Result { 325 | match self.head(path) { 326 | Ok(_) => Ok(true), 327 | Err(OpenReadError::FileDoesNotExist(_)) => Ok(false), 328 | Err(e) => Err(e), 329 | } 330 | } 331 | 332 | // NOTE: the only thing that needs atomic write is the meta.json file 333 | // we add versioning here in this interface to load different versions 334 | // of the meta.json file at Directory construction time 335 | 336 | fn atomic_write(&self, path: &Path, data: &[u8]) -> std::io::Result<()> { 337 | debug!("atomic_write({:?})", path); 338 | if path != Path::new("meta.json") && path != Path::new(".managed.json") { 339 | // Just blow up 340 | unimplemented!("Only meta.json is supported") 341 | } 342 | 343 | // Inject versioning into path 344 | let buf = path.to_string_lossy(); 345 | let path_str = format!("{}.{}", buf, self.write_version); 346 | let path = Path::new(&path_str); 347 | 348 | let location = self.to_object_path(path)?; 349 | 350 | debug!("true location: {:?}", location); 351 | 352 | // Lock so no one can read a dirty version 353 | let _lock = self.atomic_rw_lock.lock().unwrap(); 354 | self.rt.handle().block_on(async { 355 | self.store 356 | .put(&location, bytes::Bytes::from(data.to_vec())) 357 | .await 358 | })?; 359 | 360 | Ok(()) 361 | } 362 | 363 | fn delete(&self, _: &Path) -> Result<(), DeleteError> { 364 | // Don't actually garbage collect since we want to have versioning of the meta.json file 365 | Ok(()) 366 | } 367 | 368 | fn open_write(&self, path: &Path) -> Result { 369 | debug!("open_write({:?})", path); 370 | let location = self 371 | .to_object_path(path) 372 | .map_err(|e| OpenWriteError::wrap_io_error(e, path.to_path_buf()))?; 373 | 374 | debug!("true location: {:?}", location); 375 | 376 | let write_handle = Box::new( 377 | ObjectStoreWriteHandle::new( 378 | self.store.clone(), 379 | location, 380 | self.cache_loc.clone(), 381 | self.rt.clone(), 382 | ) 383 | .map_err(|e| OpenWriteError::wrap_io_error(e, path.to_path_buf()))?, 384 | ); 385 | 386 | Ok(WritePtr::new(write_handle)) 387 | } 388 | 389 | fn sync_directory(&self) -> std::io::Result<()> { 390 | // Noop as synchronization is handled by the object store 391 | Ok(()) 392 | } 393 | 394 | fn watch(&self, _: WatchCallback) -> tantivy::Result { 395 | // We have reload mechanism from else where in the system 396 | // A sinlge index load will always be immutable 397 | Ok(WatchHandle::empty()) 398 | } 399 | 400 | fn acquire_lock(&self, _: &directory::Lock) -> Result { 401 | // We will manually garueentee index RW safety 402 | Ok(DirectoryLock::from(NoOpLock::new())) 403 | } 404 | } 405 | 406 | /// Create a new object store directory that implements CoW for the meta.json file 407 | /// 408 | /// # Arguments 409 | /// 410 | /// * store - An object store object 411 | /// 412 | /// * base_path - The base path to store the index, relative to the object store root 413 | /// 414 | /// * read_version - The version of the meta.json file to read from if a write version hasn't been created. 415 | /// Can not be greater than the write version. Has no effect if there is a write version. Index will be 416 | /// built from scratch if None is provided. 417 | /// 418 | /// * write_version - The version of the meta.json file to write to 419 | /// 420 | /// * cache_loc - The location to cache the meta.json file. If not provided, a random UUID will be used. 421 | /// This string is used for caching uploaded artifacts under /tmp/{cache_loc} directory 422 | /// 423 | /// * rt - An optional tokio runtime to use for async operations. If not provided, a new runtime will be created. 424 | /// NOTE: if you already run from an async context, dropping the returned Directory will cause the runtime to panic 425 | /// as it will attempt to shutdown the runtime inside an async context. 426 | /// 427 | /// # Example 428 | /// ``` 429 | /// use std::sync::Arc; 430 | /// 431 | /// use object_store::local::LocalFileSystem; 432 | /// use tantivy::{Index, IndexSettings, schema::{Schema, STORED, STRING, TEXT}}; 433 | /// use tantivy_object_store::new_object_store_directory; 434 | /// 435 | /// let store = Arc::new(LocalFileSystem::new()); 436 | /// let base_path = format!("/tmp/{}", uuid::Uuid::new_v4()); 437 | /// let dir = new_object_store_directory(store, &base_path, Some(0), 1, None, None).unwrap(); 438 | /// 439 | /// let mut schema_builder = Schema::builder(); 440 | /// let id_field = schema_builder.add_text_field("id", STRING); 441 | /// let text_field = schema_builder.add_text_field("text", TEXT | STORED); 442 | /// let schema = schema_builder.build(); 443 | /// 444 | /// let idx = tantivy::Index::create(dir, schema.clone(), IndexSettings::default()).unwrap(); 445 | /// 446 | /// 447 | pub fn new_object_store_directory( 448 | store: Arc, 449 | base_path: &str, 450 | read_version: Option, 451 | write_version: u64, 452 | cache_loc: Option<&str>, 453 | rt: Option>, 454 | ) -> Result, std::io::Error> { 455 | if let Some(read_version) = read_version { 456 | if read_version > write_version { 457 | return Err(std::io::Error::new( 458 | std::io::ErrorKind::InvalidInput, 459 | "read version cannot be greater than write version", 460 | )); 461 | } 462 | } 463 | 464 | let cache_loc = cache_loc 465 | .map(|s| Arc::new(Path::new(&s).to_owned())) 466 | .unwrap_or(Arc::new(tempfile::tempdir()?.path().to_owned())); 467 | 468 | Ok(Box::new(ObjectStoreDirectory { 469 | store, 470 | base_path: base_path.to_string(), 471 | read_version, 472 | write_version, 473 | local_fs: Arc::new(LocalFileSystem::new()), 474 | cache_loc, 475 | rt: rt.unwrap_or(Arc::new( 476 | tokio::runtime::Builder::new_multi_thread() 477 | .enable_all() 478 | .build()?, 479 | )), 480 | 481 | atomic_rw_lock: Arc::new(Mutex::new(())), 482 | })) 483 | } 484 | 485 | #[cfg(test)] 486 | mod test { 487 | use log::info; 488 | use object_store::local::LocalFileSystem; 489 | use std::sync::Arc; 490 | use tantivy::{ 491 | doc, 492 | schema::{Schema, STORED, STRING, TEXT}, 493 | IndexSettings, 494 | }; 495 | 496 | use crate::new_object_store_directory; 497 | 498 | #[test] 499 | fn test_full_workflow() { 500 | env_logger::init(); 501 | 502 | let store = Arc::new(LocalFileSystem::new()); 503 | 504 | let base_path = format!("/tmp/{}", uuid::Uuid::new_v4().hyphenated()); 505 | 506 | let dir = 507 | new_object_store_directory(store.clone(), &base_path, None, 0, None, None).unwrap(); 508 | 509 | let mut schema_builder = Schema::builder(); 510 | let id_field = schema_builder.add_text_field("id", STRING); 511 | let text_field = schema_builder.add_text_field("text", TEXT | STORED); 512 | let schema = schema_builder.build(); 513 | 514 | info!("Creating index"); 515 | let idx = tantivy::Index::create(dir, schema.clone(), IndexSettings::default()).unwrap(); 516 | 517 | info!("Creating writer"); 518 | let mut writer = idx.writer(1024 * 1024 * 64).unwrap(); 519 | info!("Write doc 1"); 520 | writer 521 | .add_document(doc!( 522 | id_field => "1", 523 | text_field => "hello world" 524 | )) 525 | .unwrap(); 526 | info!("Write doc 2"); 527 | writer 528 | .add_document(doc!( 529 | id_field => "2", 530 | text_field => "Deus Ex" 531 | )) 532 | .unwrap(); 533 | info!("COMMIT!"); 534 | writer.commit().unwrap(); 535 | 536 | std::mem::drop(writer); 537 | std::mem::drop(idx); 538 | 539 | // try open again and add some data 540 | let dir = 541 | new_object_store_directory(store.clone(), &base_path, Some(0), 1, None, None).unwrap(); 542 | 543 | info!("Open index"); 544 | let idx = tantivy::Index::open(dir).unwrap(); 545 | 546 | info!("Creating writer"); 547 | let mut writer = idx.writer(1024 * 1024 * 64).unwrap(); 548 | info!("Write doc 3"); 549 | writer 550 | .add_document(doc!( 551 | id_field => "3", 552 | text_field => "bye bye" 553 | )) 554 | .unwrap(); 555 | info!("COMMIT!"); 556 | writer.commit().unwrap(); 557 | info!("wait for merging threads"); 558 | writer.wait_merging_threads().unwrap(); 559 | 560 | std::mem::drop(idx); 561 | 562 | // open and search 563 | let dir = 564 | new_object_store_directory(store.clone(), &base_path, None, 0, None, None).unwrap(); 565 | 566 | info!("Open index"); 567 | let s3_idx = tantivy::Index::open(dir).unwrap(); 568 | let query_parser = 569 | tantivy::query::QueryParser::for_index(&s3_idx, vec![id_field, text_field]); 570 | let searcher = s3_idx.reader().unwrap().searcher(); 571 | 572 | info!("searching 1"); 573 | let query = query_parser.parse_query("hello").unwrap(); 574 | let top_docs = searcher 575 | .search(&query, &tantivy::collector::TopDocs::with_limit(10)) 576 | .unwrap(); 577 | assert_eq!(top_docs.len(), 1); 578 | let doc = top_docs.first().unwrap().1; 579 | let retrieved_doc = searcher.doc(doc).unwrap(); 580 | // we only store the text field, so there won't be an id field 581 | assert_eq!( 582 | retrieved_doc, 583 | doc!( 584 | text_field => "hello world" 585 | ) 586 | ); 587 | 588 | info!("searching 2"); 589 | // No result -- not in this version 590 | let query = query_parser.parse_query("bye").unwrap(); 591 | let top_docs = searcher 592 | .search(&query, &tantivy::collector::TopDocs::with_limit(10)) 593 | .unwrap(); 594 | assert_eq!(top_docs.len(), 0); 595 | 596 | info!("searching 3"); 597 | // finds the other doc 598 | let query = query_parser.parse_query("ex").unwrap(); 599 | let top_docs = searcher 600 | .search(&query, &tantivy::collector::TopDocs::with_limit(10)) 601 | .unwrap(); 602 | 603 | assert_eq!(top_docs.len(), 1); 604 | let doc = top_docs.first().unwrap().1; 605 | let retrieved_doc = searcher.doc(doc).unwrap(); 606 | // we only store the text field, so there won't be an id field 607 | assert_eq!( 608 | retrieved_doc, 609 | doc!( 610 | text_field => "Deus Ex" 611 | ) 612 | ); 613 | 614 | // open a differnet version and search 615 | let dir = 616 | new_object_store_directory(store.clone(), &base_path, None, 1, None, None).unwrap(); 617 | info!("Open Index"); 618 | let s3_idx = tantivy::Index::open(dir).unwrap(); 619 | let searcher = s3_idx.reader().unwrap().searcher(); 620 | 621 | info!("searching 4"); 622 | // is in the newer version 623 | let query = query_parser.parse_query("bye").unwrap(); 624 | let top_docs = searcher 625 | .search(&query, &tantivy::collector::TopDocs::with_limit(10)) 626 | .unwrap(); 627 | assert_eq!(top_docs.len(), 1); 628 | } 629 | } 630 | --------------------------------------------------------------------------------