├── .gitignore ├── CHANGELOG.md ├── LICENSE ├── README.md ├── analysis_options.yaml ├── assets └── dvdb.png ├── example └── dvdb_example.dart ├── lib ├── dvdb.dart └── src │ ├── collection.dart │ ├── document.dart │ ├── dvdb_helper.dart │ ├── errors.dart │ ├── math.dart │ └── search_result.dart ├── pubspec.lock ├── pubspec.yaml └── test └── dvdb_test.dart /.gitignore: -------------------------------------------------------------------------------- 1 | .dart_tool 2 | .DS_Store 3 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## 1.0.0 2 | 3 | - Initial version. 4 | 5 | ## 1.0.1 6 | 7 | - Minor Changes 8 | 9 | ## 1.0.2 10 | 11 | - Fix image link issue in Readme.md 12 | 13 | ## 1.0.3 14 | 15 | - Added repository link 16 | 17 | ## 1.0.4 18 | 19 | - Update pubspec.yaml 20 | 21 | ## 1.0.5 22 | 23 | - Added dart doc 24 | 25 | ## 1.0.6 26 | 27 | - Resolved version dependencies 28 | 29 | ## 1.0.7 30 | 31 | - Resolved version dependencies -------------------------------------------------------------------------------- /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 [2024] [Dhaval Taunk] 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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Mobile-First DVDB (Dart Vector DB): The Pocket-Sized Powerhouse for Your Apps! 🚀 2 | 3 | ![DVDB](assets/dvdb.png) 4 | 5 | This DVDB repository provides functionality to create a vector database locally on a mobile device. 6 | 7 | ## Why did we create this? 8 | We at [Fast Code AI](https://fastcode.ai/) were working on a use case that required us to create privacy-preserving, on-device vector databases, ensuring that private user information never left their devices. So, we started searching for suitable on-device vector databases on the internet. We found [SVDB](https://github.com/Dripfarm/SVDB), which provides on-device vector database support for iOS-based applications, and it worked well for our iOS application. However, we also needed one for Android. Alas, to the best of our knowledge, no such vector database existed for Android. 9 | 10 | 11 | ## Our solution 12 | One way to address this issue was to write a local vector database for Android similar to SVDB, but the main challenge in this scenario would be managing two different vector databases for both applications. Therefore, we considered writing a unified vector database that would work on both Android and iOS-based applications. In this repository, we have created a Dart-based vector db that can be used in Flutter-based applications. 13 | 14 | We have benchmarked the performance of our DVDB against SVDB on the iPhone 14. Additionally, we also have the same benchmarks on an Android device (Vivo 2252 Y02T) to demonstrate that it works on both devices, inlcuding low end devices. 15 | 16 | 17 | ## DVDB Highlights ✨ 18 | - **Privacy First**: Private user data never leaves their device, and do not reside on our services. You own your data and your embeddings. 19 | - **No Server, No Cry**: DVDB runs locally on device. Thus, zero latency and no hassle of server upkeep! 20 | - **OpenAI's Embeddings Support**: Add OpenAI Embeddings in DVDB in few lines of code. 21 | - **Custom Embeddings**: Create your own embeddings and add it in DVDB instead of OpenAI embeddings. 22 | - **Multi-platform Support**: Whether you're team Android or squad iOS, DVDB works on both, making app development a breezy affair. 23 | 24 | 25 | ## Launch Your Journey with DVDB 🚀 26 | 27 | ### Install Flutter 28 | 29 | - **Step 1**: Install the Flutter SDK from the [official website](https://flutter.dev/docs/get-started/install). 30 | - **Step 2**: Set up your development environment with your favorite IDE, and install the Dart plugin. 31 | - **Step 3**: Run `flutter doctor` in your terminal to ensure everything is set up properly. 32 | 33 | ### Install our DVDB 34 | 35 | - **Step 4**: Run `git clone https://github.com/FastCodeAI/DVDB.git` 36 | 37 | 38 | ## DVDB Quick Launch: Magic in Minutes! 🎩✨ 39 | 40 | After you've set up your codebase, it's time to start using DVDB! Check out the `vector_db_example.dart` in examples folder to see DVDB in action. Simply run the script from the command line as mentioned below: 41 | 42 | ```bash 43 | dart example/vector_db_example.dart 44 | ``` 45 | 46 | Want to use DVDB in your Flutter project? Just add the below command into your pubspec.yaml and start using it: 47 | 48 | ``` 49 | DVDB: 50 | path: ./path_to_dvdb_folder/DVDB/ 51 | ``` 52 | 53 | 54 | ## Explore More About DVDB 🔍 55 | 56 | ### Benchmakring Results: 57 | 58 | The following table shows the benchmarking results on SVDB as compared to DVDB on iPhone 14. 59 | ##### Note: The time is in miliseconds. 60 | 61 | #### Insertion over n documents 62 | 63 | | # vectors in DB | SVDB | DVDB | 64 | | --------------- | ------ | --------- | 65 | | 100 | 9801.3 | 15.9 | 66 | | 500 | 277903.0 | 45.36 | 67 | 68 | #### Searching 69 | 70 | | # vectors in DB | SVDB | DVDB | 71 | | --------------- | --------- | --------- | 72 | | 100 | 34.9418 | 15.9485 | 73 | | 500 | 93.7644 | 33.3472 | 74 | 75 | 76 | The following table shows the benchmarking results of DVDB on android phone. 77 | 78 | #### Insertion over n documents 79 | 80 | | # vectors in DB | DVDB | 81 | | --------------- | -------- | 82 | | 100 | 264.379 | 83 | | 500 | 891.433 | 84 | 85 | #### Searching 86 | 87 | | # vectors in DB | DVDB | 88 | | --------------- | -------- | 89 | | 100 | 67.309 | 90 | | 500 | 155.228 | 91 | 92 | 93 | -------------------------------------------------------------------------------- /analysis_options.yaml: -------------------------------------------------------------------------------- 1 | # This file configures the static analysis results for your project (errors, 2 | # warnings, and lints). 3 | # 4 | # This enables the 'recommended' set of lints from `package:lints`. 5 | # This set helps identify many issues that may lead to problems when running 6 | # or consuming Dart code, and enforces writing Dart using a single, idiomatic 7 | # style and format. 8 | # 9 | # If you want a smaller set of lints you can change this to specify 10 | # 'package:lints/core.yaml'. These are just the most critical lints 11 | # (the recommended set includes the core lints). 12 | # The core lints are also what is used by pub.dev for scoring packages. 13 | 14 | include: package:lints/recommended.yaml 15 | 16 | # Uncomment the following section to specify additional rules. 17 | 18 | # linter: 19 | # rules: 20 | # - camel_case_types 21 | 22 | # analyzer: 23 | # exclude: 24 | # - path/to/excluded/files/** 25 | 26 | # For more information about the core and recommended set of lints, see 27 | # https://dart.dev/go/core-lints 28 | 29 | # For additional information about configuring this file, see 30 | # https://dart.dev/guides/language/analysis-options 31 | -------------------------------------------------------------------------------- /assets/dvdb.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FastCodeAI/DVDB/9f4a75b2c0afa0e233d0908e2f3907939b4b7a6b/assets/dvdb.png -------------------------------------------------------------------------------- /example/dvdb_example.dart: -------------------------------------------------------------------------------- 1 | import 'dart:typed_data'; 2 | 3 | import 'package:dvdb/dvdb.dart'; 4 | import 'dart:convert'; 5 | import 'package:http/http.dart' as http; 6 | 7 | const String openaiApiKey = 'sk-your_api_key'; // Replace with your OpenAI API key 8 | const String openaiUrl = 'https://api.openai.com/v1/embeddings'; 9 | 10 | void main() async { 11 | var headers = { 12 | 'Content-Type': 'application/json', 13 | 'Authorization': 'Bearer $openaiApiKey' 14 | }; 15 | 16 | var collection = DVDB().collection("Test"); 17 | 18 | var texts = ['cat', 'dog', 'lion']; 19 | 20 | for (var text in texts) { 21 | try { 22 | var requestBody = jsonEncode({ 23 | 'input': text, 24 | 'model': 'text-embedding-ada-002' 25 | }); 26 | 27 | var response = await http.post(Uri.parse(openaiUrl), headers: headers, body: requestBody); 28 | 29 | if (response.statusCode == 200) { 30 | var jsonResponse = jsonDecode(response.body); 31 | Float64List embedding = jsonResponse['data'][0]['embedding']; 32 | print('Response from OpenAI: ${embedding.runtimeType}'); 33 | collection.addDocument(null, text, embedding); 34 | } 35 | else { 36 | print('Request failed with status: ${response.statusCode}.'); 37 | print('Response body: ${response.body}'); 38 | } 39 | } 40 | catch(e) { 41 | print('An error occurred: $e'); 42 | } 43 | } 44 | 45 | try { 46 | var requestBody = jsonEncode({ 47 | 'input': 'tiger', 48 | 'model': 'text-embedding-ada-002' 49 | }); 50 | 51 | var response = await http.post(Uri.parse(openaiUrl), headers: headers, body: requestBody); 52 | if (response.statusCode == 200) { 53 | var jsonResponse = jsonDecode(response.body); 54 | Float64List embedding = jsonResponse['data'][0]['embedding']; 55 | 56 | final query = collection.search(embedding, numResults: 1); 57 | 58 | query.forEach((element) { 59 | 60 | print("${element.score} || ${element.text}"); 61 | }); 62 | } 63 | else { 64 | print('Request failed with status: ${response.statusCode}.'); 65 | print('Response body: ${response.body}'); 66 | } 67 | } 68 | catch(e){ 69 | print(e); 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /lib/dvdb.dart: -------------------------------------------------------------------------------- 1 | library; 2 | 3 | export 'src/collection.dart'; 4 | export 'src/document.dart'; 5 | export 'src/errors.dart'; 6 | export 'src/dvdb_helper.dart'; 7 | -------------------------------------------------------------------------------- /lib/src/collection.dart: -------------------------------------------------------------------------------- 1 | import 'dart:convert'; 2 | import 'dart:core'; 3 | import 'dart:io'; 4 | import 'dart:typed_data'; 5 | 6 | import 'package:path/path.dart'; 7 | import 'package:path_provider/path_provider.dart'; 8 | import 'package:uuid/uuid.dart'; 9 | import 'package:dvdb/src/document.dart'; 10 | import 'package:dvdb/src/math.dart'; 11 | import 'package:dvdb/src/search_result.dart'; 12 | 13 | class Collection { 14 | Collection(this.name); 15 | 16 | final String name; 17 | final Map documents = {}; 18 | 19 | void addDocument(String? id, String text, Float64List embedding, {Map? metadata}) { 20 | var uuid = Uuid(); 21 | final Document document = Document( 22 | id: id ?? uuid.v1(), 23 | text: text, 24 | embedding: embedding, 25 | metadata: metadata, 26 | ); 27 | 28 | documents[document.id] = document; 29 | _writeDocument(document); 30 | } 31 | 32 | void addDocuments(List docs) { 33 | for (final Document doc in docs) { 34 | documents[doc.id] = doc; 35 | _writeDocument(doc); 36 | } 37 | } 38 | 39 | void removeDocument(String id) { 40 | if (documents.containsKey(id)) { 41 | documents.remove(id); 42 | _saveAllDocuments(); // Re-saving all documents after removal 43 | } 44 | } 45 | 46 | List search(Float64List query, {int numResults = 10, double? threshold}) { 47 | 48 | final List similarities = []; 49 | for (var document in documents.values) { 50 | final double similarity = MathFunctions().cosineSimilarity(query, document.embedding); 51 | 52 | if (threshold != null && similarity < threshold) { 53 | continue; 54 | } 55 | 56 | similarities.add(SearchResult(id:document.id, text:document.text, score:similarity)); 57 | } 58 | 59 | similarities.sort((SearchResult a, SearchResult b) => b.score.compareTo(a.score)); 60 | return similarities.take(numResults).toList(); 61 | } 62 | 63 | Future _writeDocument(Document document) async { 64 | Directory documentsDirectory = await getApplicationDocumentsDirectory(); 65 | String path = join(documentsDirectory.path, '$name.json'); 66 | final File file = File(path); 67 | 68 | var encodedDocument = json.encode(document.toJson()); 69 | List bytes = utf8.encode('$encodedDocument\n'); 70 | 71 | file.writeAsBytesSync(bytes, mode: FileMode.append); 72 | } 73 | 74 | Future _saveAllDocuments() async { 75 | Directory documentsDirectory = await getApplicationDocumentsDirectory(); 76 | String path = join(documentsDirectory.path, '$name.json'); 77 | final File file = File(path); 78 | 79 | file.writeAsStringSync(''); // Clearing the file 80 | for (var document in documents.values) { 81 | _writeDocument(document); 82 | } 83 | } 84 | 85 | Future load() async { 86 | Directory documentsDirectory = await getApplicationDocumentsDirectory(); 87 | String path = join(documentsDirectory.path, '$name.json'); 88 | final File file = File(path); 89 | 90 | if (!file.existsSync()) { 91 | documents.clear(); 92 | return; 93 | } 94 | 95 | final lines = file.readAsLinesSync(); 96 | 97 | for (var line in lines) { 98 | var decodedDocument = json.decode(line) as Map; 99 | var document = Document.fromJson(decodedDocument); 100 | documents[document.id] = document; 101 | } 102 | } 103 | 104 | void clear() { 105 | documents.clear(); 106 | _saveAllDocuments(); 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /lib/src/document.dart: -------------------------------------------------------------------------------- 1 | import 'dart:math'; 2 | import 'dart:typed_data'; 3 | import 'package:uuid/uuid.dart'; 4 | 5 | class Document { 6 | Document({String? id, required this.text, required this.embedding, Map? metadata}) 7 | : id = id ?? _generateUuid(), 8 | magnitude = _calculateMagnitude(embedding), 9 | metadata = metadata ?? Map(); 10 | 11 | final String id; 12 | final String text; 13 | final Float64List embedding; 14 | final double magnitude; 15 | final Map metadata; 16 | 17 | static String _generateUuid() { 18 | return Uuid().v1(); 19 | } 20 | 21 | static double _calculateMagnitude(Float64List embedding) { 22 | return sqrt(embedding.fold(0, (num sum, double element) => sum + element * element)); 23 | } 24 | 25 | Map toJson() { 26 | return { 27 | 'id': id, 28 | 'text': text, 29 | 'embedding': embedding, 30 | 'magnitude': magnitude, 31 | 'metadata': metadata, 32 | }; 33 | } 34 | 35 | factory Document.fromJson(Map json) { 36 | return Document( 37 | id: json['id'], 38 | text: json['text'], 39 | embedding: Float64List.fromList(json['embedding'].cast()), 40 | metadata: Map.from(json['metadata']) 41 | ); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /lib/src/dvdb_helper.dart: -------------------------------------------------------------------------------- 1 | import 'package:dvdb/dvdb.dart'; 2 | 3 | class DVDB { 4 | DVDB._internal(); 5 | 6 | static final DVDB _shared = DVDB._internal(); 7 | 8 | factory DVDB() { 9 | return _shared; 10 | } 11 | 12 | final Map _collections = {}; 13 | 14 | Collection collection(String name) { 15 | if (_collections.containsKey(name)) { 16 | return _collections[name]!; 17 | } 18 | 19 | final Collection collection = Collection(name); 20 | _collections[name] = collection; 21 | collection.load(); 22 | return collection; 23 | } 24 | 25 | Collection? getCollection(String name) { 26 | return _collections[name]; 27 | } 28 | 29 | void releaseCollection(String name) { 30 | _collections.remove(name); 31 | } 32 | 33 | void reset() { 34 | for (final Collection collection in _collections.values) { 35 | collection.clear(); 36 | } 37 | _collections.clear(); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /lib/src/errors.dart: -------------------------------------------------------------------------------- 1 | enum VectorDBError { 2 | collectionAlreadyExists, 3 | } 4 | 5 | class CollectionError implements Exception { 6 | CollectionError._(this.message); 7 | 8 | final String message; 9 | 10 | factory CollectionError.fileNotFound() { 11 | return CollectionError._("File not found."); 12 | } 13 | 14 | factory CollectionError.loadFailed(String errorMessage) { 15 | return CollectionError._("Load failed: $errorMessage"); 16 | } 17 | 18 | @override 19 | String toString() { 20 | return message; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /lib/src/math.dart: -------------------------------------------------------------------------------- 1 | import 'package:ml_linalg/linalg.dart'; 2 | 3 | class MathFunctions { 4 | MathFunctions._internal(); 5 | 6 | static final MathFunctions _shared = MathFunctions._internal(); 7 | 8 | factory MathFunctions() { 9 | return _shared; 10 | } 11 | 12 | double cosineSimilarity(List a, List b) { 13 | assert(a.length == b.length); 14 | 15 | Vector aVector = Vector.fromList(a); 16 | Vector bVector = Vector.fromList(b); 17 | 18 | double dotProduct = aVector.dot(bVector); 19 | 20 | double aNorm = aVector.norm(); 21 | double bNorm = bVector.norm(); 22 | 23 | if (aNorm == 0 || bNorm == 0) { 24 | return 0.0; 25 | } else { 26 | return dotProduct / (aNorm * bNorm); 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /lib/src/search_result.dart: -------------------------------------------------------------------------------- 1 | import 'dart:core'; 2 | 3 | class SearchResult { 4 | SearchResult({required this.id, required this.text, required this.score}); 5 | 6 | final String id; 7 | final String text; 8 | final double score; 9 | 10 | // Optional: If you need to serialize/deserialize to/from JSON 11 | factory SearchResult.fromJson(Map json) { 12 | return SearchResult( 13 | id: json['id'], 14 | text: json['text'], 15 | score: json['score'].toDouble(), 16 | ); 17 | } 18 | 19 | Map toJson() { 20 | return { 21 | 'id': id, 22 | 'text': text, 23 | 'score': score, 24 | }; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /pubspec.lock: -------------------------------------------------------------------------------- 1 | # Generated by pub 2 | # See https://dart.dev/tools/pub/glossary#lockfile 3 | packages: 4 | _fe_analyzer_shared: 5 | dependency: transitive 6 | description: 7 | name: _fe_analyzer_shared 8 | sha256: eb376e9acf6938204f90eb3b1f00b578640d3188b4c8a8ec054f9f479af8d051 9 | url: "https://pub.dev" 10 | source: hosted 11 | version: "64.0.0" 12 | analyzer: 13 | dependency: transitive 14 | description: 15 | name: analyzer 16 | sha256: "69f54f967773f6c26c7dcb13e93d7ccee8b17a641689da39e878d5cf13b06893" 17 | url: "https://pub.dev" 18 | source: hosted 19 | version: "6.2.0" 20 | args: 21 | dependency: transitive 22 | description: 23 | name: args 24 | sha256: eef6c46b622e0494a36c5a12d10d77fb4e855501a91c1b9ef9339326e58f0596 25 | url: "https://pub.dev" 26 | source: hosted 27 | version: "2.4.2" 28 | async: 29 | dependency: transitive 30 | description: 31 | name: async 32 | sha256: "947bfcf187f74dbc5e146c9eb9c0f10c9f8b30743e341481c1e2ed3ecc18c20c" 33 | url: "https://pub.dev" 34 | source: hosted 35 | version: "2.11.0" 36 | boolean_selector: 37 | dependency: transitive 38 | description: 39 | name: boolean_selector 40 | sha256: "6cfb5af12253eaf2b368f07bacc5a80d1301a071c73360d746b7f2e32d762c66" 41 | url: "https://pub.dev" 42 | source: hosted 43 | version: "2.1.1" 44 | characters: 45 | dependency: transitive 46 | description: 47 | name: characters 48 | sha256: "04a925763edad70e8443c99234dc3328f442e811f1d8fd1a72f1c8ad0f69a605" 49 | url: "https://pub.dev" 50 | source: hosted 51 | version: "1.3.0" 52 | collection: 53 | dependency: transitive 54 | description: 55 | name: collection 56 | sha256: ee67cb0715911d28db6bf4af1026078bd6f0128b07a5f66fb2ed94ec6783c09a 57 | url: "https://pub.dev" 58 | source: hosted 59 | version: "1.18.0" 60 | convert: 61 | dependency: transitive 62 | description: 63 | name: convert 64 | sha256: "0f08b14755d163f6e2134cb58222dd25ea2a2ee8a195e53983d57c075324d592" 65 | url: "https://pub.dev" 66 | source: hosted 67 | version: "3.1.1" 68 | coverage: 69 | dependency: transitive 70 | description: 71 | name: coverage 72 | sha256: "8acabb8306b57a409bf4c83522065672ee13179297a6bb0cb9ead73948df7c76" 73 | url: "https://pub.dev" 74 | source: hosted 75 | version: "1.7.2" 76 | crypto: 77 | dependency: transitive 78 | description: 79 | name: crypto 80 | sha256: ff625774173754681d66daaf4a448684fb04b78f902da9cb3d308c19cc5e8bab 81 | url: "https://pub.dev" 82 | source: hosted 83 | version: "3.0.3" 84 | ffi: 85 | dependency: transitive 86 | description: 87 | name: ffi 88 | sha256: "7bf0adc28a23d395f19f3f1eb21dd7cfd1dd9f8e1c50051c069122e6853bc878" 89 | url: "https://pub.dev" 90 | source: hosted 91 | version: "2.1.0" 92 | file: 93 | dependency: transitive 94 | description: 95 | name: file 96 | sha256: "5fc22d7c25582e38ad9a8515372cd9a93834027aacf1801cf01164dac0ffa08c" 97 | url: "https://pub.dev" 98 | source: hosted 99 | version: "7.0.0" 100 | fixnum: 101 | dependency: transitive 102 | description: 103 | name: fixnum 104 | sha256: "25517a4deb0c03aa0f32fd12db525856438902d9c16536311e76cdc57b31d7d1" 105 | url: "https://pub.dev" 106 | source: hosted 107 | version: "1.1.0" 108 | flutter: 109 | dependency: transitive 110 | description: flutter 111 | source: sdk 112 | version: "0.0.0" 113 | frontend_server_client: 114 | dependency: transitive 115 | description: 116 | name: frontend_server_client 117 | sha256: "408e3ca148b31c20282ad6f37ebfa6f4bdc8fede5b74bc2f08d9d92b55db3612" 118 | url: "https://pub.dev" 119 | source: hosted 120 | version: "3.2.0" 121 | glob: 122 | dependency: transitive 123 | description: 124 | name: glob 125 | sha256: "0e7014b3b7d4dac1ca4d6114f82bf1782ee86745b9b42a92c9289c23d8a0ab63" 126 | url: "https://pub.dev" 127 | source: hosted 128 | version: "2.1.2" 129 | http: 130 | dependency: "direct main" 131 | description: 132 | name: http 133 | sha256: a2bbf9d017fcced29139daa8ed2bba4ece450ab222871df93ca9eec6f80c34ba 134 | url: "https://pub.dev" 135 | source: hosted 136 | version: "1.2.0" 137 | http_multi_server: 138 | dependency: transitive 139 | description: 140 | name: http_multi_server 141 | sha256: "97486f20f9c2f7be8f514851703d0119c3596d14ea63227af6f7a481ef2b2f8b" 142 | url: "https://pub.dev" 143 | source: hosted 144 | version: "3.2.1" 145 | http_parser: 146 | dependency: transitive 147 | description: 148 | name: http_parser 149 | sha256: "2aa08ce0341cc9b354a498388e30986515406668dbcc4f7c950c3e715496693b" 150 | url: "https://pub.dev" 151 | source: hosted 152 | version: "4.0.2" 153 | io: 154 | dependency: transitive 155 | description: 156 | name: io 157 | sha256: "2ec25704aba361659e10e3e5f5d672068d332fc8ac516421d483a11e5cbd061e" 158 | url: "https://pub.dev" 159 | source: hosted 160 | version: "1.0.4" 161 | js: 162 | dependency: transitive 163 | description: 164 | name: js 165 | sha256: c1b2e9b5ea78c45e1a0788d29606ba27dc5f71f019f32ca5140f61ef071838cf 166 | url: "https://pub.dev" 167 | source: hosted 168 | version: "0.7.1" 169 | lints: 170 | dependency: "direct dev" 171 | description: 172 | name: lints 173 | sha256: cbf8d4b858bb0134ef3ef87841abdf8d63bfc255c266b7bf6b39daa1085c4290 174 | url: "https://pub.dev" 175 | source: hosted 176 | version: "3.0.0" 177 | logging: 178 | dependency: transitive 179 | description: 180 | name: logging 181 | sha256: "623a88c9594aa774443aa3eb2d41807a48486b5613e67599fb4c41c0ad47c340" 182 | url: "https://pub.dev" 183 | source: hosted 184 | version: "1.2.0" 185 | matcher: 186 | dependency: transitive 187 | description: 188 | name: matcher 189 | sha256: d2323aa2060500f906aa31a895b4030b6da3ebdcc5619d14ce1aada65cd161cb 190 | url: "https://pub.dev" 191 | source: hosted 192 | version: "0.12.16+1" 193 | material_color_utilities: 194 | dependency: transitive 195 | description: 196 | name: material_color_utilities 197 | sha256: "9528f2f296073ff54cb9fee677df673ace1218163c3bc7628093e7eed5203d41" 198 | url: "https://pub.dev" 199 | source: hosted 200 | version: "0.5.0" 201 | meta: 202 | dependency: transitive 203 | description: 204 | name: meta 205 | sha256: a6e590c838b18133bb482a2745ad77c5bb7715fb0451209e1a7567d416678b8e 206 | url: "https://pub.dev" 207 | source: hosted 208 | version: "1.10.0" 209 | mime: 210 | dependency: transitive 211 | description: 212 | name: mime 213 | sha256: "2e123074287cc9fd6c09de8336dae606d1ddb88d9ac47358826db698c176a1f2" 214 | url: "https://pub.dev" 215 | source: hosted 216 | version: "1.0.5" 217 | ml_linalg: 218 | dependency: "direct main" 219 | description: 220 | name: ml_linalg 221 | sha256: "304cb8a2a172f2303226d672d0b6f18dbfe558e2db49d27c8aa9f3e15475c0cd" 222 | url: "https://pub.dev" 223 | source: hosted 224 | version: "13.12.2" 225 | node_preamble: 226 | dependency: transitive 227 | description: 228 | name: node_preamble 229 | sha256: "6e7eac89047ab8a8d26cf16127b5ed26de65209847630400f9aefd7cd5c730db" 230 | url: "https://pub.dev" 231 | source: hosted 232 | version: "2.0.2" 233 | package_config: 234 | dependency: transitive 235 | description: 236 | name: package_config 237 | sha256: "1c5b77ccc91e4823a5af61ee74e6b972db1ef98c2ff5a18d3161c982a55448bd" 238 | url: "https://pub.dev" 239 | source: hosted 240 | version: "2.1.0" 241 | path: 242 | dependency: "direct main" 243 | description: 244 | name: path 245 | sha256: "087ce49c3f0dc39180befefc60fdb4acd8f8620e5682fe2476afd0b3688bb4af" 246 | url: "https://pub.dev" 247 | source: hosted 248 | version: "1.9.0" 249 | path_provider: 250 | dependency: "direct main" 251 | description: 252 | name: path_provider 253 | sha256: b27217933eeeba8ff24845c34003b003b2b22151de3c908d0e679e8fe1aa078b 254 | url: "https://pub.dev" 255 | source: hosted 256 | version: "2.1.2" 257 | path_provider_android: 258 | dependency: transitive 259 | description: 260 | name: path_provider_android 261 | sha256: "477184d672607c0a3bf68fbbf601805f92ef79c82b64b4d6eb318cbca4c48668" 262 | url: "https://pub.dev" 263 | source: hosted 264 | version: "2.2.2" 265 | path_provider_foundation: 266 | dependency: transitive 267 | description: 268 | name: path_provider_foundation 269 | sha256: "5a7999be66e000916500be4f15a3633ebceb8302719b47b9cc49ce924125350f" 270 | url: "https://pub.dev" 271 | source: hosted 272 | version: "2.3.2" 273 | path_provider_linux: 274 | dependency: transitive 275 | description: 276 | name: path_provider_linux 277 | sha256: f7a1fe3a634fe7734c8d3f2766ad746ae2a2884abe22e241a8b301bf5cac3279 278 | url: "https://pub.dev" 279 | source: hosted 280 | version: "2.2.1" 281 | path_provider_platform_interface: 282 | dependency: transitive 283 | description: 284 | name: path_provider_platform_interface 285 | sha256: "88f5779f72ba699763fa3a3b06aa4bf6de76c8e5de842cf6f29e2e06476c2334" 286 | url: "https://pub.dev" 287 | source: hosted 288 | version: "2.1.2" 289 | path_provider_windows: 290 | dependency: transitive 291 | description: 292 | name: path_provider_windows 293 | sha256: "8bc9f22eee8690981c22aa7fc602f5c85b497a6fb2ceb35ee5a5e5ed85ad8170" 294 | url: "https://pub.dev" 295 | source: hosted 296 | version: "2.2.1" 297 | platform: 298 | dependency: transitive 299 | description: 300 | name: platform 301 | sha256: "12220bb4b65720483f8fa9450b4332347737cf8213dd2840d8b2c823e47243ec" 302 | url: "https://pub.dev" 303 | source: hosted 304 | version: "3.1.4" 305 | plugin_platform_interface: 306 | dependency: transitive 307 | description: 308 | name: plugin_platform_interface 309 | sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02" 310 | url: "https://pub.dev" 311 | source: hosted 312 | version: "2.1.8" 313 | pool: 314 | dependency: transitive 315 | description: 316 | name: pool 317 | sha256: "20fe868b6314b322ea036ba325e6fc0711a22948856475e2c2b6306e8ab39c2a" 318 | url: "https://pub.dev" 319 | source: hosted 320 | version: "1.5.1" 321 | pub_semver: 322 | dependency: transitive 323 | description: 324 | name: pub_semver 325 | sha256: "40d3ab1bbd474c4c2328c91e3a7df8c6dd629b79ece4c4bd04bee496a224fb0c" 326 | url: "https://pub.dev" 327 | source: hosted 328 | version: "2.1.4" 329 | quiver: 330 | dependency: transitive 331 | description: 332 | name: quiver 333 | sha256: b1c1ac5ce6688d77f65f3375a9abb9319b3cb32486bdc7a1e0fdf004d7ba4e47 334 | url: "https://pub.dev" 335 | source: hosted 336 | version: "3.2.1" 337 | shelf: 338 | dependency: transitive 339 | description: 340 | name: shelf 341 | sha256: ad29c505aee705f41a4d8963641f91ac4cee3c8fad5947e033390a7bd8180fa4 342 | url: "https://pub.dev" 343 | source: hosted 344 | version: "1.4.1" 345 | shelf_packages_handler: 346 | dependency: transitive 347 | description: 348 | name: shelf_packages_handler 349 | sha256: "89f967eca29607c933ba9571d838be31d67f53f6e4ee15147d5dc2934fee1b1e" 350 | url: "https://pub.dev" 351 | source: hosted 352 | version: "3.0.2" 353 | shelf_static: 354 | dependency: transitive 355 | description: 356 | name: shelf_static 357 | sha256: a41d3f53c4adf0f57480578c1d61d90342cd617de7fc8077b1304643c2d85c1e 358 | url: "https://pub.dev" 359 | source: hosted 360 | version: "1.1.2" 361 | shelf_web_socket: 362 | dependency: transitive 363 | description: 364 | name: shelf_web_socket 365 | sha256: "9ca081be41c60190ebcb4766b2486a7d50261db7bd0f5d9615f2d653637a84c1" 366 | url: "https://pub.dev" 367 | source: hosted 368 | version: "1.0.4" 369 | sky_engine: 370 | dependency: transitive 371 | description: flutter 372 | source: sdk 373 | version: "0.0.99" 374 | source_map_stack_trace: 375 | dependency: transitive 376 | description: 377 | name: source_map_stack_trace 378 | sha256: "84cf769ad83aa6bb61e0aa5a18e53aea683395f196a6f39c4c881fb90ed4f7ae" 379 | url: "https://pub.dev" 380 | source: hosted 381 | version: "2.1.1" 382 | source_maps: 383 | dependency: transitive 384 | description: 385 | name: source_maps 386 | sha256: "708b3f6b97248e5781f493b765c3337db11c5d2c81c3094f10904bfa8004c703" 387 | url: "https://pub.dev" 388 | source: hosted 389 | version: "0.10.12" 390 | source_span: 391 | dependency: transitive 392 | description: 393 | name: source_span 394 | sha256: "53e943d4206a5e30df338fd4c6e7a077e02254531b138a15aec3bd143c1a8b3c" 395 | url: "https://pub.dev" 396 | source: hosted 397 | version: "1.10.0" 398 | sprintf: 399 | dependency: transitive 400 | description: 401 | name: sprintf 402 | sha256: "1fc9ffe69d4df602376b52949af107d8f5703b77cda567c4d7d86a0693120f23" 403 | url: "https://pub.dev" 404 | source: hosted 405 | version: "7.0.0" 406 | stack_trace: 407 | dependency: transitive 408 | description: 409 | name: stack_trace 410 | sha256: "73713990125a6d93122541237550ee3352a2d84baad52d375a4cad2eb9b7ce0b" 411 | url: "https://pub.dev" 412 | source: hosted 413 | version: "1.11.1" 414 | stream_channel: 415 | dependency: transitive 416 | description: 417 | name: stream_channel 418 | sha256: ba2aa5d8cc609d96bbb2899c28934f9e1af5cddbd60a827822ea467161eb54e7 419 | url: "https://pub.dev" 420 | source: hosted 421 | version: "2.1.2" 422 | string_scanner: 423 | dependency: transitive 424 | description: 425 | name: string_scanner 426 | sha256: "556692adab6cfa87322a115640c11f13cb77b3f076ddcc5d6ae3c20242bedcde" 427 | url: "https://pub.dev" 428 | source: hosted 429 | version: "1.2.0" 430 | term_glyph: 431 | dependency: transitive 432 | description: 433 | name: term_glyph 434 | sha256: a29248a84fbb7c79282b40b8c72a1209db169a2e0542bce341da992fe1bc7e84 435 | url: "https://pub.dev" 436 | source: hosted 437 | version: "1.2.1" 438 | test: 439 | dependency: "direct dev" 440 | description: 441 | name: test 442 | sha256: "7ee446762c2c50b3bd4ea96fe13ffac69919352bd3b4b17bac3f3465edc58073" 443 | url: "https://pub.dev" 444 | source: hosted 445 | version: "1.25.2" 446 | test_api: 447 | dependency: transitive 448 | description: 449 | name: test_api 450 | sha256: "9955ae474176f7ac8ee4e989dadfb411a58c30415bcfb648fa04b2b8a03afa7f" 451 | url: "https://pub.dev" 452 | source: hosted 453 | version: "0.7.0" 454 | test_core: 455 | dependency: transitive 456 | description: 457 | name: test_core 458 | sha256: "2bc4b4ecddd75309300d8096f781c0e3280ca1ef85beda558d33fcbedc2eead4" 459 | url: "https://pub.dev" 460 | source: hosted 461 | version: "0.6.0" 462 | typed_data: 463 | dependency: transitive 464 | description: 465 | name: typed_data 466 | sha256: facc8d6582f16042dd49f2463ff1bd6e2c9ef9f3d5da3d9b087e244a7b564b3c 467 | url: "https://pub.dev" 468 | source: hosted 469 | version: "1.3.2" 470 | uuid: 471 | dependency: "direct main" 472 | description: 473 | name: uuid 474 | sha256: cd210a09f7c18cbe5a02511718e0334de6559871052c90a90c0cca46a4aa81c8 475 | url: "https://pub.dev" 476 | source: hosted 477 | version: "4.3.3" 478 | vector_math: 479 | dependency: transitive 480 | description: 481 | name: vector_math 482 | sha256: "80b3257d1492ce4d091729e3a67a60407d227c27241d6927be0130c98e741803" 483 | url: "https://pub.dev" 484 | source: hosted 485 | version: "2.1.4" 486 | vm_service: 487 | dependency: transitive 488 | description: 489 | name: vm_service 490 | sha256: a2662fb1f114f4296cf3f5a50786a2d888268d7776cf681aa17d660ffa23b246 491 | url: "https://pub.dev" 492 | source: hosted 493 | version: "14.0.0" 494 | watcher: 495 | dependency: transitive 496 | description: 497 | name: watcher 498 | sha256: "3d2ad6751b3c16cf07c7fca317a1413b3f26530319181b37e3b9039b84fc01d8" 499 | url: "https://pub.dev" 500 | source: hosted 501 | version: "1.1.0" 502 | web: 503 | dependency: transitive 504 | description: 505 | name: web 506 | sha256: afe077240a270dcfd2aafe77602b4113645af95d0ad31128cc02bce5ac5d5152 507 | url: "https://pub.dev" 508 | source: hosted 509 | version: "0.3.0" 510 | web_socket_channel: 511 | dependency: transitive 512 | description: 513 | name: web_socket_channel 514 | sha256: d88238e5eac9a42bb43ca4e721edba3c08c6354d4a53063afaa568516217621b 515 | url: "https://pub.dev" 516 | source: hosted 517 | version: "2.4.0" 518 | webkit_inspection_protocol: 519 | dependency: transitive 520 | description: 521 | name: webkit_inspection_protocol 522 | sha256: "87d3f2333bb240704cd3f1c6b5b7acd8a10e7f0bc28c28dcf14e782014f4a572" 523 | url: "https://pub.dev" 524 | source: hosted 525 | version: "1.2.1" 526 | win32: 527 | dependency: transitive 528 | description: 529 | name: win32 530 | sha256: "464f5674532865248444b4c3daca12bd9bf2d7c47f759ce2617986e7229494a8" 531 | url: "https://pub.dev" 532 | source: hosted 533 | version: "5.2.0" 534 | xdg_directories: 535 | dependency: transitive 536 | description: 537 | name: xdg_directories 538 | sha256: faea9dee56b520b55a566385b84f2e8de55e7496104adada9962e0bd11bcff1d 539 | url: "https://pub.dev" 540 | source: hosted 541 | version: "1.0.4" 542 | yaml: 543 | dependency: transitive 544 | description: 545 | name: yaml 546 | sha256: "75769501ea3489fca56601ff33454fe45507ea3bfb014161abc3b43ae25989d5" 547 | url: "https://pub.dev" 548 | source: hosted 549 | version: "3.1.2" 550 | sdks: 551 | dart: ">=3.2.4 <4.0.0" 552 | flutter: ">=3.10.0" 553 | -------------------------------------------------------------------------------- /pubspec.yaml: -------------------------------------------------------------------------------- 1 | name: dvdb 2 | description: A dart based on-device vector database. It is compatible to both iOS and Android. 3 | version: 1.0.7 4 | repository: https://github.com/FastCodeAI/DVDB 5 | 6 | environment: 7 | sdk: ^3.2.4 8 | 9 | # Add regular dependencies here. 10 | dependencies: 11 | uuid: ^4.3.3 12 | path: ^1.8.0 13 | http: ^1.1.0 14 | ml_linalg: ^13.12.2 15 | path_provider: ^2.1.2 16 | 17 | dev_dependencies: 18 | lints: ^3.0.0 19 | test: ^1.24.0 20 | -------------------------------------------------------------------------------- /test/dvdb_test.dart: -------------------------------------------------------------------------------- 1 | import 'dart:typed_data'; 2 | 3 | import 'package:test/test.dart'; 4 | import 'dart:io'; 5 | import 'dart:convert'; 6 | import 'dart:core'; 7 | 8 | import 'package:dvdb/dvdb.dart'; 9 | 10 | void main() { 11 | group('Collection', () { 12 | late Collection collection; 13 | setUp(() { 14 | collection = Collection('test_collection'); 15 | }); 16 | 17 | test('addDocument adds a document', () { 18 | var document = Document(id: '1', text: 'Test', embedding: Float64List.fromList([1.0]), metadata: {}); 19 | collection.addDocument(document.id, document.text, document.embedding, metadata: document.metadata); 20 | 21 | expect(collection.documents.containsKey(document.id), isTrue); 22 | }); 23 | 24 | test('addDocuments adds multiple documents', () { 25 | var documents = [ 26 | Document(id: '1', text: 'Test 1', embedding: Float64List.fromList([1.0]), metadata: {}), 27 | Document(id: '2', text: 'Test 2', embedding: Float64List.fromList([2.0]), metadata: {}) 28 | ]; 29 | collection.addDocuments(documents); 30 | 31 | expect(collection.documents.length, equals(2)); 32 | }); 33 | 34 | test('removeDocument removes a document', () { 35 | var document = Document(id: '1', text: 'Test', embedding: Float64List.fromList([1.0]), metadata: {}); 36 | collection.addDocument(document.id, document.text, document.embedding, metadata: document.metadata); 37 | collection.removeDocument(document.id); 38 | 39 | expect(collection.documents.containsKey(document.id), isFalse); 40 | }); 41 | 42 | test('search returns correct results', () { 43 | // Setup: Adding some documents 44 | var documents = [ 45 | Document(id: '1', text: 'Dart programming', embedding: Float64List.fromList([1.0, 0.0]), metadata: {}), 46 | Document(id: '2', text: 'Flutter development', embedding: Float64List.fromList([0.0, 1.0]), metadata: {}), 47 | // Add more documents as needed 48 | ]; 49 | collection.addDocuments(documents); 50 | 51 | // Perform a search 52 | var query = Float64List.fromList([0.5, 0.5]); // Define a query that matches your test case 53 | var searchResults = collection.search(query); 54 | 55 | // Assert: Check if the search results are as expected 56 | // This will depend on how your search logic is implemented 57 | expect(searchResults, isNotEmpty); 58 | // Additional checks based on expected results 59 | }); 60 | 61 | test('load loads documents', () async { 62 | // Setup: Create a test file with predefined content 63 | var testFile = File('./test_collection.json'); 64 | await testFile.writeAsString('${jsonEncode({ 65 | 'id': '1', 66 | 'text': 'Test Document', 67 | 'embedding': [1.0, 2.0], 68 | 'metadata': {'key': 'value'} 69 | })}\n'); 70 | 71 | // Load documents 72 | collection.load(); 73 | 74 | // Assert: Check if documents are loaded correctly 75 | expect(collection.documents, isNotEmpty); 76 | expect(collection.documents.containsKey('1'), isTrue); 77 | 78 | // Clean up: Delete the test file 79 | await testFile.delete(); 80 | }); 81 | 82 | 83 | test('clear clears all documents', () { 84 | collection.clear(); 85 | expect(collection.documents.isEmpty, isTrue); 86 | }); 87 | }); 88 | } 89 | --------------------------------------------------------------------------------