@memberjunction/ai-vectors-memory 3.4.0 → 4.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,46 +1,55 @@
1
1
  # @memberjunction/ai-vectors-memory
2
2
 
3
- A powerful, production-ready in-memory vector similarity search and clustering service for MemberJunction. This package provides comprehensive vector operations including 6 distance metrics, 2 clustering algorithms, and extensive utility methods for business applications.
4
-
5
- ## Table of Contents
6
- - [Features](#features)
7
- - [Installation](#installation)
8
- - [Quick Start](#quick-start)
9
- - [Distance Metrics Guide](#distance-metrics-guide)
10
- - [Clustering Algorithms](#clustering-algorithms)
11
- - [Utility Methods](#utility-methods)
12
- - [Business Use Cases](#business-use-cases)
13
- - [API Reference](#api-reference)
14
- - [Performance](#performance)
15
- - [Best Practices](#best-practices)
16
-
17
- ## Features
18
-
19
- ### 🎯 Core Capabilities
20
- - **In-memory vector storage** with O(1) lookups
21
- - **6 distance/similarity metrics** (all normalized to 0-1 range)
22
- - **K-nearest neighbor search** with threshold filtering
23
- - **Metadata pre-filtering** for efficient scoped searches
24
- - **Dimension validation** to ensure vector consistency
25
- - **Generic TypeScript support** for metadata typing
26
-
27
- ### 📊 Distance Metrics
28
- - **Cosine Similarity** - Semantic similarity, text embeddings
29
- - **Euclidean Distance** - Physical measurements, specifications
30
- - **Manhattan Distance** - Grid navigation, robust to outliers
31
- - **Dot Product** - Recommendations with magnitude
32
- - **Jaccard Similarity** - Set comparisons, categorical data
33
- - **Hamming Distance** - Error detection, configuration drift
34
-
35
- ### 🔬 Clustering Algorithms
36
- - **K-Means with K-Means++** - Fast, spherical clusters
37
- - **DBSCAN** - Density-based, automatic outlier detection
38
-
39
- ### 🛠️ Utility Methods
40
- - **Silhouette Score** - Evaluate clustering quality
41
- - **Elbow Method** - Find optimal number of clusters
42
- - **Centroid Calculation** - Find cluster centers
43
- - **Within/Between Cluster Distance** - Measure cluster quality
3
+ An in-memory vector similarity search and clustering service for MemberJunction. Provides six distance metrics, two clustering algorithms (K-Means and DBSCAN), and comprehensive utility methods for vector analysis -- all without requiring an external vector database.
4
+
5
+ ## Architecture
6
+
7
+ ```mermaid
8
+ graph TD
9
+ subgraph MemoryPkg["@memberjunction/ai-vectors-memory"]
10
+ SVS["SimpleVectorService<TMetadata>"]
11
+
12
+ subgraph Search["Similarity Search"]
13
+ FN["FindNearest"]
14
+ FS["FindSimilar"]
15
+ FAT["FindAboveThreshold"]
16
+ end
17
+
18
+ subgraph Metrics["Distance Metrics"]
19
+ COS["Cosine"]
20
+ EUC["Euclidean"]
21
+ MAN["Manhattan"]
22
+ DOT["Dot Product"]
23
+ JAC["Jaccard"]
24
+ HAM["Hamming"]
25
+ end
26
+
27
+ subgraph Clustering["Clustering"]
28
+ KM["K-Means (K-Means++)"]
29
+ DBS["DBSCAN"]
30
+ EM["Elbow Method"]
31
+ end
32
+
33
+ subgraph Evaluation["Evaluation"]
34
+ SIL["Silhouette Score"]
35
+ WCD["Within-Cluster Distance"]
36
+ BCD["Between-Cluster Distance"]
37
+ CENT["Find Centroid"]
38
+ end
39
+ end
40
+
41
+ FN --> Metrics
42
+ FS --> FN
43
+ FAT --> FN
44
+ KM --> Metrics
45
+ DBS --> FN
46
+
47
+ style MemoryPkg fill:#2d6a9f,stroke:#1a4971,color:#fff
48
+ style Search fill:#2d8659,stroke:#1a5c3a,color:#fff
49
+ style Metrics fill:#b8762f,stroke:#8a5722,color:#fff
50
+ style Clustering fill:#7c5295,stroke:#563a6b,color:#fff
51
+ style Evaluation fill:#2d8659,stroke:#1a5c3a,color:#fff
52
+ ```
44
53
 
45
54
  ## Installation
46
55
 
@@ -48,721 +57,296 @@ A powerful, production-ready in-memory vector similarity search and clustering s
48
57
  npm install @memberjunction/ai-vectors-memory
49
58
  ```
50
59
 
51
- ## Quick Start
52
-
53
- ```typescript
54
- import { SimpleVectorService, VectorEntry } from '@memberjunction/ai-vectors-memory';
60
+ ## Overview
55
61
 
56
- // Create service instance
57
- const service = new SimpleVectorService();
58
-
59
- // Load vectors with metadata
60
- const vectors: VectorEntry[] = [
61
- { key: 'doc1', vector: [0.1, 0.2, 0.3], metadata: { title: 'Document 1' } },
62
- { key: 'doc2', vector: [0.4, 0.5, 0.6], metadata: { title: 'Document 2' } },
63
- { key: 'doc3', vector: [0.7, 0.8, 0.9], metadata: { title: 'Document 3' } }
64
- ];
65
- service.LoadVectors(vectors);
66
-
67
- // Find similar vectors
68
- const queryVector = [0.15, 0.25, 0.35];
69
- const results = service.FindNearest(queryVector, 2);
70
-
71
- results.forEach(result => {
72
- console.log(`${result.key}: similarity=${result.score.toFixed(3)}`);
73
- });
74
- ```
62
+ Unlike the other vector packages that depend on external vector databases (Pinecone, etc.), this package operates entirely in-memory. It is ideal for:
75
63
 
76
- ## Metadata Filtering
64
+ - Lightweight similarity search without infrastructure overhead
65
+ - AI agent note retrieval and session memory
66
+ - Clustering analysis and data exploration
67
+ - Prototyping and testing before deploying to a full vector database
68
+ - Scenarios where the vector count fits comfortably in memory (tens of thousands)
77
69
 
78
- All search methods support optional metadata filtering for efficient scoped searches. Filtering happens **before** similarity calculation, making it 10-20x faster than post-search filtering.
70
+ The `SimpleVectorService` class is generic (`SimpleVectorService<TMetadata>`) for type-safe metadata access.
79
71
 
80
- ### Basic Filtering
72
+ ## Quick Start
81
73
 
82
74
  ```typescript
83
- interface DocumentMetadata {
84
- category: string;
85
- author: string;
86
- status: 'active' | 'archived';
87
- }
75
+ import { SimpleVectorService, VectorEntry } from '@memberjunction/ai-vectors-memory';
88
76
 
89
- const service = new SimpleVectorService<DocumentMetadata>();
77
+ const service = new SimpleVectorService();
90
78
 
91
- // Find similar documents filtered by category
92
- const results = service.FindNearest(
93
- queryVector,
94
- 5,
95
- 0.7,
96
- 'cosine',
97
- (metadata) => metadata.category === 'Technology'
98
- );
79
+ // Load vectors
80
+ service.LoadVectors([
81
+ { key: 'doc1', vector: [0.1, 0.2, 0.3], metadata: { title: 'Document 1' } },
82
+ { key: 'doc2', vector: [0.4, 0.5, 0.6], metadata: { title: 'Document 2' } },
83
+ { key: 'doc3', vector: [0.7, 0.8, 0.9], metadata: { title: 'Document 3' } }
84
+ ]);
99
85
 
100
- // Find similar documents by multiple criteria
101
- const filtered = service.FindNearest(
102
- queryVector,
103
- 10,
104
- 0.5,
105
- 'cosine',
106
- (metadata) =>
107
- metadata.status === 'active' &&
108
- metadata.author === 'John Doe'
109
- );
86
+ // Find nearest neighbors
87
+ const results = service.FindNearest([0.15, 0.25, 0.35], 2);
88
+ results.forEach(r => console.log(`${r.key}: ${r.score.toFixed(3)}`));
110
89
  ```
111
90
 
112
- ### Advanced Filtering
113
-
114
- ```typescript
115
- // Complex filtering logic
116
- const results = service.FindNearest(
117
- queryVector,
118
- 10,
119
- 0.6,
120
- 'cosine',
121
- (metadata) => {
122
- // Multi-condition filtering
123
- if (metadata.category === 'Premium') return true;
124
- if (metadata.views > 1000 && metadata.rating >= 4.5) return true;
125
- return false;
126
- }
127
- );
128
-
129
- // FindSimilar also supports filtering
130
- const similar = service.FindSimilar(
131
- 'doc123',
132
- 5,
133
- 0.7,
134
- 'cosine',
135
- (metadata) => metadata.language === 'en'
136
- );
137
-
138
- // FindAboveThreshold with filtering
139
- const matches = service.FindAboveThreshold(
140
- queryVector,
141
- 0.8,
142
- 'cosine',
143
- (metadata) => metadata.verified === true
144
- );
145
-
146
- // DBSCAN clustering with pre-filtering
147
- const clusters = service.DBSCANCluster(
148
- 0.3,
149
- 3,
150
- 'euclidean',
151
- (metadata) => metadata.active === true
152
- );
91
+ ## Core Types
92
+
93
+ ```mermaid
94
+ classDiagram
95
+ class SimpleVectorService~TMetadata~ {
96
+ +LoadVectors(entries) void
97
+ +AddVector(key, vector, metadata?) void
98
+ +AddOrUpdateVector(key, vector, metadata?) boolean
99
+ +UpdateVector(key, updates) boolean
100
+ +FindNearest(query, topK, threshold?, metric?, filter?) VectorSearchResult[]
101
+ +FindSimilar(key, topK, threshold?, metric?, filter?) VectorSearchResult[]
102
+ +FindAboveThreshold(query, threshold, metric?, filter?) VectorSearchResult[]
103
+ +Similarity(key1, key2) number
104
+ +CalculateDistance(a, b, metric?) number
105
+ +KMeansCluster(k, maxIter?, metric?, tolerance?) ClusterResult
106
+ +DBSCANCluster(epsilon, minPoints, metric?, filter?) ClusterResult
107
+ +ElbowMethod(minK, maxK, metric?) Map
108
+ +SilhouetteScore(result, metric?) number
109
+ +WithinClusterDistance(result, metric?) number
110
+ +BetweenClusterDistance(result, metric?) number
111
+ +FindCentroid(vectors) number[]
112
+ +Size : number
113
+ +ExpectedDimensions : number
114
+ +GetVector(key) number[]
115
+ +GetMetadata(key) TMetadata
116
+ +RemoveVector(key) boolean
117
+ +ExportVectors() VectorEntry[]
118
+ +Clear() void
119
+ +Has(key) boolean
120
+ +GetAllKeys() string[]
121
+ }
122
+
123
+ class VectorEntry~TMetadata~ {
124
+ +key : string
125
+ +vector : number[]
126
+ +metadata? : TMetadata
127
+ }
128
+
129
+ class VectorSearchResult~TMetadata~ {
130
+ +key : string
131
+ +score : number
132
+ +metadata? : TMetadata
133
+ }
134
+
135
+ class ClusterResult~TMetadata~ {
136
+ +clusters : Map~number, string[]~
137
+ +centroids? : Map~number, number[]~
138
+ +outliers? : string[]
139
+ +metadata? : ClusterMetadata
140
+ }
141
+
142
+ SimpleVectorService --> VectorEntry : stores
143
+ SimpleVectorService --> VectorSearchResult : returns
144
+ SimpleVectorService --> ClusterResult : returns
145
+
146
+ style SimpleVectorService fill:#2d6a9f,stroke:#1a4971,color:#fff
147
+ style VectorEntry fill:#2d8659,stroke:#1a5c3a,color:#fff
148
+ style VectorSearchResult fill:#2d8659,stroke:#1a5c3a,color:#fff
149
+ style ClusterResult fill:#7c5295,stroke:#563a6b,color:#fff
153
150
  ```
154
151
 
155
- ### Performance Benefits
152
+ ### DistanceMetric Type
156
153
 
157
154
  ```typescript
158
- // ❌ OLD WAY: Search 3x wider then filter (inefficient)
159
- const wideResults = service.FindNearest(queryVector, topK * 3);
160
- const filtered = wideResults
161
- .filter(r => r.metadata.agentId === 'agent-123')
162
- .slice(0, topK);
163
-
164
- // ✅ NEW WAY: Filter before similarity calculation (10-20x faster!)
165
- const filtered = service.FindNearest(
166
- queryVector,
167
- topK,
168
- undefined,
169
- 'cosine',
170
- (metadata) => metadata.agentId === 'agent-123'
171
- );
155
+ type DistanceMetric = 'cosine' | 'euclidean' | 'manhattan' | 'dotproduct' | 'jaccard' | 'hamming';
172
156
  ```
173
157
 
174
- **Why it's faster:**
175
- - For 1000 vectors with filter matching 50 items:
176
- - **Old way**: Calculate similarity for 1000 vectors, filter to 50, return topK
177
- - **New way**: Filter to 50 vectors (fast), calculate similarity for 50, return topK
178
- - **Speedup**: ~20x (similarity calculation is expensive vs metadata checks)
158
+ ## Distance Metrics
179
159
 
180
- ## Distance Metrics Guide
160
+ All metrics are normalized to a 0-1 range where **1 = most similar**.
181
161
 
182
- All metrics are normalized to 0-1 range where 1 = most similar/closest.
162
+ | Metric | Best For | Formula |
163
+ |---|---|---|
164
+ | `cosine` (default) | Text embeddings, semantic search | `(dot(A,B) / (norm(A) * norm(B)) + 1) / 2` |
165
+ | `euclidean` | Physical measurements, specs | `1 / (1 + sqrt(sum((a-b)^2)))` |
166
+ | `manhattan` | Grid navigation, time series | `1 / (1 + sum(abs(a-b)))` |
167
+ | `dotproduct` | Recommendations, weighted scoring | `(tanh(dot(A,B) / sqrt(n)) + 1) / 2` |
168
+ | `jaccard` | Categorical/binary data, set comparison | `intersection / union` |
169
+ | `hamming` | Configuration drift, error detection | `1 - (differences / length)` |
183
170
 
184
- ### Cosine Similarity (Default)
171
+ ## Similarity Search
185
172
 
186
- **Best for:** Text embeddings, semantic search, document similarity
173
+ ### FindNearest
187
174
 
188
- ```typescript
189
- // Find semantically similar documents
190
- const similar = service.FindNearest(docEmbedding, 5, undefined, 'cosine');
191
-
192
- // Filter by minimum similarity (0.8 = 80% similar)
193
- const highSimilarity = service.FindNearest(docEmbedding, 10, 0.8, 'cosine');
194
- ```
195
-
196
- **When to use:**
197
- - ✅ Text embeddings from LLMs
198
- - ✅ Document/content similarity
199
- - ✅ When magnitude doesn't matter
200
- - ❌ Physical measurements
201
-
202
- ### Euclidean Distance
203
-
204
- **Best for:** Physical measurements, product specifications, geographic data
175
+ K-nearest neighbor search with optional threshold and metadata pre-filtering.
205
176
 
206
177
  ```typescript
207
- // Find products with similar specifications
208
- const productFeatures = [size, weight, price, rating];
209
- const similar = service.FindNearest(productFeatures, 5, undefined, 'euclidean');
210
-
211
- // Find stores within distance threshold
212
- const nearbyStores = service.FindAboveThreshold(location, 0.7, 'euclidean');
178
+ const results = service.FindNearest(
179
+ queryVector, // vector to search for
180
+ 10, // topK results
181
+ 0.7, // minimum similarity threshold
182
+ 'cosine', // distance metric
183
+ (meta) => meta.status === 'active' // pre-filter by metadata
184
+ );
213
185
  ```
214
186
 
215
- **When to use:**
216
- - ✅ Physical dimensions (size, weight, distance)
217
- - ✅ Continuous numeric features
218
- - ✅ Quality control measurements
219
- - ❌ High-dimensional sparse data
187
+ Pre-filtering happens **before** similarity calculation, making filtered searches significantly faster than post-filtering.
220
188
 
221
- ### Manhattan Distance
189
+ ### FindSimilar
222
190
 
223
- **Best for:** Grid systems, warehouse navigation, time series
191
+ Find vectors similar to an existing stored vector (excludes the source vector from results).
224
192
 
225
193
  ```typescript
226
- // Warehouse picking optimization
227
- const currentLocation = [aisle, shelf, bin];
228
- const nearestItems = service.FindNearest(currentLocation, 10, undefined, 'manhattan');
229
-
230
- // Time series comparison (robust to outliers)
231
- const trendSimilarity = service.FindSimilar('trend1', 5, undefined, 'manhattan');
194
+ const similar = service.FindSimilar('doc-123', 5, 0.8, 'cosine');
232
195
  ```
233
196
 
234
- **When to use:**
235
- - ✅ Grid-based movement (warehouses, city blocks)
236
- - ✅ When outliers should have linear impact
237
- - ✅ Each dimension is independent
238
- - ❌ Smooth gradients needed
239
-
240
- ### Dot Product
197
+ ### FindAboveThreshold
241
198
 
242
- **Best for:** Recommendation systems, weighted scoring, revenue analysis
199
+ Return all vectors above a similarity threshold (no topK limit).
243
200
 
244
201
  ```typescript
245
- // Product recommendations with popularity weighting
246
- const userPreferences = [0.8, 0.2, 0.5, 0.9]; // Interest levels
247
- const recommendations = service.FindNearest(userPreferences, 10, undefined, 'dotproduct');
248
-
249
- // Revenue impact analysis (quantity × price)
250
- const revenueVector = quantities.map((q, i) => q * prices[i]);
251
- const similar = service.FindSimilar('product1', 5, undefined, 'dotproduct');
202
+ const matches = service.FindAboveThreshold(queryVector, 0.9, 'cosine');
252
203
  ```
253
204
 
254
- **When to use:**
255
- - ✅ Magnitude matters (popularity, importance)
256
- - ✅ Weighted feature comparisons
257
- - ✅ Collaborative filtering
258
- - ❌ Vectors with different scales
259
-
260
- ### Jaccard Similarity
261
-
262
- **Best for:** Set comparisons, customer behavior, categorical data
205
+ ## Vector Management
263
206
 
264
207
  ```typescript
265
- // Customer purchase patterns (1 = purchased, 0 = not purchased)
266
- const customerPurchases = [1, 0, 1, 1, 0, 1, 0, 0];
267
- const similarCustomers = service.FindNearest(customerPurchases, 10, undefined, 'jaccard');
268
-
269
- // Document keyword comparison
270
- const docKeywords = [1, 1, 0, 1, 0]; // Presence/absence of keywords
271
- const similar = service.FindAboveThreshold(docKeywords, 0.5, 'jaccard');
272
- ```
208
+ // Add individual vectors
209
+ service.AddVector('key1', [0.1, 0.2, 0.3], { category: 'A' });
273
210
 
274
- **When to use:**
275
- - ✅ Binary/categorical data
276
- - ✅ Set membership comparisons
277
- - ✅ Sparse vectors (many zeros)
278
- - ❌ Continuous numeric features
211
+ // Add or update (upsert)
212
+ const wasUpdate = service.AddOrUpdateVector('key1', [0.4, 0.5, 0.6]);
279
213
 
280
- ### Hamming Distance
214
+ // Update in place (vector, metadata, or both)
215
+ service.UpdateVector('key1', { metadata: { category: 'B' } });
281
216
 
282
- **Best for:** Error detection, configuration management, A/B testing
217
+ // Remove
218
+ service.RemoveVector('key1');
283
219
 
284
- ```typescript
285
- // Configuration drift detection
286
- const currentConfig = [1, 2, 3, 1, 2, 3];
287
- const configs = service.FindNearest(currentConfig, 5, undefined, 'hamming');
220
+ // Bulk load from array or Map
221
+ service.LoadVectors(new Map([['k1', [1, 2, 3]], ['k2', [4, 5, 6]]]));
288
222
 
289
- // A/B test variant comparison
290
- const variantA = [1, 0, 1, 1, 0]; // Feature flags
291
- const similar = service.FindSimilar('variantA', 3, undefined, 'hamming');
223
+ // Export for persistence
224
+ const allVectors = service.ExportVectors();
292
225
  ```
293
226
 
294
- **When to use:**
295
- - ✅ Categorical data comparison
296
- - ✅ Error detection
297
- - ✅ Fixed-length codes
298
- - ❌ Continuous values
227
+ Dimension validation is automatic -- all vectors must have the same dimensionality.
299
228
 
300
229
  ## Clustering Algorithms
301
230
 
302
- ### K-Means Clustering
231
+ ### K-Means (with K-Means++ Initialization)
303
232
 
304
- Fast algorithm for finding K spherical clusters.
233
+ Partitions vectors into K clusters by minimizing within-cluster variance.
305
234
 
306
235
  ```typescript
307
- // Basic K-Means clustering
308
- const result = service.KMeansCluster(
309
- 3, // k: number of clusters
310
- 100, // maxIterations
311
- 'euclidean', // metric
312
- 0.0001 // convergence tolerance
313
- );
236
+ const result = service.KMeansCluster(3, 100, 'euclidean', 0.0001);
314
237
 
315
- // Access results
316
238
  result.clusters.forEach((members, clusterId) => {
317
- console.log(`Cluster ${clusterId}: ${members.length} members`);
318
- const centroid = result.centroids.get(clusterId);
319
- console.log(`Centroid: ${centroid}`);
239
+ const centroid = result.centroids.get(clusterId);
240
+ console.log(`Cluster ${clusterId}: ${members.length} members`);
320
241
  });
321
242
 
322
- // Evaluate clustering quality
323
- console.log(`Silhouette Score: ${result.metadata.silhouetteScore}`);
243
+ console.log(`Silhouette: ${result.metadata.silhouetteScore.toFixed(3)}`);
324
244
  console.log(`Converged in ${result.metadata.iterations} iterations`);
325
245
  ```
326
246
 
327
- #### Finding Optimal K with Elbow Method
247
+ ### DBSCAN
328
248
 
329
- ```typescript
330
- // Test different k values
331
- const elbowData = service.ElbowMethod(2, 10, 'euclidean');
332
-
333
- // Plot or analyze the results
334
- elbowData.forEach((inertia, k) => {
335
- console.log(`k=${k}: inertia=${inertia.toFixed(2)}`);
336
- });
337
- // Look for the "elbow" where inertia stops decreasing rapidly
338
- ```
339
-
340
- ### DBSCAN Clustering
341
-
342
- Density-based clustering that automatically finds clusters and outliers.
249
+ Density-based clustering that automatically determines the number of clusters and identifies outliers.
343
250
 
344
251
  ```typescript
345
- // DBSCAN with outlier detection
346
252
  const result = service.DBSCANCluster(
347
- 0.15, // epsilon: max distance for neighbors (1-similarity)
348
- 3, // minPoints: minimum cluster size
349
- 'euclidean' // metric
253
+ 0.3, // epsilon (max distance for neighbors)
254
+ 3, // minPoints (minimum cluster density)
255
+ 'euclidean', // metric
256
+ (meta) => meta.active // optional pre-filter
350
257
  );
351
258
 
352
- // Process clusters
353
- result.clusters.forEach((members, clusterId) => {
354
- console.log(`Cluster ${clusterId}: ${members.length} members`);
355
- });
356
-
357
- // Handle outliers
358
- if (result.outliers && result.outliers.length > 0) {
359
- console.log(`Found ${result.outliers.length} outliers:`);
360
- result.outliers.forEach(key => {
361
- console.log(` - ${key}`);
362
- });
363
- }
364
- ```
365
-
366
- ## Utility Methods
367
-
368
- ### Evaluate Clustering Quality
369
-
370
- ```typescript
371
- // After clustering, evaluate the results
372
- const clusterResult = service.KMeansCluster(3);
373
-
374
- // 1. Silhouette Score (-1 to 1, higher is better)
375
- const silhouette = service.SilhouetteScore(clusterResult, 'euclidean');
376
- console.log(`Silhouette: ${silhouette.toFixed(3)}`);
377
- // > 0.7: Strong structure
378
- // 0.5-0.7: Reasonable structure
379
- // < 0.5: Weak structure
380
-
381
- // 2. Within-cluster distance (lower is better)
382
- const cohesion = service.WithinClusterDistance(clusterResult, 'euclidean');
383
- console.log(`Cohesion: ${cohesion.toFixed(3)}`);
384
-
385
- // 3. Between-cluster distance (higher is better)
386
- const separation = service.BetweenClusterDistance(clusterResult, 'euclidean');
387
- console.log(`Separation: ${separation.toFixed(3)}`);
388
- ```
389
-
390
- ### Find Centroids
391
-
392
- ```typescript
393
- // Calculate centroid of a vector group
394
- const vectors = [
395
- [1, 2, 3],
396
- [4, 5, 6],
397
- [7, 8, 9]
398
- ];
399
- const centroid = service.FindCentroid(vectors);
400
- console.log(`Centroid: ${centroid}`); // [4, 5, 6]
401
- ```
402
-
403
- ## Business Use Cases
404
-
405
- ### Customer Segmentation
406
-
407
- ```typescript
408
- // Load customer feature vectors
409
- const customers: VectorEntry[] = [
410
- {
411
- key: 'customer1',
412
- vector: [purchaseFreq, avgOrderValue, recency, categories],
413
- metadata: { name: 'John Doe', tier: 'Gold' }
414
- },
415
- // ... more customers
416
- ];
417
- service.LoadVectors(customers);
418
-
419
- // Segment customers into groups
420
- const segments = service.KMeansCluster(5, 100, 'euclidean');
421
-
422
- // Analyze each segment
423
- segments.clusters.forEach((members, segmentId) => {
424
- const centroid = segments.centroids.get(segmentId);
425
- console.log(`\nSegment ${segmentId}:`);
426
- console.log(` Size: ${members.length} customers`);
427
- console.log(` Avg Purchase Freq: ${centroid[0].toFixed(2)}`);
428
- console.log(` Avg Order Value: ${centroid[1].toFixed(2)}`);
429
- });
430
- ```
431
-
432
- ### Product Recommendations
433
-
434
- ```typescript
435
- // Using dot product for popularity-weighted recommendations
436
- const userInterests = [0.9, 0.3, 0.7, 0.1, 0.8]; // Interest in categories
437
-
438
- // Find products that match interests AND are popular
439
- const recommendations = service.FindNearest(
440
- userInterests,
441
- 10,
442
- 0.6, // Minimum similarity threshold
443
- 'dotproduct' // Considers both direction and magnitude
444
- );
445
-
446
- recommendations.forEach(rec => {
447
- const product = rec.metadata;
448
- console.log(`${product.name}: ${(rec.score * 100).toFixed(1)}% match`);
449
- });
450
- ```
451
-
452
- ### Anomaly Detection
453
-
454
- ```typescript
455
- // Using DBSCAN to find outliers in transaction data
456
- const transactions: VectorEntry[] = transactionData.map(t => ({
457
- key: t.id,
458
- vector: [t.amount, t.frequency, t.timeOfDay, t.merchantCategory],
459
- metadata: t
460
- }));
461
-
462
- service.LoadVectors(transactions);
463
-
464
- // Find anomalies
465
- const result = service.DBSCANCluster(0.1, 5, 'euclidean');
466
-
467
- // Process outliers as potential fraud
468
- if (result.outliers) {
469
- result.outliers.forEach(transactionId => {
470
- const transaction = service.GetMetadata(transactionId);
471
- console.log(`Potential fraud: Transaction ${transactionId}`);
472
- // Send for review
473
- });
474
- }
259
+ console.log(`Found ${result.clusters.size} clusters`);
260
+ console.log(`Outliers: ${result.outliers?.length ?? 0}`);
475
261
  ```
476
262
 
477
- ### Content Similarity
478
-
479
- ```typescript
480
- // Find similar documents using cosine similarity
481
- const docEmbedding = await generateEmbedding(documentText);
482
-
483
- // Find related content
484
- const similar = service.FindNearest(docEmbedding, 5, 0.7, 'cosine');
485
-
486
- // Build recommendation list
487
- const recommendations = similar.map(result => ({
488
- title: result.metadata.title,
489
- similarity: `${(result.score * 100).toFixed(1)}%`,
490
- url: result.metadata.url
491
- }));
492
- ```
263
+ ### Elbow Method
493
264
 
494
- ### Quality Control
265
+ Find the optimal number of clusters by testing a range of K values.
495
266
 
496
267
  ```typescript
497
- // Monitor product specifications
498
- const targetSpecs = [10.0, 5.5, 3.2, 98.5]; // Target measurements
499
-
500
- // Find products deviating from spec
501
- const allProducts = service.FindAboveThreshold(targetSpecs, 0, 'euclidean');
502
-
503
- // Sort by distance from target (ascending)
504
- const deviations = allProducts
505
- .sort((a, b) => a.score - b.score)
506
- .slice(0, 10);
507
-
508
- deviations.forEach(product => {
509
- const deviation = (1 - product.score) * 100;
510
- console.log(`${product.key}: ${deviation.toFixed(2)}% deviation`);
268
+ const elbowData = service.ElbowMethod(2, 10, 'euclidean');
269
+ elbowData.forEach((inertia, k) => {
270
+ console.log(`k=${k}: inertia=${inertia.toFixed(2)}`);
511
271
  });
512
272
  ```
513
273
 
514
- ## API Reference
515
-
516
- ### Core Methods
517
-
518
- #### `LoadVectors(entries: VectorEntry[] | Map<string, number[]>)`
519
- Load vectors into the service.
520
-
521
- #### `AddVector(key: string, vector: number[], metadata?: TMetadata)`
522
- Add or update a single vector.
523
-
524
- #### `FindNearest(queryVector: number[], topK: number, threshold?: number, metric?: DistanceMetric, filter?: (metadata: TMetadata) => boolean)`
525
- Find K nearest neighbors to a query vector. Optional filter applies before similarity calculation for efficient scoped searches.
526
-
527
- #### `FindSimilar(key: string, topK: number, threshold?: number, metric?: DistanceMetric, filter?: (metadata: TMetadata) => boolean)`
528
- Find vectors similar to an existing vector. Optional filter applies before similarity calculation.
529
-
530
- #### `FindAboveThreshold(queryVector: number[], threshold: number, metric?: DistanceMetric, filter?: (metadata: TMetadata) => boolean)`
531
- Find all vectors above a similarity threshold. Optional filter applies before similarity calculation.
532
-
533
- ### Clustering Methods
534
-
535
- #### `KMeansCluster(k: number, maxIterations?: number, metric?: DistanceMetric, tolerance?: number)`
536
- Perform K-Means clustering.
537
-
538
- #### `DBSCANCluster(epsilon: number, minPoints: number, metric?: DistanceMetric, filter?: (metadata: TMetadata) => boolean)`
539
- Perform DBSCAN clustering. Optional filter applies to pre-filter the vector space before clustering.
540
-
541
- #### `ElbowMethod(minK: number, maxK: number, metric?: DistanceMetric)`
542
- Find optimal K using elbow method.
543
-
544
- ### Utility Methods
545
-
546
- #### `SilhouetteScore(clusterResult: ClusterResult, metric?: DistanceMetric)`
547
- Calculate silhouette score for clustering quality.
548
-
549
- #### `WithinClusterDistance(clusterResult: ClusterResult, metric?: DistanceMetric)`
550
- Calculate average within-cluster distance.
551
-
552
- #### `BetweenClusterDistance(clusterResult: ClusterResult, metric?: DistanceMetric)`
553
- Calculate average between-cluster distance.
554
-
555
- #### `FindCentroid(vectors: number[][])`
556
- Calculate the centroid of a vector set.
557
-
558
- ### Helper Methods
559
-
560
- #### `Similarity(key1: string, key2: string)`
561
- Calculate similarity between two stored vectors.
562
-
563
- #### `GetVector(key: string)`
564
- Retrieve a vector by key.
565
-
566
- #### `GetMetadata(key: string)`
567
- Retrieve metadata for a vector.
568
-
569
- #### `RemoveVector(key: string)`
570
- Remove a vector from the service.
571
-
572
- #### `Clear()`
573
- Remove all vectors.
574
-
575
- #### `Size`
576
- Get the number of vectors stored.
577
-
578
- #### `ExpectedDimensions`
579
- Get the expected vector dimensions.
580
-
581
- ## Performance
582
-
583
- ### Benchmarks
584
-
585
- Based on testing with 1000 vectors of 128 dimensions:
586
-
587
- | Operation | Time | Notes |
588
- |-----------|------|-------|
589
- | Load 1000 vectors | < 5ms | One-time operation |
590
- | FindNearest (k=10) | ~1ms | All metrics similar |
591
- | K-Means (k=5) | ~70ms | Includes convergence |
592
- | DBSCAN | ~80ms | Includes neighborhood calc |
593
- | Silhouette Score | ~15ms | For 5 clusters |
594
-
595
- ### Memory Usage
596
-
597
- Approximate memory usage:
598
- - Base overhead: ~1KB
599
- - Per vector: 8 bytes × dimensions + ~100 bytes overhead
600
- - Example: 10,000 vectors × 384 dimensions ≈ 31MB
601
-
602
- ### Optimization Tips
603
-
604
- 1. **Batch Operations**: Load vectors in bulk rather than one at a time
605
- 2. **Metric Selection**: Cosine is fastest for normalized vectors
606
- 3. **Threshold Filtering**: Use thresholds to reduce result set size
607
- 4. **Dimension Reduction**: Consider PCA/UMAP for very high dimensions
608
- 5. **Clustering**: Start with small K for ElbowMethod, increase gradually
274
+ ## Clustering Evaluation
609
275
 
610
- ## Best Practices
276
+ ```mermaid
277
+ graph LR
278
+ CR["ClusterResult"] --> SIL["SilhouetteScore<br/>-1 to 1<br/>(higher = better)"]
279
+ CR --> WCD["WithinClusterDistance<br/>0 to 1<br/>(lower = tighter)"]
280
+ CR --> BCD["BetweenClusterDistance<br/>0 to 1<br/>(higher = more separated)"]
281
+ CR --> CENT["FindCentroid<br/>mean vector"]
611
282
 
612
- ### 1. Choose the Right Metric
613
-
614
- ```typescript
615
- // Text/semantic similarity
616
- const textResults = service.FindNearest(embedding, 10, 0.7, 'cosine');
617
-
618
- // Physical/numeric features
619
- const productResults = service.FindNearest(features, 10, 0.8, 'euclidean');
620
-
621
- // Categorical/binary data
622
- const categoryResults = service.FindNearest(categories, 10, 0.6, 'jaccard');
283
+ style CR fill:#2d6a9f,stroke:#1a4971,color:#fff
284
+ style SIL fill:#2d8659,stroke:#1a5c3a,color:#fff
285
+ style WCD fill:#b8762f,stroke:#8a5722,color:#fff
286
+ style BCD fill:#b8762f,stroke:#8a5722,color:#fff
287
+ style CENT fill:#7c5295,stroke:#563a6b,color:#fff
623
288
  ```
624
289
 
625
- ### 2. Validate Dimensions
290
+ | Method | Returns | Interpretation |
291
+ |---|---|---|
292
+ | `SilhouetteScore` | -1 to 1 | > 0.7 strong, 0.5-0.7 reasonable, < 0.25 no structure |
293
+ | `WithinClusterDistance` | 0 to 1 | Lower = tighter clusters (more cohesive) |
294
+ | `BetweenClusterDistance` | 0 to 1 | Higher = better separated clusters |
295
+ | `FindCentroid` | number[] | Mean position of a vector set |
626
296
 
627
- ```typescript
628
- // Service automatically validates dimensions
629
- try {
630
- service.AddVector('key1', [1, 2, 3]);
631
- service.AddVector('key2', [4, 5, 6, 7]); // Error! Different dimensions
632
- } catch (error) {
633
- console.error('Dimension mismatch:', error.message);
634
- }
635
- ```
297
+ ## Typed Metadata
636
298
 
637
- ### 3. Use Metadata Effectively
299
+ Use TypeScript generics for type-safe metadata access:
638
300
 
639
301
  ```typescript
640
302
  interface ProductMetadata {
641
- name: string;
642
- category: string;
643
- price: number;
644
- inStock: boolean;
303
+ name: string;
304
+ category: string;
305
+ price: number;
645
306
  }
646
307
 
647
308
  const service = new SimpleVectorService<ProductMetadata>();
648
309
 
649
- // Now TypeScript knows the metadata structure
650
- const results = service.FindNearest(query, 5);
651
- results.forEach(r => {
652
- console.log(`${r.metadata.name}: $${r.metadata.price}`);
653
- });
654
- ```
655
-
656
- ### 4. Evaluate Clustering
657
-
658
- ```typescript
659
- // Always evaluate clustering quality
660
- function evaluateClustering(k: number) {
661
- const result = service.KMeansCluster(k);
662
- const score = result.metadata.silhouetteScore;
663
-
664
- if (score < 0.25) {
665
- console.warn('Poor clustering structure');
666
- } else if (score < 0.5) {
667
- console.log('Weak clustering structure');
668
- } else if (score < 0.7) {
669
- console.log('Reasonable clustering');
670
- } else {
671
- console.log('Strong clustering!');
672
- }
673
-
674
- return score;
675
- }
676
-
677
- // Try different K values
678
- for (let k = 2; k <= 10; k++) {
679
- const score = evaluateClustering(k);
680
- console.log(`k=${k}: score=${score.toFixed(3)}`);
681
- }
682
- ```
683
-
684
- ### 5. Handle Outliers
685
-
686
- ```typescript
687
- // Use DBSCAN when outliers are expected
688
- const result = service.DBSCANCluster(0.15, 3, 'euclidean');
689
-
690
- // Separate processing for outliers
691
- const normalData = [];
692
- const anomalies = [];
310
+ service.AddVector('prod1', embedding, { name: 'Widget', category: 'Tools', price: 29.99 });
693
311
 
694
- result.clusters.forEach((members, id) => {
695
- normalData.push(...members);
312
+ const results = service.FindNearest(queryVector, 5);
313
+ results.forEach(r => {
314
+ // TypeScript knows r.metadata is ProductMetadata
315
+ console.log(`${r.metadata.name}: $${r.metadata.price}`);
696
316
  });
697
-
698
- if (result.outliers) {
699
- anomalies.push(...result.outliers);
700
- // Special handling for anomalies
701
- console.log(`Found ${anomalies.length} anomalies`);
702
- }
703
317
  ```
704
318
 
705
- ## TypeScript Support
319
+ ## Performance Characteristics
706
320
 
707
- Full TypeScript support with generics for metadata:
321
+ | Operation | Complexity | Notes |
322
+ |---|---|---|
323
+ | AddVector / LoadVectors | O(1) per vector | Map-based storage |
324
+ | FindNearest (no filter) | O(n) | Linear scan with sort |
325
+ | FindNearest (with filter) | O(m) where m < n | Filter reduces candidate set |
326
+ | KMeansCluster | O(n * k * iterations) | K-Means++ initialization |
327
+ | DBSCANCluster | O(n^2) | Neighborhood pre-computation |
708
328
 
709
- ```typescript
710
- interface DocumentMetadata {
711
- title: string;
712
- author: string;
713
- date: Date;
714
- tags: string[];
715
- }
329
+ **Memory usage**: approximately `8 bytes * dimensions + ~100 bytes` per vector. Example: 10,000 vectors at 384 dimensions is roughly 31 MB.
716
330
 
717
- const service = new SimpleVectorService<DocumentMetadata>();
331
+ ## Dependencies
718
332
 
719
- // Type-safe metadata access
720
- const results = service.FindNearest(queryVector, 5);
721
- results.forEach(result => {
722
- // TypeScript knows result.metadata is DocumentMetadata
723
- console.log(`${result.metadata.title} by ${result.metadata.author}`);
724
- });
725
- ```
333
+ | Package | Purpose |
334
+ |---|---|
335
+ | `@memberjunction/core` | `LogError` for error reporting |
336
+ | `@memberjunction/global` | Global utilities |
726
337
 
727
- ## Error Handling
338
+ This package has minimal dependencies, making it lightweight and suitable for both server-side and client-side use.
728
339
 
729
- ```typescript
730
- try {
731
- // Dimension validation
732
- service.AddVector('key1', [1, 2, 3]);
733
- service.AddVector('key2', [4, 5]); // Error: dimension mismatch
734
- } catch (error) {
735
- console.error('Dimension error:', error.message);
736
- }
340
+ ## Development
737
341
 
738
- try {
739
- // Invalid parameters
740
- service.KMeansCluster(0); // Error: invalid k
741
- } catch (error) {
742
- console.error('Parameter error:', error.message);
743
- }
342
+ ```bash
343
+ # Build
344
+ npm run build
744
345
 
745
- try {
746
- // Empty vector set
747
- service.FindCentroid([]); // Error: empty set
748
- } catch (error) {
749
- console.error('Empty set error:', error.message);
750
- }
346
+ # Development mode
347
+ npm run start
751
348
  ```
752
349
 
753
- ## Contributing
754
-
755
- This is part of the MemberJunction open-source project. Contributions are welcome!
756
-
757
350
  ## License
758
351
 
759
- MIT License - see LICENSE file for details.
760
-
761
- ## Support
762
-
763
- For issues, questions, or contributions, please visit:
764
- https://github.com/MemberJunction/MJ
765
-
766
- ---
767
-
768
- *Part of the MemberJunction AI ecosystem - Enterprise-grade vector operations for modern applications.*
352
+ ISC