@rushdb/javascript-sdk 1.19.0 → 2.0.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
@@ -2,156 +2,189 @@
2
2
 
3
3
  ![RushDB Logo](https://raw.githubusercontent.com/rush-db/rushdb/main/rushdb-logo.svg)
4
4
 
5
- # 🚀 RushDB SDK for JavaScript and TypeScript
5
+ # RushDB — JavaScript & TypeScript SDK
6
6
 
7
- ### The Modern Graph Database Client for Web & Node.js
7
+ ### The memory layer for AI agents and apps.
8
+
9
+ Push any JSON. Get graph relationships and vector search — automatically.
10
+ No schema. No pipeline. No glue code.
8
11
 
9
12
  [![NPM Version](https://img.shields.io/npm/v/%40rushdb%2Fjavascript-sdk)](https://www.npmjs.com/package/@rushdb/javascript-sdk)
10
- [![NPM License](https://img.shields.io/npm/l/%40rushdb%2Fjavascript-sdk)](#license "Go to license section")
11
13
  [![NPM Downloads](https://img.shields.io/npm/dw/%40rushdb%2Fjavascript-sdk)](https://www.npmjs.com/package/@rushdb/javascript-sdk)
12
- [![npm bundle size](https://img.shields.io/bundlephobia/minzip/%40rushdb%2Fjavascript-sdk)](https://bundlephobia.com/package/@rushdb/javascript-sdk)
14
+ [![Bundle size](https://img.shields.io/bundlephobia/minzip/%40rushdb%2Fjavascript-sdk)](https://bundlephobia.com/package/@rushdb/javascript-sdk)
15
+ [![License](https://img.shields.io/npm/l/%40rushdb%2Fjavascript-sdk)](#license)
16
+ [![Made with Node](https://img.shields.io/badge/dynamic/json?label=node&query=%24.engines%5B%22node%22%5D&url=https%3A%2F%2Fraw.githubusercontent.com%2Frush-db%2Frushdb%2Fmain%2Fpackage.json)](https://nodejs.org)
13
17
 
14
- [![Made with Node](https://img.shields.io/badge/dynamic/json?label=node&query=%24.engines%5B%22node%22%5D&url=https%3A%2F%2Fraw.githubusercontent.com%2Frush-db%2Frushdb%2Fmain%2Fpackage.json)](https://nodejs.org "Go to Node.js homepage")
15
- [![Package - Typescript](https://img.shields.io/github/package-json/dependency-version/rush-db/rushdb/dev/typescript?logo=typescript&logoColor=white)](https://www.npmjs.com/package/typescript "Go to TypeScript on NPM")
18
+ [🌐 Website](https://rushdb.com) • [📖 Documentation](https://docs.rushdb.com) • [☁️ Cloud](https://app.rushdb.com) • [🔍 Examples](https://github.com/rush-db/examples)
16
19
 
17
- [🌐 Website](https://rushdb.com) • [📖 Documentation](https://docs.rushdb.com) • [☁️ Cloud Platform](https://app.rushdb.com) • [🔍 Examples](https://github.com/rush-db/examples)
18
20
  </div>
19
21
 
20
- ## ✨ Highlights
21
-
22
22
  ---
23
23
 
24
- - **🔌 No Configuration Needed**: Plug-and-play design requires minimal setup to get started
25
- - **🛡️ Automatic Type Inference**: Enjoy seamless type safety with automatic TypeScript inference
26
- - **🔄 Isomorphic Architecture**: Fully compatible with both server and browser environments
27
- - **⚡ Zero Dependencies**: Lightweight (just 6.9KB gzipped) and efficient with no external dependencies
24
+ ## Why RushDB
25
+
26
+ Agents need memory. Apps need connected data. The standard answer involves multiple databases, schema design, and an embedding pipeline before you write a single useful line of business logic.
28
27
 
28
+ RushDB skips all of that:
29
29
 
30
- ## 📦 Installation
30
+ - **Managed embeddings** — mark a property for indexing once; every write is auto-embedded server-side
31
+ - **Graph auto-structured** — nested JSON becomes a traversable graph; no manual edge creation
32
+ - **Semantic + graph in one query** — filter by relationships, rank by meaning, compute metrics — one call (use select/groupBy)
33
+ - **Zero schema** — push any shape; RushDB infers types and links records
34
+ - **6.9KB gzipped** — zero runtime dependencies
35
+ - **Isomorphic** — Node.js and browser
31
36
 
32
37
  ---
33
- ```bash
34
- # NPM
35
- npm install @rushdb/javascript-sdk
36
38
 
37
- # YARN
38
- yarn add @rushdb/javascript-sdk
39
+ ## Installation
39
40
 
40
- # PNPM
41
- pnpm add @rushdb/javascript-sdk
41
+ ```bash
42
+ npm install @rushdb/javascript-sdk
43
+ # yarn add @rushdb/javascript-sdk
44
+ # pnpm add @rushdb/javascript-sdk
42
45
  ```
43
46
 
47
+ ---
44
48
 
45
- ## 🚀 Usage
49
+ ## Agent memory in 3 lines
46
50
 
47
- ---
51
+ Get an API key at [app.rushdb.com](https://app.rushdb.com).
48
52
 
49
- 1. **Obtain API Key**: Grab one from the [RushDB Cloud Dashboard](https://app.rushdb.com).
50
- 2. **Build anything**: Easily push, search, and manage relationships within your data.
53
+ ```typescript
54
+ import RushDB from '@rushdb/javascript-sdk'
55
+
56
+ const db = new RushDB('RUSHDB_API_KEY')
57
+
58
+ // 1. One-time: index a property for semantic search
59
+ await db.ai.indexes.create({ label: 'MEMORY', propertyName: 'output' })
60
+
61
+ // 2. Store — no embedder needed, server handles it
62
+ await db.records.create({
63
+ label: 'MEMORY',
64
+ data: {
65
+ agent_id: 'agent-42',
66
+ session_id: 'sess-001',
67
+ action: 'summarized',
68
+ topic: 'Q4 results',
69
+ output: summaryText,
70
+ },
71
+ })
51
72
 
52
- ### Quick Example
53
- ```ts
54
- import RushDB from '@rushdb/javascript-sdk';
73
+ // 3. Recall by meaning, scoped by graph
74
+ const memories = await db.ai.search({
75
+ labels: ['MEMORY'],
76
+ propertyName: 'output',
77
+ query: 'what did we decide about Q4?',
78
+ where: { agent_id: 'agent-42' },
79
+ limit: 10,
80
+ })
81
+ ```
55
82
 
56
- // Setup SDK
57
- const db = new RushDB("RUSHDB_API_KEY");
58
- // Default URL is "https://api.rushdb.com/api/v1". See SDK Configuration for more options.
83
+ ---
59
84
 
60
- // Push any data, and RushDB will automatically flatten it into Records
61
- // and establish relationships between them accordingly.
62
- await db.records.createMany({
63
- label: "COMPANY",
85
+ ## Graph traversal
86
+
87
+ ```typescript
88
+ // Push nested JSON — relationships created automatically
89
+ await db.records.importJson({
90
+ label: 'COMPANY',
64
91
  payload: {
65
- name: 'Google LLC',
66
- address: '1600 Amphitheatre Parkway, Mountain View, CA 94043, USA',
67
- foundedAt: '1998-09-04T00:00:00.000Z',
68
- rating: 4.9,
92
+ name: 'Acme Corp',
69
93
  DEPARTMENT: [{
70
- name: 'Research & Development',
71
- description: 'Innovating and creating advanced technologies for AI, cloud computing, and consumer devices.',
72
- PROJECT: [{
73
- name: 'Bard AI',
74
- description: 'A state-of-the-art generative AI model designed for natural language understanding and creation.',
75
- active: true,
76
- budget: 1200000000,
77
- EMPLOYEE: [{
78
- name: 'Jeff Dean',
79
- position: 'Head of AI Research',
80
- email: 'jeff@google.com',
81
- dob: '1968-07-16T00:00:00.000Z',
82
- salary: 3000000
83
- }]
94
+ name: 'Engineering',
95
+ EMPLOYEE: [{
96
+ name: 'Alice',
97
+ role: 'Staff Engineer',
84
98
  }]
85
99
  }]
86
100
  }
87
101
  })
88
102
 
89
-
90
- // Find Records by specific criteria
91
- const matchedEmployees = await db.records.find({
103
+ // Traverse the auto-created graph
104
+ const engineers = await db.records.find({
92
105
  labels: ['EMPLOYEE'],
93
106
  where: {
94
- position: { $contains: 'AI' },
95
- PROJECT: {
96
- DEPARTMENT: {
97
- COMPANY: {
98
- rating: { $gte: 4 }
99
- }
100
- }
101
- }
102
- }
107
+ role: { $contains: 'Engineer' },
108
+ DEPARTMENT: { COMPANY: { name: 'Acme Corp' } },
109
+ },
103
110
  })
104
111
 
105
- const company = await db.records.findUniq({
106
- labels: ['COMPANY'],
112
+ // Constrain by relationship type and direction
113
+ const authoredPosts = await db.records.find({
114
+ labels: ['USER'],
107
115
  where: {
108
- name: 'Google LLC'
109
- }
116
+ POST: {
117
+ $relation: { type: 'AUTHORED', direction: 'out' },
118
+ title: { $contains: 'graph' },
119
+ },
120
+ },
121
+ limit: 10,
110
122
  })
111
123
 
112
- // Manage relationships
113
- await company.attach(matchedEmployees, { type: "WORKING_AT" })
124
+ // Manage relationships explicitly
125
+ const company = await db.records.findUniq({
126
+ labels: ['COMPANY'],
127
+ where: { name: 'Acme Corp' },
128
+ })
129
+ await company.attach(engineers, { type: 'EMPLOYS' })
114
130
  ```
115
131
 
116
- ## ⚙️ SDK Configuration
117
132
  ---
118
- The SDK is designed to be flexible. You can provide configuration options when initializing `RushDB` to customize its behavior, such as the API endpoint or request timeouts.
119
133
 
120
- ```typescript
121
- import RushDB from '@rushdb/javascript-sdk';
134
+ ## Unified query API
122
135
 
123
- // Example: Initialize with a custom URL and timeout
124
- const db = new RushDB('RUSHDB_API_KEY', {
125
- url: 'http://your-custom-rushdb-server.com/api/v1', // Default is 'https://api.rushdb.com/api/v1'
126
- timeout: 30000 // 30 seconds
127
- });
136
+ One JSON structure works for records, labels, properties, relationships, aggregations, and vector search:
137
+
138
+ ```typescript
139
+ const result = await db.records.find({
140
+ labels: ['TRANSACTION'],
141
+ where: {
142
+ status: 'posted',
143
+ amount: { $gte: 100 },
144
+ },
145
+ select: {
146
+ total: { $sum: '$record.amount' },
147
+ },
148
+ groupBy: ['$record.category'],
149
+ // Legacy: The aggregate clause is deprecated and should only be used for vector similarity until select supports it.
150
+ orderBy: { amount: 'desc' },
151
+ limit: 50,
152
+ })
128
153
  ```
129
154
 
130
- The `RushDB` constructor accepts an optional second argument for configuration. Key options include:
131
- - `url`: The complete URL to the RushDB API.
132
- - Alternatively, `host`, `port`, and `protocol` can be specified individually.
133
- - `timeout`: Request timeout in milliseconds (default: 10000).
134
- - `httpClient`: For advanced use cases, provide a custom HTTP client implementation.
135
- - `logger`: Implement a custom logger for debugging or monitoring.
136
- - `options.allowForceDelete`: Set to `true` to enable deleting all records without specifying criteria (defaults to `false` for safety).
155
+ The same shape works with `db.labels.find()`, `db.properties.find()`, and `db.relationships.find()` — learn once, works everywhere.
137
156
 
138
- For a comprehensive guide on all available configuration options, please refer to the [SDK Configuration Documentation](https://docs.rushdb.com/typescript-sdk/introduction#sdk-configuration-options).
157
+ ---
139
158
 
140
- <div align="center">
141
- <b>You're Awesome!</b> 🚀
142
- </div>
159
+ ## SDK configuration
143
160
 
144
- ---
161
+ ```typescript
162
+ import RushDB from '@rushdb/javascript-sdk'
163
+
164
+ const db = new RushDB('RUSHDB_API_KEY', {
165
+ // Override for self-hosted or staging
166
+ url: 'http://your-rushdb-server.com/api/v1',
167
+ timeout: 30000,
168
+ })
169
+ ```
145
170
 
146
- <div align="center" style="margin-top: 20px">
171
+ Key options:
172
+ - `url` — full API URL (default: `https://api.rushdb.com/api/v1`)
173
+ - `host`, `port`, `protocol` — alternative to `url`
174
+ - `timeout` — request timeout in ms (default: 10000)
175
+ - `httpClient` — custom HTTP client for advanced use
176
+ - `options.allowForceDelete` — allow deleting all records without criteria (default: false)
147
177
 
148
- > 📚 Check the [Complete Documentation](https://docs.rushdb.com/typescript-sdk/introduction) and [Examples Repository](https://github.com/rush-db/examples) to learn more!
178
+ Full config reference: [docs.rushdb.com/typescript-sdk/introduction#sdk-configuration-options](https://docs.rushdb.com/typescript-sdk/introduction#sdk-configuration-options)
149
179
 
150
- </div>
180
+ ---
151
181
 
182
+ ## Documentation
152
183
 
153
- ## 🤝 Contributing
184
+ [docs.rushdb.com/typescript-sdk](https://docs.rushdb.com/typescript-sdk/introduction) — full API reference, examples, transactions, CSV import, and more.
154
185
 
155
186
  ---
156
- We welcome contributions! See our [CONTRIBUTING.md](CONTRIBUTING.md) guide for details.
157
187
 
188
+ ## Contributing
189
+
190
+ See [CONTRIBUTING.md](CONTRIBUTING.md). Issues and PRs welcome.
package/dist/api/api.d.ts CHANGED
@@ -4,6 +4,7 @@ import { DBRecordInstance, DBRecordsArrayInstance } from '../sdk/record.js';
4
4
  import type { SDKConfig } from '../sdk/types.js';
5
5
  import type { FlatObject, InferSchemaTypesWrite, MaybeArray, OrderDirection, Property, PropertyDraft, PropertyValuesData, Schema, SearchQuery, Where } from '../types/index.js';
6
6
  import type { ApiResponse } from './types.js';
7
+ import type { CreateEmbeddingIndexParams, EmbeddingIndex, EmbeddingIndexStats, SemanticSearchParams, UpsertEmbeddingVectorsParams, UpsertEmbeddingVectorsResult, VectorEntry } from './types.js';
7
8
  import { createFetcher } from '../network/index.js';
8
9
  import { Transaction } from '../sdk/transaction.js';
9
10
  export declare class RestAPI {
@@ -61,10 +62,11 @@ export declare class RestAPI {
61
62
  * @returns Promise resolving to the created DBRecordInstance
62
63
  * @throws Error if data is not a flat object and createMany should be used instead
63
64
  */
64
- create: <S extends Schema = any>({ label, data: rawData, options }: {
65
+ create: <S extends Schema = any>({ label, data: rawData, options, vectors }: {
65
66
  label: string;
66
67
  data: InferSchemaTypesWrite<S> | Array<PropertyDraft>;
67
68
  options?: Omit<DBRecordCreationOptions, "returnResult" | "capitalizeLabels" | "relationshipType">;
69
+ vectors?: VectorEntry[];
68
70
  }, transaction?: Transaction | string) => Promise<DBRecordInstance<S>>;
69
71
  /**
70
72
  * Creates multiple flat records in a single operation.
@@ -83,6 +85,11 @@ export declare class RestAPI {
83
85
  label: string;
84
86
  data: Array<InferSchemaTypesWrite<S>>;
85
87
  options?: DBRecordCreationOptions;
88
+ /**
89
+ * Per-row inline vectors for external embedding indexes.
90
+ * `vectors[i]` is applied to `data[i]`. Its length must not exceed `data.length`.
91
+ */
92
+ vectors?: VectorEntry[][];
86
93
  }, transaction?: Transaction | string) => Promise<DBRecordsArrayInstance<S>>;
87
94
  /**
88
95
  * Import nested or complex JSON payloads.
@@ -127,6 +134,12 @@ export declare class RestAPI {
127
134
  newline?: string;
128
135
  };
129
136
  parentId?: string;
137
+ /**
138
+ * Per-row inline vectors for external embedding indexes.
139
+ * `vectors[i]` is applied to CSV row `i` (0-based, after header).
140
+ * Its length must not exceed the number of data rows — validated server-side.
141
+ */
142
+ vectors?: VectorEntry[][];
130
143
  }, transaction?: Transaction | string) => Promise<DBRecordsArrayInstance<S>>;
131
144
  /**
132
145
  * Deletes records matching the search query
@@ -198,11 +211,12 @@ export declare class RestAPI {
198
211
  * @returns Promise resolving to updated DBRecordInstance
199
212
  * @throws Error if data is not a flat object
200
213
  */
201
- set: <S extends Schema = any>({ target, label, data: rawData, options }: {
214
+ set: <S extends Schema = any>({ target, label, data: rawData, options, vectors }: {
202
215
  target: DBRecordTarget;
203
216
  label: string;
204
217
  data: InferSchemaTypesWrite<S> | Array<PropertyDraft>;
205
218
  options?: Omit<DBRecordCreationOptions, "returnResult" | "capitalizeLabels" | "relationshipType">;
219
+ vectors?: VectorEntry[];
206
220
  }, transaction?: Transaction | string) => Promise<DBRecordInstance<S, SearchQuery<S>>>;
207
221
  /**
208
222
  * Updates record data (partial update)
@@ -232,13 +246,14 @@ export declare class RestAPI {
232
246
  * @param options.mergeStrategy - 'rewrite' | 'append'
233
247
  * @param transaction - Optional transaction for atomic operations
234
248
  */
235
- upsert: <S extends Schema = any>({ label, data: rawData, options }: {
249
+ upsert: <S extends Schema = any>({ label, data: rawData, options, vectors }: {
236
250
  label?: string;
237
251
  data: InferSchemaTypesWrite<S> | Array<PropertyDraft>;
238
252
  options?: Omit<DBRecordCreationOptions, "returnResult" | "capitalizeLabels" | "relationshipType"> & {
239
253
  mergeBy?: string[];
240
254
  mergeStrategy?: "rewrite" | "append";
241
255
  };
256
+ vectors?: VectorEntry[];
242
257
  }, transaction?: Transaction | string) => Promise<DBRecordInstance<S>>;
243
258
  };
244
259
  /**
@@ -336,6 +351,7 @@ export declare class RestAPI {
336
351
  metadata?: string;
337
352
  name: string;
338
353
  type: import("../types/value.js").PropertyType;
354
+ recordsCount?: number;
339
355
  } & {
340
356
  id: string;
341
357
  } & PropertyValuesData>>;
@@ -397,26 +413,105 @@ export declare class RestAPI {
397
413
  selfHosted: boolean;
398
414
  customDB?: boolean;
399
415
  managedDB?: boolean;
400
- planType?: import("../sdk/types.js").PlanType;
401
416
  } | undefined>>;
402
417
  };
403
418
  query: {
404
419
  /**
405
- * Runs a raw Cypher query against the connected Neo4j database.
420
+ * Executes a raw query against the underlying database engine.
406
421
  *
407
422
  * NOTE: This endpoint is cloud-only — available only on the RushDB managed
408
423
  * service or when your project is connected to a custom database through
409
424
  * RushDB Cloud. It will not work for self-hosted or local-only deployments.
410
425
  *
411
- * @param param0 - Object containing the Cypher query and optional params
412
- * @param param0.query - Cypher query string to execute
426
+ * @param param0 - Object containing the query and optional params
427
+ * @param param0.query - Query string to execute
413
428
  * @param param0.params - Optional parameters to pass to the query
414
429
  * @param transaction - Optional transaction id or Transaction instance to run the query in
415
- * @returns ApiResponse<any> - Raw result returned by the server (Neo4j driver result wrapped in ApiResponse)
430
+ * @returns ApiResponse<any> - Raw result returned by the server (wrapped in ApiResponse)
416
431
  */
417
432
  raw: <T extends unknown = any>({ query, params }: {
418
433
  query: string;
419
434
  params?: FlatObject;
420
435
  }, transaction?: Transaction | string) => Promise<ApiResponse<T>>;
421
436
  };
437
+ /**
438
+ * API methods for AI-assisted graph exploration.
439
+ */
440
+ ai: {
441
+ /**
442
+ * Returns the full graph ontology as structured JSON.
443
+ * Each item contains the label name, record count, properties with value ranges/samples,
444
+ * and cross-label relationships with direction.
445
+ * Properties may include a `vectorIndexes` array when one or more embedding indexes
446
+ * exist for that property — a non-empty array means the property is queryable with
447
+ * `db.ai.search()`. Each entry exposes: id, sourceType, similarityFunction, dimensions,
448
+ * status, and modelKey.
449
+ * Use property `id` fields to pass to db.properties.values() for deeper drill-down.
450
+ * @param params - Optional filter. `labels` scopes to specific labels only.
451
+ * `force: true` bypasses the 1-hour ontology cache and triggers a full recalculation.
452
+ * @param transaction - Optional transaction for atomic operations
453
+ */
454
+ getOntology: (params?: {
455
+ labels?: string[];
456
+ force?: boolean;
457
+ }, transaction?: Transaction | string) => Promise<ApiResponse<unknown[]>>;
458
+ /**
459
+ * Returns the full graph ontology as compact Markdown tables.
460
+ * Token-efficient — intended for direct LLM consumption.
461
+ * Includes: labels with counts, properties with types and value ranges/samples,
462
+ * cross-label relationship map, and a "Semantic Search" column per property that shows
463
+ * `sourceType similarityFunction dimensionsd [status]` (e.g. `managed cosine 1536d [ready]`)
464
+ * for indexed properties, or `—` when no embedding index exists.
465
+ * @param params - Optional filter. `labels` scopes to specific labels only.
466
+ * `force: true` bypasses the 1-hour ontology cache and triggers a full recalculation.
467
+ * @param transaction - Optional transaction for atomic operations
468
+ */
469
+ getOntologyMarkdown: (params?: {
470
+ labels?: string[];
471
+ force?: boolean;
472
+ }, transaction?: Transaction | string) => Promise<ApiResponse<string>>;
473
+ /**
474
+ * Embedding Index management methods.
475
+ */
476
+ indexes: {
477
+ /**
478
+ * Lists all embedding index policies configured for the current project.
479
+ */
480
+ find: () => Promise<ApiResponse<EmbeddingIndex[]>>;
481
+ /**
482
+ * Creates a new embedding index policy for a string property.
483
+ * @param params.propertyName - Name of the property to index
484
+ * @param params.modelKey - Embedding model identifier (e.g. 'text-embedding-3-small')
485
+ * @param params.dimensions - Vector dimensionality produced by the model
486
+ */
487
+ create: (params: CreateEmbeddingIndexParams) => Promise<ApiResponse<EmbeddingIndex>>;
488
+ /**
489
+ * Upserts external vectors for a specific embedding index.
490
+ * @param id - The target embedding index ID
491
+ * @param params.items - Array of { recordId, vector }
492
+ */
493
+ upsertVectors: (id: string, params: UpsertEmbeddingVectorsParams) => Promise<ApiResponse<UpsertEmbeddingVectorsResult>>;
494
+ /**
495
+ * Deletes an embedding index policy by ID.
496
+ * @param id - The ID of the embedding index to delete
497
+ */
498
+ delete: (id: string) => Promise<ApiResponse<{
499
+ deleted: boolean;
500
+ }>>;
501
+ /**
502
+ * Returns Neo4j-level statistics for an embedding index.
503
+ * @param id - The ID of the embedding index
504
+ */
505
+ stats: (id: string) => Promise<ApiResponse<EmbeddingIndexStats>>;
506
+ };
507
+ /**
508
+ * Performs semantic (vector) search over records whose `propertyName` has been indexed.
509
+ *
510
+ * RushDB performs exact search: candidates are narrowed via MATCH/WHERE first,
511
+ * then ranked by similarity. You can pass either query text or queryVector.
512
+ *
513
+ * @param params - Search parameters including the query text, property name, and optional filters
514
+ */
515
+ search: <S extends Schema = any>(params: SemanticSearchParams) => Promise<DBRecordsArrayInstance<S>>;
516
+ };
422
517
  }
@@ -1,2 +1,2 @@
1
1
  export { RestAPI } from './api.js';
2
- export { ApiResponse } from './types.js';
2
+ export { ApiResponse, CreateEmbeddingIndexParams, EmbeddingIndex, EmbeddingIndexStats, SemanticSearchParams, SemanticSearchResult, UpsertEmbeddingVectorItem, UpsertEmbeddingVectorsParams, UpsertEmbeddingVectorsResult } from './types.js';
@@ -1,5 +1,107 @@
1
+ import type { DBRecord } from '../sdk/record.js';
2
+ import type { Schema } from '../types/index.js';
1
3
  export type ApiResponse<T, E = Record<string, any>> = {
2
4
  data: T;
3
5
  success: boolean;
4
6
  total?: number;
5
7
  } & E;
8
+ /** An embedding index policy stored in RushDB. */
9
+ export type EmbeddingIndex = {
10
+ id: string;
11
+ projectId: string;
12
+ /** Neo4j label this index is scoped to (e.g. "Book"). */
13
+ label: string;
14
+ propertyName: string;
15
+ modelKey: string;
16
+ sourceType: 'managed' | 'external';
17
+ similarityFunction: 'cosine' | 'euclidean';
18
+ dimensions: number;
19
+ vectorPropertyName: string;
20
+ enabled: boolean;
21
+ /** 'pending' | 'indexing' | 'awaiting_vectors' | 'ready' | 'error' */
22
+ status: string;
23
+ createdAt: string;
24
+ updatedAt: string;
25
+ };
26
+ /** Parameters for creating a new embedding index. */
27
+ export type CreateEmbeddingIndexParams = {
28
+ /** Neo4j label to scope this index to (e.g. "Book", "Task"). */
29
+ label: string;
30
+ propertyName: string;
31
+ sourceType?: 'managed' | 'external';
32
+ /**
33
+ * Shorthand for `sourceType: 'external'`.
34
+ * When `true`, the index will be created with `sourceType: 'external'` regardless of the `sourceType` field.
35
+ */
36
+ external?: boolean;
37
+ similarityFunction?: 'cosine' | 'euclidean';
38
+ dimensions?: number;
39
+ };
40
+ /**
41
+ * A single vector entry for inline vector upsert.
42
+ * Provided alongside record data in create/upsert/set calls.
43
+ */
44
+ export type VectorEntry = {
45
+ /** Name of the property whose embedding index should be written to. */
46
+ propertyName: string;
47
+ /** The embedding vector to store. Its length must match the index dimensions. */
48
+ vector: number[];
49
+ /**
50
+ * Required when two indexes share the same `propertyName` and `dimensions` but differ in
51
+ * `similarityFunction`. Omit when there is only one matching index.
52
+ */
53
+ similarityFunction?: 'cosine' | 'euclidean';
54
+ };
55
+ export type UpsertEmbeddingVectorItem = {
56
+ recordId: string;
57
+ vector: number[];
58
+ };
59
+ export type UpsertEmbeddingVectorsParams = {
60
+ items: UpsertEmbeddingVectorItem[];
61
+ };
62
+ export type UpsertEmbeddingVectorsResult = {
63
+ updated: number;
64
+ requested: number;
65
+ };
66
+ /** Neo4j-level stats for an embedding index. */
67
+ export type EmbeddingIndexStats = {
68
+ totalRecords: number;
69
+ indexedRecords: number;
70
+ };
71
+ /** Parameters for semantic (vector) search over an embedding index. */
72
+ export type SemanticSearchParams = {
73
+ /** Name of the indexed property to search against. */
74
+ propertyName: string;
75
+ /** Free-text query that will be embedded and compared against indexed vectors. */
76
+ query?: string;
77
+ /** External vector query. Use instead of query text for external indexes. */
78
+ queryVector?: number[];
79
+ /**
80
+ * One or more Neo4j labels to scope the search.
81
+ * The first label is used to resolve which embedding index to use.
82
+ * Required — always provide at least one label.
83
+ */
84
+ labels: string[];
85
+ sourceType?: 'managed' | 'external';
86
+ similarityFunction?: 'cosine' | 'euclidean';
87
+ dimensions?: number;
88
+ /**
89
+ * Optional filter applied before cosine scoring.
90
+ * Candidates are narrowed via MATCH/WHERE and then ranked by similarity.
91
+ */
92
+ where?: Record<string, unknown>;
93
+ /** Number of results to skip for pagination (default 0). */
94
+ skip?: number;
95
+ /** Maximum number of results to return (default 20). */
96
+ limit?: number;
97
+ };
98
+ /**
99
+ * A record returned by db.ai.search().
100
+ * Identical to DBRecord but with __score guaranteed present — never optional.
101
+ * __score is the cosine similarity between the query vector and this record's embedding (0–1,
102
+ * higher = more similar). It is only injected by the semantic search path; regular
103
+ * db.records.find() / db.records.search() results are plain DBRecord and never carry __score.
104
+ */
105
+ export type SemanticSearchResult<S extends Schema = Schema> = DBRecord<S> & {
106
+ readonly __score: number;
107
+ };
@@ -5,5 +5,4 @@ export declare const PROPERTY_TYPE_DATETIME: "datetime";
5
5
  export declare const PROPERTY_TYPE_BOOLEAN: "boolean";
6
6
  export declare const PROPERTY_TYPE_NUMBER: "number";
7
7
  export declare const PROPERTY_TYPE_NULL: "null";
8
- export declare const PROPERTY_TYPE_VECTOR: "vector";
9
- export declare const PROPERTY_TYPES: ("string" | "number" | "boolean" | "datetime" | "null" | "vector")[];
8
+ export declare const PROPERTY_TYPES: ("string" | "number" | "boolean" | "datetime" | "null")[];