本库是一款专为 MoonBit 生态量身定制的、纯 Wasm/JS/Native 兼容、零外部依赖的向量相似度检索与多维空间索引引擎(向量数据库)。针对大模型 RAG 及客户端嵌入式应用进行了优化,支持余弦相似度(Cosine Similarity)、欧氏距离(L2 Distance)、曼哈顿距离(L1 Distance)及点积(Dot Product)等核心度量,并实现了 Flat 线性检索、高
版权所有:中国计算机学会技术支持:开源发展技术委员会
京ICP备13000930号-9
京公网安备 11010802047560号
MoonVector Similarity Search Library (
MoonVector)A pure MoonBit, zero-dependency high-dimensional Vector Similarity Search and Indexing Engine (Vector Database). It is designed to support client-side and server-side retrieval (Wasm, JS, Native), making it ideal for modern LLM applications such as Retrieval-Augmented Generation (RAG), embedding similarity search, and semantic classification.
MoonVector implements multiple indexing algorithms (Flat, IVF-Flat, KD-Tree, LSH) alongside K-Means clustering, metadata filtering, and JSON serialization.
Features
Documentrecords to/from JSON.IndexStats) such as tree depths, centroid count, and document size.Installation
Add this package to your MoonBit dependencies:
Or manually declare it in your
moon.moddependencies:Repositories
Quick Start
1. Simple Flat Indexing and Similarity Search
2. High-Dimensional IVF-Flat Cluster Searching
3. Spatial Partitioning with KD-Trees
4. Approximate Cosine Search using LSH
5. Document JSON Serialization
API Reference
1. Distance Metrics
cosine_similarity(v1: Array[Double], v2: Array[Double]) -> Double raise VectorErroreuclidean_distance(v1: Array[Double], v2: Array[Double]) -> Double raise VectorErrormanhattan_distance(v1: Array[Double], v2: Array[Double]) -> Double raise VectorErrordot_product(v1: Array[Double], v2: Array[Double]) -> Double raise VectorError2. Unsupervised Clustering
kmeans(vectors: Array[Array[Double]], k: Int, max_iters: Int) -> Array[Array[Double]] raise VectorError3. Indexing Classes
FlatIndex::new() -> FlatIndexadd(self: FlatIndex, doc: Document) -> Unitsearch(self: FlatIndex, query: Array[Double], top_k: Int, metric: DistanceMetric, filters: Array[(String, String)]) -> Array[SearchResult] raise VectorErrorstats(self: FlatIndex) -> IndexStatsIvfIndex::new(k: Int, metric: DistanceMetric) -> IvfIndexbuild(self: IvfIndex, docs: Array[Document]) -> Unit raise VectorErrorsearch(self: IvfIndex, query: Array[Double], top_k: Int, nprobe: Int, filters: Array[(String, String)]) -> Array[SearchResult] raise VectorErrorstats(self: IvfIndex) -> IndexStatsKdTreeIndex::new(metric: DistanceMetric) -> KdTreeIndexbuild(self: KdTreeIndex, docs: Array[Document]) -> Unitsearch(self: KdTreeIndex, query: Array[Double], top_k: Int, filters: Array[(String, String)]) -> Array[SearchResult] raise VectorErrorstats(self: KdTreeIndex) -> IndexStatsLshIndex::new(num_planes: Int, dim: Int) -> LshIndexadd(self: LshIndex, doc: Document) -> Unit raise VectorErrorsearch(self: LshIndex, query: Array[Double], top_k: Int, filters: Array[(String, String)]) -> Array[SearchResult] raise VectorErrorData-quality and application helpers
validate_documents(docs)rejects empty corpora, blank/duplicate ids, empty vectors, and mixed dimensions before indexing.normalize_l2andnormalize_documentsprovide explicit embedding normalization without mutating the input arrays.VectorCollectionsupports validatedupsert,remove,replace_all,rebuild, exact search, and batch search for in-memory applications.search_batch,recall_at_k,mean_recall,evaluate_ivf, andevaluate_lshmake approximate-index evaluation reproducible.paginate_results,merge_results,diversify_results,inspect_corpus, andsummarize_workloadcover common service-layer and monitoring needs.Complete application workflows
The repository also includes reusable application-level paths rather than only isolated algorithms:
KnowledgeBasemanages validated upserts, deletes, revisions, exact search, approximate index fallback, batch requests, health reports, and tenant-safe metadata expressions.MetadataFilterandFilterExpressionsupport equality, inequality, prefix, substring, membership, AND, OR, and NOT policies.hybrid_searchcombines embedding similarity with text metadata overlap;compose_retrieval_contextproduces bounded RAG context with source ids and citations.run_rag_scenario,run_catalog_scenario, andrun_batch_scenarioare deterministic application fixtures covering multi-tenant retrieval, filtered recommendations, and batch workload telemetry.Testing
Run the full whitebox and blackbox test suite with:
The current local suite contains 21 tests covering metrics, clustering, all index types, JSON round-trips, filtering, malformed input, collection lifecycle, batch search, benchmark recall, multi-tenant RAG, catalog recommendation, and application-level retrieval policies. Expected output:
For the strict CI-equivalent check, run:
Reproducible benchmark
The repository includes a deterministic 48-document, 8-dimensional corpus and six query vectors in
benchmark.mbt. It is intentionally synthetic but is structured into four semantic topic bands so that cluster locality, metadata filtering, and approximate recall can be checked without downloading private or copyrighted data.The public helpers are
benchmark_corpus,benchmark_queries,evaluate_ivf, andevaluate_lsh. The test suite compares IVF and LSH against the exactFlatIndexbaseline using recall@k. This gives a repeatable quality signal rather than a claim based on a single hand-picked example.Boundary and data-quality behavior
VectorError::DimensionMismatch.validate_documentsand reported byinspect_corpus.top_k <= 0returns no results; requesting more results than available is safely truncated.Document::from_jsonrejects missing required fields; this lightweight serializer expects string values without embedded unescaped quotes.nprobeis bounded to the number of clusters. LSH is approximate and must be evaluated against Flat when a recall target matters.Application APIs
VectorCollectionprovides validated upsert/remove/replace/rebuild lifecycle operations for applications receiving documents over time.QueryPlanandrecommend_strategymake the choice between exact Flat, IVF, KD-Tree, and LSH explicit.ResultPage,merge_results,diversify_results, andSearchTelemetrysupport common service-layer concerns without coupling the library to a network framework.Original work and open-source compliance
MoonVector is an original MoonBit implementation. It is not a line-by-line port and has no vendored third-party source, generated source, private code, or external benchmark dataset. The repository depends only on MoonBit’s standard library and is released under Apache-2.0. The deterministic benchmark fixture is authored in
benchmark.mbt; it contains no personal or proprietary data.See
docs/ARCHITECTURE.mdfor package boundaries, algorithm trade-offs, correctness guarantees, and known limitations.OSC 2026 Submission Notes
cmd/main, whitebox and blackbox tests, docs, and package metadata are all present.moon check,moon fmt --deny-warnequivalent formatting enforcement,moon info --deny-warninterface generation, andmoon test.License
This project is licensed under the Apache 2.0 License - see the LICENSE file for details.