@wiscale/velesdb-sdk 1.3.0 → 1.4.1

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
@@ -165,24 +165,27 @@ const results = await db.hybridSearch(
165
165
  );
166
166
  ```
167
167
 
168
- ### `db.query(queryString, params)` (v0.8.5+)
168
+ ### `db.query(collection, queryString, params?, options?)` (v0.8.5+)
169
169
 
170
170
  Execute a VelesQL query.
171
171
 
172
172
  ```typescript
173
173
  // Simple query
174
174
  const results = await db.query(
175
+ 'documents',
175
176
  "SELECT * FROM documents WHERE category = 'tech' LIMIT 10"
176
177
  );
177
178
 
178
179
  // With vector parameter
179
180
  const results = await db.query(
181
+ 'documents',
180
182
  "SELECT * FROM documents WHERE VECTOR NEAR $query LIMIT 5",
181
183
  { query: [0.1, 0.2, ...] }
182
184
  );
183
185
 
184
186
  // Hybrid query
185
187
  const results = await db.query(
188
+ 'docs',
186
189
  "SELECT * FROM docs WHERE VECTOR NEAR $v AND content MATCH 'rust' LIMIT 10",
187
190
  { v: queryVector }
188
191
  );
@@ -246,6 +249,147 @@ await db.flush('documents');
246
249
 
247
250
  Close the client and release resources.
248
251
 
252
+ ## Knowledge Graph API (v1.2.0+)
253
+
254
+ VelesDB supports hybrid vector + graph queries.
255
+
256
+ ### `db.addEdge(collection, edge)`
257
+
258
+ ```typescript
259
+ await db.addEdge('social', {
260
+ id: 1, source: 100, target: 200,
261
+ label: 'FOLLOWS',
262
+ properties: { since: '2024-01-01' }
263
+ });
264
+ ```
265
+
266
+ ### `db.getEdges(collection, options?)`
267
+
268
+ ```typescript
269
+ const edges = await db.getEdges('social', { label: 'FOLLOWS' });
270
+ ```
271
+
272
+ ### `db.traverseGraph(collection, request)`
273
+
274
+ ```typescript
275
+ const result = await db.traverseGraph('social', {
276
+ source: 100, strategy: 'bfs', maxDepth: 3
277
+ });
278
+ ```
279
+
280
+ ### `db.getNodeDegree(collection, nodeId)`
281
+
282
+ ```typescript
283
+ const degree = await db.getNodeDegree('social', 100);
284
+ ```
285
+
286
+ ## VelesQL v2.0 Queries (v1.4.0+)
287
+
288
+ Execute advanced SQL-like queries with aggregation, joins, and set operations.
289
+
290
+ ### Aggregation with GROUP BY / HAVING
291
+
292
+ ```typescript
293
+ // Group by with aggregates
294
+ const result = await db.query('products', `
295
+ SELECT category, COUNT(*), AVG(price)
296
+ FROM products
297
+ GROUP BY category
298
+ HAVING COUNT(*) > 5 AND AVG(price) > 50
299
+ `);
300
+
301
+ // Access results
302
+ for (const row of result.results) {
303
+ console.log(row.payload.category, row.payload.count);
304
+ }
305
+ ```
306
+
307
+ ### ORDER BY with similarity()
308
+
309
+ ```typescript
310
+ // Order by semantic similarity
311
+ const result = await db.query('docs', `
312
+ SELECT * FROM docs
313
+ ORDER BY similarity(vector, $v) DESC
314
+ LIMIT 10
315
+ `, { v: queryVector });
316
+ ```
317
+
318
+ ### JOIN across collections
319
+
320
+ ```typescript
321
+ // Cross-collection join
322
+ const result = await db.query('orders', `
323
+ SELECT * FROM orders
324
+ JOIN customers AS c ON orders.customer_id = c.id
325
+ WHERE status = $status
326
+ `, { status: 'active' });
327
+ ```
328
+
329
+ ### Set Operations (UNION / INTERSECT / EXCEPT)
330
+
331
+ ```typescript
332
+ // Combine query results
333
+ const result = await db.query('users', `
334
+ SELECT * FROM active_users
335
+ UNION
336
+ SELECT * FROM archived_users
337
+ `);
338
+
339
+ // Find common elements
340
+ const result = await db.query('users', `
341
+ SELECT id FROM premium_users
342
+ INTERSECT
343
+ SELECT id FROM active_users
344
+ `);
345
+ ```
346
+
347
+ ### Hybrid Search with USING FUSION
348
+
349
+ ```typescript
350
+ // RRF fusion (default)
351
+ const result = await db.query('docs', `
352
+ SELECT * FROM docs
353
+ USING FUSION(strategy = 'rrf', k = 60)
354
+ LIMIT 20
355
+ `);
356
+
357
+ // Weighted fusion
358
+ const result = await db.query('docs', `
359
+ SELECT * FROM docs
360
+ USING FUSION(strategy = 'weighted', vector_weight = 0.7, graph_weight = 0.3)
361
+ LIMIT 20
362
+ `);
363
+ ```
364
+
365
+ ## VelesQL Query Builder (v1.2.0+)
366
+
367
+ Build type-safe VelesQL queries with the fluent builder API.
368
+
369
+ ```typescript
370
+ import { velesql } from '@wiscale/velesdb-sdk';
371
+
372
+ // Graph pattern query
373
+ const builder = velesql()
374
+ .match('d', 'Document')
375
+ .nearVector('$queryVector', queryVector)
376
+ .andWhere('d.category = $cat', { cat: 'tech' })
377
+ .limit(10);
378
+
379
+ const queryString = builder.toVelesQL();
380
+ const params = builder.getParams();
381
+ const results = await db.query('documents', queryString, params);
382
+
383
+ // Graph traversal with relationships
384
+ const graphQuery = velesql()
385
+ .match('p', 'Person')
386
+ .rel('KNOWS')
387
+ .to('f', 'Person')
388
+ .where('p.age > 25')
389
+ .return(['p.name', 'f.name'])
390
+ .toVelesQL();
391
+ ```
392
+
249
393
  ## Error Handling
