A lightweight, zero-dependency vector similarity search and index engine (Vector Database) in MoonBit.
moon add ywz1314/vectorimport {
"ywz1314/vector@0.1.3",
}import "ywz1314/vector" as @vector
fn main {
// Create a Flat index
let index = @vector.FlatIndex::new()
// Insert documents with 3-dimensional embeddings and tags
index.add(@vector.Document::new("doc_1", [1.0, 2.0, 3.0], [("category", "ml")]))
index.add(@vector.Document::new("doc_2", [4.0, 5.0, 6.0], [("category", "security")]))
// Search Top 2 nearest neighbors using L2 Euclidean Distance
let query = [1.2, 2.2, 3.2]
let results = index.search(query, 2, @vector.Euclidean, [])
for i = 0; i < results.length(); i = i + 1 {
println("Rank " + (i + 1).to_string() + ": " + results[i].id + ", Score: " + results[i].score.to_string())
}
}import "ywz1314/vector" as @vector
fn main {
// IVF Index with K=2 centroids evaluated under Cosine Metric
let index = @vector.IvfIndex::new(2, @vector.Cosine)
let docs = [
@vector.Document::new("doc_1", [1.0, 2.0, 3.0], [("category", "ml")]),
@vector.Document::new("doc_2", [1.5, 2.5, 3.5], [("category", "ml")]),
@vector.Document::new("doc_3", [5.0, 5.0, 5.0], [("category", "security")]),
]
// Build cluster index using K-Means
index.build(docs)
// Search the closest 1 cluster centroid (nprobe=1)
let query = [1.1, 2.1, 3.1]
let results = index.search(query, 2, 1, [])
}import "ywz1314/vector" as @vector
fn main {
let index = @vector.KdTreeIndex::new(@vector.Euclidean)
let docs = [
@vector.Document::new("doc_1", [1.0, 2.0], []),
@vector.Document::new("doc_2", [3.0, 4.0], []),
]
index.build(docs)
// Search nearest neighbor
let query = [1.1, 2.1]
let results = index.search(query, 1, [])
}import "ywz1314/vector" as @vector
fn main {
// Set up LSH index with 4 random projection planes for 3D vectors
let index = @vector.LshIndex::new(4, 3)
index.add(@vector.Document::new("doc_1", [1.0, 2.0, 3.0], []))
index.add(@vector.Document::new("doc_2", [-1.0, -2.0, -3.0], []))
// Retrieve candidate neighbors sharing the same projection hash
let query = [1.1, 2.1, 3.1]
let results = index.search(query, 1, [])
}import "ywz1314/vector" as @vector
fn main {
let doc = @vector.Document::new("doc_1", [1.25, -2.5], [("tag", "a")])
let json = doc.to_json()
println("JSON: " + json)
// Deserialization
let parsed = @vector.Document::from_json(json)
println("Parsed Document ID: " + parsed.id)
}moon testTotal tests: 21, passed: 21, failed: 0.moon fmt --check
moon check --deny-warn
moon test --deny-warn
moon build
moon info
git diff --exit-codepub suberror VectorError {
DimensionMismatch(String)
EmptyVector
InvalidK
ClusterError(String)
IndexError(String)
}impl Show for VectorErrorpub(all) struct BenchmarkReport {
queries : Int
corpus : Int
top_k : Int
recall : Double
index_name : String
}impl Show for BenchmarkReportpub(all) struct ContextChunk {
id : String
text : String
score : Double
metadata : Array[(String, String)]
}pub(all) enum FilterExpression {
MatchAll
MatchNone
AllOf(Array[MetadataFilter])
AnyOf(Array[MetadataFilter])
Not(MetadataFilter)
}pub(all) struct FilterReport {
total : Int
matched : Int
selectivity : Double
}impl Show for FilterReportfn FlatIndex::search(self : FlatIndex, query : Array[Double], top_k : Int, metric : DistanceMetric, filters : Array[(String, String)]) -> Array[SearchResult] raise VectorErrorfn FlatIndex::search_batch(self : FlatIndex, queries : Array[Array[Double]], top_k : Int, metric : DistanceMetric, filters : Array[(String, String)]) -> Array[Array[SearchResult]] raise VectorErrorpub(all) struct HealthReport {
healthy : Bool
document_count : Int
dimension : Int
duplicate_ids : Int
empty_ids : Int
dimension_errors : Int
message : String
}impl Show for HealthReportpub(all) struct IndexStats {
count : Int
dim : Int
extra_info : String
}impl Show for IndexStatspub(all) enum IndexStrategy {
ExactFlat
ClusteredIvf
SpatialKdTree
ApproximateLsh
}impl Show for IndexStrategyfn IvfIndex::search(self : IvfIndex, query : Array[Double], top_k : Int, nprobe : Int, filters : Array[(String, String)]) -> Array[SearchResult] raise VectorErrorfn IvfIndex::search_batch(self : IvfIndex, queries : Array[Array[Double]], top_k : Int, nprobe : Int, filters : Array[(String, String)]) -> Array[Array[SearchResult]] raise VectorErrorfn KdTreeIndex::search(self : KdTreeIndex, query : Array[Double], top_k : Int, filters : Array[(String, String)]) -> Array[SearchResult] raise VectorErrorpub struct KnowledgeBase {
collection : VectorCollection
ivf : IvfIndex?
lsh : LshIndex?
revision : Int
}fn KnowledgeBase::replace_all(self : KnowledgeBase, docs : Array[Document]) -> Unit raise VectorErrorfn KnowledgeBase::retrieve(self : KnowledgeBase, options : RetrievalOptions) -> RetrievalResponse raise VectorErrorfn KnowledgeBase::retrieve_batch(self : KnowledgeBase, requests : Array[RetrievalOptions]) -> Array[RetrievalResponse] raise VectorErrorfn KnowledgeBase::search_exact(self : KnowledgeBase, query : Array[Double], top_k : Int, metric : DistanceMetric, expression : FilterExpression) -> Array[SearchResult] raise VectorErrorfn LshIndex::search(self : LshIndex, query : Array[Double], top_k : Int, filters : Array[(String, String)]) -> Array[SearchResult] raise VectorErrorfn LshIndex::search_batch(self : LshIndex, queries : Array[Array[Double]], top_k : Int, filters : Array[(String, String)]) -> Array[Array[SearchResult]] raise VectorErrorpub(all) enum MetadataFilter {
MetadataEquals(String, String)
MetadataNotEquals(String, String)
MetadataPrefix(String, String)
MetadataContains(String, String)
MetadataIn(String, Array[String])
}pub(all) struct QueryPlan {
query : Array[Double]
top_k : Int
metric : DistanceMetric
filters : Array[(String, String)]
strategy : IndexStrategy
nprobe : Int
}fn QueryPlan::exact(query : Array[Double], top_k : Int, metric : DistanceMetric, filters : Array[(String, String)]) -> QueryPlanpub(all) struct ResultPage {
results : Array[SearchResult]
offset : Int
limit : Int
total : Int
has_more : Bool
}impl Show for ResultPagepub(all) struct RetrievalContext {
chunks : Array[ContextChunk]
text : String
source_ids : Array[String]
total_characters : Int
}impl Show for RetrievalContextpub(all) struct RetrievalOptions {
query : Array[Double]
top_k : Int
metric : DistanceMetric
filters : Array[(String, String)]
expression : FilterExpression
strategy : RetrievalStrategy
nprobe : Int
}pub(all) struct RetrievalResponse {
results : Array[SearchResult]
strategy : RetrievalStrategy
corpus_count : Int
candidate_count : Int
returned_count : Int
filter_description : String
}impl Show for RetrievalResponsepub(all) enum RetrievalStrategy {
RetrievalExact
RetrievalIvf
RetrievalKdTree
RetrievalLsh
}pub(all) struct ScenarioReport {
name : String
documents : Int
queries : Int
successful_queries : Int
average_recall : Double
context_sources : Int
passed : Bool
notes : String
}impl Show for ScenarioReportpub(all) struct SearchTelemetry {
queries : Int
returned : Int
filtered : Int
empty_queries : Int
average_results : Double
}impl Show for SearchTelemetryfn VectorCollection::replace_all(self : VectorCollection, docs : Array[Document]) -> Unit raise VectorErrorfn VectorCollection::search(self : VectorCollection, query : Array[Double], top_k : Int, metric : DistanceMetric, filters : Array[(String, String)]) -> Array[SearchResult] raise VectorErrorfn VectorCollection::search_batch(self : VectorCollection, queries : Array[Array[Double]], top_k : Int, metric : DistanceMetric, filters : Array[(String, String)]) -> Array[Array[SearchResult]] raise VectorErrorpub(all) struct VectorSummary {
count : Int
dimension : Int
min_norm : Double
max_norm : Double
mean_norm : Double
mean_vector : Array[Double]
}impl Show for VectorSummaryfn build_ivf_index(docs : Array[Document], k : Int, metric : DistanceMetric) -> IvfIndex raise VectorErrorfn build_kd_tree_index(docs : Array[Document], metric : DistanceMetric) -> KdTreeIndex raise VectorErrorfn build_rag_context(docs : Array[Document], query_vector : Array[Double], query_text : String, top_k : Int, semantic_weight : Double, character_budget : Int) -> RetrievalContext raise VectorErrorfn calculate_distance(v1 : Array[Double], v2 : Array[Double], metric : DistanceMetric) -> Double raise VectorErrorfn compose_retrieval_context(results : Array[SearchResult], docs : Array[Document], character_budget : Int, separator : String) -> RetrievalContextfn diversify_results(results : Array[SearchResult], metadata_key : String, per_value : Int) -> Array[SearchResult]fn evaluate_ivf(docs : Array[Document], queries : Array[Array[Double]], k : Int, nprobe : Int) -> BenchmarkReport raise VectorErrorfn evaluate_lsh(docs : Array[Document], queries : Array[Array[Double]], k : Int) -> BenchmarkReport raise VectorErrorfn filter_documents_expression(docs : Array[Document], expression : FilterExpression) -> Array[Document]fn filter_results_expression(results : Array[SearchResult], expression : FilterExpression) -> Array[SearchResult]fn filtered_recall(approximate : Array[SearchResult], exact : Array[SearchResult], k : Int) -> Doublefn hybrid_rerank(query_text : String, semantic_results : Array[SearchResult], docs : Array[Document], semantic_weight : Double) -> Array[SearchResult]fn hybrid_score(semantic_score : Double, lexical_score : Double, semantic_weight : Double) -> Doublefn hybrid_search(docs : Array[Document], query_vector : Array[Double], query_text : String, top_k : Int, semantic_weight : Double, filters : Array[(String, String)]) -> Array[SearchResult] raise VectorErrorfn kmeans(vectors : Array[Array[Double]], k : Int, max_iters : Int) -> Array[Array[Double]] raise VectorErrorfn matches_filter_expression(metadata : Array[(String, String)], expression : FilterExpression) -> Boolfn mean_average_precision(approximate : Array[Array[SearchResult]], exact : Array[Array[SearchResult]]) -> Doublefn mean_coverage(approximate : Array[Array[SearchResult]], exact : Array[Array[SearchResult]]) -> Doublefn mean_recall(approximate : Array[Array[SearchResult]], exact : Array[Array[SearchResult]], k : Int) -> Doublefn meets_recall_target(approximate : Array[Array[SearchResult]], exact : Array[Array[SearchResult]], k : Int, target : Double) -> Boolfn merge_results(lists : Array[Array[SearchResult]], metric : DistanceMetric) -> Array[SearchResult]fn nearest_distance(query : Array[Double], docs : Array[Document], metric : DistanceMetric) -> Double? raise VectorErrorfn pairwise_distances(vectors : Array[Array[Double]], metric : DistanceMetric) -> Array[Array[Double]] raise VectorErrorfn recall_curve(approximate : Array[SearchResult], exact : Array[SearchResult], cutoffs : Array[Int]) -> Array[(Int, Double)]fn retrieval_options(query : Array[Double], top_k : Int, metric : DistanceMetric) -> RetrievalOptionsfn retrieval_with_expression(options : RetrievalOptions, expression : FilterExpression) -> RetrievalOptionsfn retrieval_with_filters(options : RetrievalOptions, filters : Array[(String, String)]) -> RetrievalOptionsfn retrieval_with_strategy(options : RetrievalOptions, strategy : RetrievalStrategy, nprobe : Int) -> RetrievalOptionsfn retrieved_relevant_count(approximate : Array[SearchResult], relevant : Array[SearchResult]) -> Intfn run_retrieval_scenario(name : String, docs : Array[Document], queries : Array[Array[Double]], top_k : Int) -> ScenarioReport raise VectorErrorfn search_documents(docs : Array[Document], plan : QueryPlan) -> Array[SearchResult] raise VectorErrorfn search_with_threshold(docs : Array[Document], query : Array[Double], metric : DistanceMetric, threshold : Double) -> Array[SearchResult] raise VectorErrorfn summarize_workload(batches : Array[Array[SearchResult]], requested_top_k : Int) -> SearchTelemetryA lightweight, zero-dependency vector similarity search and index engine (Vector Database) in MoonBit.