250
394
 
251
395
  ```typescript
package/dist/index.d.mts CHANGED
@@ -72,13 +72,13 @@ interface SearchOptions {
72
72
  includeVectors?: boolean;
73
73
  }
74
74
  /** Fusion strategy for multi-query search */
75
- type FusionStrategy = 'rrf' | 'average' | 'maximum' | 'weighted';
75
+ type FusionStrategy$1 = 'rrf' | 'average' | 'maximum' | 'weighted';
76
76
  /** Multi-query search options */
77
77
  interface MultiQuerySearchOptions {
78
78
  /** Number of results to return (default: 10) */
79
79
  k?: number;
80
80
  /** Fusion strategy (default: 'rrf') */
81
- fusion?: FusionStrategy;
81
+ fusion?: FusionStrategy$1;
82
82
  /** Fusion parameters */
83
83
  fusionParams?: {
84
84
  /** RRF k parameter (default: 60) */
@@ -191,6 +191,44 @@ interface DegreeResponse {
191
191
  /** Number of outgoing edges */
192
192
  outDegree: number;
193
193
  }
194
+ /** VelesQL query options */
195
+ interface QueryOptions {
196
+ /** Timeout in milliseconds (default: 30000) */
197
+ timeoutMs?: number;
198
+ /** Enable streaming response */
199
+ stream?: boolean;
200
+ }
201
+ /** Query result from multi-model VelesQL query */
202
+ interface QueryResult {
203
+ /** Node/point ID */
204
+ nodeId: bigint | number;
205
+ /** Vector similarity score (if applicable) */
206
+ vectorScore: number | null;
207
+ /** Graph relevance score (if applicable) */
208
+ graphScore: number | null;
209
+ /** Combined fused score */
210
+ fusedScore: number;
211
+ /** Variable bindings from MATCH clause */
212
+ bindings: Record<string, unknown>;
213
+ /** Column data from JOIN (if applicable) */
214
+ columnData: Record<string, unknown> | null;
215
+ }
216
+ /** Query execution statistics */
217
+ interface QueryStats {
218
+ /** Execution time in milliseconds */
219
+ executionTimeMs: number;
220
+ /** Execution strategy used */
221
+ strategy: string;
222
+ /** Number of nodes scanned */
223
+ scannedNodes: number;
224
+ }
225
+ /** Full query response with results and stats */
226
+ interface QueryResponse {
227
+ /** Query results */
228
+ results: QueryResult[];
229
+ /** Execution statistics */
230
+ stats: QueryStats;
231
+ }
194
232
  /** Index type for property indexes */
195
233
  type IndexType = 'hash' | 'range';
196
234
  /** Index information */
@@ -256,8 +294,8 @@ interface IVelesDBBackend {
256
294
  vectorWeight?: number;
257
295
  filter?: Record<string, unknown>;
258
296
  }): Promise<SearchResult[]>;
259
- /** Execute VelesQL query */
260
- query(queryString: string, params?: Record<string, unknown>): Promise<SearchResult[]>;
297
+ /** Execute VelesQL multi-model query (EPIC-031 US-011) */
298
+ query(collection: string, queryString: string, params?: Record<string, unknown>, options?: QueryOptions): Promise<QueryResponse>;
261
299
  /** Multi-query fusion search */
262
300
  multiQuerySearch(collection: string, vectors: Array<number[] | Float32Array>, options?: MultiQuerySearchOptions): Promise<SearchResult[]>;
263
301
  /** Check if collection is empty */
@@ -462,13 +500,28 @@ declare class VelesDB {
462
500
  filter?: Record<string, unknown>;
463
501
  }): Promise<SearchResult[]>;
464
502
  /**
465
- * Execute a VelesQL query
503
+ * Execute a VelesQL multi-model query (EPIC-031 US-011)
504
+ *
505
+ * Supports hybrid vector + graph queries with VelesQL syntax.
466
506
  *
507
+ * @param collection - Collection name
467
508
  * @param queryString - VelesQL query string
468
- * @param params - Optional query parameters
469
- * @returns Query results
509
+ * @param params - Query parameters (vectors, scalars)
510
+ * @param options - Query options (timeout, streaming)
511
+ * @returns Query response with results and execution stats
512
+ *
513
+ * @example
514
+ * ```typescript
515
+ * const response = await db.query('docs', `
516
+ * MATCH (d:Doc) WHERE vector NEAR $q LIMIT 20
517
+ * `, { q: queryVector });
518
+ *
519
+ * for (const r of response.results) {
520
+ * console.log(`Node ${r.nodeId}: ${r.fusedScore}`);
521
+ * }
522
+ * ```
470
523
  */
471
- query(queryString: string, params?: Record<string, unknown>): Promise<SearchResult[]>;
524
+ query(collection: string, queryString: string, params?: Record<string, unknown>, options?: QueryOptions): Promise<QueryResponse>;
472
525
  /**
473
526
  * Multi-query fusion search combining results from multiple query vectors
474
527
  *
@@ -673,7 +726,7 @@ declare class WasmBackend implements IVelesDBBackend {
673
726
  vectorWeight?: number;
674
727
  filter?: Record<string, unknown>;
675
728
  }): Promise<SearchResult[]>;
676
- query(_queryString: string, _params?: Record<string, unknown>): Promise<SearchResult[]>;
729
+ query(_collection: string, _queryString: string, _params?: Record<string, unknown>, _options?: QueryOptions): Promise<QueryResponse>;
677
730
  multiQuerySearch(_collection: string, _vectors: Array<number[] | Float32Array>, _options?: MultiQuerySearchOptions): Promise<SearchResult[]>;
678
731
  isEmpty(collectionName: string): Promise<boolean>;
679
732
  flush(collectionName: string): Promise<void>;
@@ -711,6 +764,11 @@ declare class RestBackend implements IVelesDBBackend {
711
764
  private ensureInitialized;
712
765
  private mapStatusToErrorCode;
713
766
  private extractErrorPayload;
767
+ /**
768
+ * Parse node ID safely to handle u64 values above Number.MAX_SAFE_INTEGER.
769
+ * Returns bigint for large values, number for safe values.
770
+ */
771
+ private parseNodeId;
714
772
  private request;
715
773
  createCollection(name: string, config: CollectionConfig): Promise<void>;
716
774
  deleteCollection(name: string): Promise<void>;
@@ -735,7 +793,7 @@ declare class RestBackend implements IVelesDBBackend {
735
793
  vectorWeight?: number;
736
794
  filter?: Record<string, unknown>;
737
795
  }): Promise<SearchResult[]>;
738
- query(queryString: string, params?: Record<string, unknown>): Promise<SearchResult[]>;
796
+ query(collection: string, queryString: string, params?: Record<string, unknown>, _options?: QueryOptions): Promise<QueryResponse>;
739
797
  multiQuerySearch(collection: string, vectors: Array<number[] | Float32Array>, options?: MultiQuerySearchOptions): Promise<SearchResult[]>;
740
798
  isEmpty(collection: string): Promise<boolean>;
741
799
  flush(collection: string): Promise<void>;
@@ -750,4 +808,194 @@ declare class RestBackend implements IVelesDBBackend {
750
808
  getNodeDegree(collection: string, nodeId: number): Promise<DegreeResponse>;
751
809
  }
752
810
 
753
- export { type AddEdgeRequest, type BackendType, type Collection, type CollectionConfig, type CollectionType, ConnectionError, type CreateIndexOptions, type DegreeResponse, type DistanceMetric, type EdgesResponse, type FusionStrategy, type GetEdgesOptions, type GraphEdge, type IVelesDBBackend, type IndexInfo, type IndexType, type MultiQuerySearchOptions, NotFoundError, RestBackend, type SearchOptions, type SearchResult, type StorageMode, type TraversalResultItem, type TraversalStats, type TraverseRequest, type TraverseResponse, ValidationError, type VectorDocument, VelesDB, type VelesDBConfig, VelesDBError, WasmBackend };
811
+ /**
812
+ * VelesQL Query Builder (EPIC-012/US-004)
813
+ *
814
+ * Fluent, type-safe API for building VelesQL queries.
815
+ *
816
+ * @example
817
+ * ```typescript
818
+ * import { velesql } from '@velesdb/sdk';
819
+ *
820
+ * const query = velesql()
821
+ * .match('d', 'Document')
822
+ * .nearVector('$q', embedding)
823
+ * .andWhere('d.category = $cat', { cat: 'tech' })
824
+ * .limit(20)
825
+ * .toVelesQL();
826
+ * ```
827
+ *
828
+ * @packageDocumentation
829
+ */
830
+ /** Direction for relationship traversal */
831
+ type RelDirection = 'outgoing' | 'incoming' | 'both';
832
+ /** Fusion strategy for hybrid queries */
833
+ type FusionStrategy = 'rrf' | 'average' | 'maximum' | 'weighted';
834
+ /** Options for relationship patterns */
835
+ interface RelOptions {
836
+ direction?: RelDirection;
837
+ minHops?: number;
838
+ maxHops?: number;
839
+ }
840
+ /** Options for vector NEAR clause */
841
+ interface NearVectorOptions {
842
+ topK?: number;
843
+ }
844
+ /** Fusion configuration */
845
+ interface FusionOptions {
846
+ strategy: FusionStrategy;
847
+ k?: number;
848
+ vectorWeight?: number;
849
+ graphWeight?: number;
850
+ }
851
+ /** Internal state for the query builder */
852
+ interface BuilderState {
853
+ matchClauses: string[];
854
+ whereClauses: string[];
855
+ whereOperators: string[];
856
+ params: Record<string, unknown>;
857
+ limitValue?: number;
858
+ offsetValue?: number;
859
+ orderByClause?: string;
860
+ returnClause?: string;
861
+ fusionOptions?: FusionOptions;
862
+ currentNode?: string;
863
+ pendingRel?: {
864
+ type: string;
865
+ alias?: string;
866
+ options?: RelOptions;
867
+ };
868
+ }
869
+ /**
870
+ * VelesQL Query Builder
871
+ *
872
+ * Immutable builder for constructing VelesQL queries with type safety.
873
+ */
874
+ declare class VelesQLBuilder {
875
+ private readonly state;
876
+ constructor(state?: Partial<BuilderState>);
877
+ private clone;
878
+ /**
879
+ * Start a MATCH clause with a node pattern
880
+ *
881
+ * @param alias - Node alias (e.g., 'n', 'person')
882
+ * @param label - Optional node label(s)
883
+ */
884
+ match(alias: string, label?: string | string[]): VelesQLBuilder;
885
+ /**
886
+ * Add a relationship pattern
887
+ *
888
+ * @param type - Relationship type (e.g., 'KNOWS', 'FOLLOWS')
889
+ * @param alias - Optional relationship alias
890
+ * @param options - Relationship options (direction, hops)
891
+ */
892
+ rel(type: string, alias?: string, options?: RelOptions): VelesQLBuilder;
893
+ /**
894
+ * Complete a relationship pattern with target node
895
+ *
896
+ * @param alias - Target node alias
897
+ * @param label - Optional target node label(s)
898
+ */
899
+ to(alias: string, label?: string | string[]): VelesQLBuilder;
900
+ /**
901
+ * Add a WHERE clause
902
+ *
903
+ * @param condition - WHERE condition
904
+ * @param params - Optional parameters
905
+ */
906
+ where(condition: string, params?: Record<string, unknown>): VelesQLBuilder;
907
+ /**
908
+ * Add an AND WHERE clause
909
+ *
910
+ * @param condition - WHERE condition
911
+ * @param params - Optional parameters
912
+ */
913
+ andWhere(condition: string, params?: Record<string, unknown>): VelesQLBuilder;
914
+ /**
915
+ * Add an OR WHERE clause
916
+ *
917
+ * @param condition - WHERE condition
918
+ * @param params - Optional parameters
919
+ */
920
+ orWhere(condition: string, params?: Record<string, unknown>): VelesQLBuilder;
921
+ /**
922
+ * Add a vector NEAR clause for similarity search
923
+ *
924
+ * @param paramName - Parameter name (e.g., '$query', '$embedding')
925
+ * @param vector - Vector data
926
+ * @param options - NEAR options (topK)
927
+ */
928
+ nearVector(paramName: string, vector: number[] | Float32Array, options?: NearVectorOptions): VelesQLBuilder;
929
+ /**
930
+ * Add LIMIT clause
931
+ *
932
+ * @param value - Maximum number of results
933
+ */
934
+ limit(value: number): VelesQLBuilder;
935
+ /**
936
+ * Add OFFSET clause
937
+ *
938
+ * @param value - Number of results to skip
939
+ */
940
+ offset(value: number): VelesQLBuilder;
941
+ /**
942
+ * Add ORDER BY clause
943
+ *
944
+ * @param field - Field to order by
945
+ * @param direction - Sort direction (ASC or DESC)
946
+ */
947
+ orderBy(field: string, direction?: 'ASC' | 'DESC'): VelesQLBuilder;
948
+ /**
949
+ * Add RETURN clause with specific fields
950
+ *
951
+ * @param fields - Fields to return (array or object with aliases)
952
+ */
953
+ return(fields: string[] | Record<string, string>): VelesQLBuilder;
954
+ /**
955
+ * Add RETURN * clause
956
+ */
957
+ returnAll(): VelesQLBuilder;
958
+ /**
959
+ * Set fusion strategy for hybrid queries
960
+ *
961
+ * @param strategy - Fusion strategy
962
+ * @param options - Fusion parameters
963
+ */
964
+ fusion(strategy: FusionStrategy, options?: {
965
+ k?: number;
966
+ vectorWeight?: number;
967
+ graphWeight?: number;
968
+ }): VelesQLBuilder;
969
+ /**
970
+ * Get the fusion options
971
+ */
972
+ getFusionOptions(): FusionOptions | undefined;
973
+ /**
974
+ * Get all parameters
975
+ */
976
+ getParams(): Record<string, unknown>;
977
+ /**
978
+ * Build the VelesQL query string
979
+ */
980
+ toVelesQL(): string;
981
+ private formatLabel;
982
+ private formatRelationship;
983
+ private formatHops;
984
+ private buildWhereClause;
985
+ }
986
+ /**
987
+ * Create a new VelesQL query builder
988
+ *
989
+ * @example
990
+ * ```typescript
991
+ * const query = velesql()
992
+ * .match('n', 'Person')
993
+ * .where('n.age > 21')
994
+ * .limit(10)
995
+ * .toVelesQL();
996
+ * // => "MATCH (n:Person) WHERE n.age > 21 LIMIT 10"
997
+ * ```
998
+ */
999
+ declare function velesql(): VelesQLBuilder;
1000
+
1001
+ export { type AddEdgeRequest, type BackendType, type Collection, type CollectionConfig, type CollectionType, ConnectionError, type CreateIndexOptions, type DegreeResponse, type DistanceMetric, type EdgesResponse, type FusionOptions, type FusionStrategy$1 as FusionStrategy, type GetEdgesOptions, type GraphEdge, type IVelesDBBackend, type IndexInfo, type IndexType, type MultiQuerySearchOptions, type NearVectorOptions, NotFoundError, type QueryOptions, type QueryResponse, type QueryResult, type QueryStats, type RelDirection, type RelOptions, RestBackend, type SearchOptions, type SearchResult, type StorageMode, type TraversalResultItem, type TraversalStats, type TraverseRequest, type TraverseResponse, ValidationError, type VectorDocument, VelesDB, type VelesDBConfig, VelesDBError, VelesQLBuilder, WasmBackend, velesql };