@mastra/qdrant 0.0.0-commonjs-20250227130920
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/.turbo/turbo-build.log +23 -0
- package/CHANGELOG.md +710 -0
- package/LICENSE +44 -0
- package/README.md +82 -0
- package/dist/_tsup-dts-rollup.d.cts +58 -0
- package/dist/_tsup-dts-rollup.d.ts +58 -0
- package/dist/index.cjs +336 -0
- package/dist/index.d.cts +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +334 -0
- package/eslint.config.js +6 -0
- package/package.json +40 -0
- package/src/index.ts +1 -0
- package/src/vector/filter.test.ts +857 -0
- package/src/vector/filter.ts +290 -0
- package/src/vector/index.test.ts +726 -0
- package/src/vector/index.ts +147 -0
- package/tsconfig.json +5 -0
- package/vitest.config.ts +11 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
Elastic License 2.0 (ELv2)
|
|
2
|
+
|
|
3
|
+
**Acceptance**
|
|
4
|
+
By using the software, you agree to all of the terms and conditions below.
|
|
5
|
+
|
|
6
|
+
**Copyright License**
|
|
7
|
+
The licensor grants you a non-exclusive, royalty-free, worldwide, non-sublicensable, non-transferable license to use, copy, distribute, make available, and prepare derivative works of the software, in each case subject to the limitations and conditions below
|
|
8
|
+
|
|
9
|
+
**Limitations**
|
|
10
|
+
You may not provide the software to third parties as a hosted or managed service, where the service provides users with access to any substantial set of the features or functionality of the software.
|
|
11
|
+
|
|
12
|
+
You may not move, change, disable, or circumvent the license key functionality in the software, and you may not remove or obscure any functionality in the software that is protected by the license key.
|
|
13
|
+
|
|
14
|
+
You may not alter, remove, or obscure any licensing, copyright, or other notices of the licensor in the software. Any use of the licensor’s trademarks is subject to applicable law.
|
|
15
|
+
|
|
16
|
+
**Patents**
|
|
17
|
+
The licensor grants you a license, under any patent claims the licensor can license, or becomes able to license, to make, have made, use, sell, offer for sale, import and have imported the software, in each case subject to the limitations and conditions in this license. This license does not cover any patent claims that you cause to be infringed by modifications or additions to the software. If you or your company make any written claim that the software infringes or contributes to infringement of any patent, your patent license for the software granted under these terms ends immediately. If your company makes such a claim, your patent license ends immediately for work on behalf of your company.
|
|
18
|
+
|
|
19
|
+
**Notices**
|
|
20
|
+
You must ensure that anyone who gets a copy of any part of the software from you also gets a copy of these terms.
|
|
21
|
+
|
|
22
|
+
If you modify the software, you must include in any modified copies of the software prominent notices stating that you have modified the software.
|
|
23
|
+
|
|
24
|
+
**No Other Rights**
|
|
25
|
+
These terms do not imply any licenses other than those expressly granted in these terms.
|
|
26
|
+
|
|
27
|
+
**Termination**
|
|
28
|
+
If you use the software in violation of these terms, such use is not licensed, and your licenses will automatically terminate. If the licensor provides you with a notice of your violation, and you cease all violation of this license no later than 30 days after you receive that notice, your licenses will be reinstated retroactively. However, if you violate these terms after such reinstatement, any additional violation of these terms will cause your licenses to terminate automatically and permanently.
|
|
29
|
+
|
|
30
|
+
**No Liability**
|
|
31
|
+
As far as the law allows, the software comes as is, without any warranty or condition, and the licensor will not be liable to you for any damages arising out of these terms or the use or nature of the software, under any kind of legal claim.
|
|
32
|
+
|
|
33
|
+
**Definitions**
|
|
34
|
+
The _licensor_ is the entity offering these terms, and the _software_ is the software the licensor makes available under these terms, including any portion of it.
|
|
35
|
+
|
|
36
|
+
_you_ refers to the individual or entity agreeing to these terms.
|
|
37
|
+
|
|
38
|
+
_your company_ is any legal entity, sole proprietorship, or other kind of organization that you work for, plus all organizations that have control over, are under the control of, or are under common control with that organization. _control_ means ownership of substantially all the assets of an entity, or the power to direct its management and policies by vote, contract, or otherwise. Control can be direct or indirect.
|
|
39
|
+
|
|
40
|
+
_your licenses_ are all the licenses granted to you for the software under these terms.
|
|
41
|
+
|
|
42
|
+
_use_ means anything you do with the software requiring one of your licenses.
|
|
43
|
+
|
|
44
|
+
_trademark_ means trademarks, service marks, and similar rights.
|
package/README.md
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
# @mastra/qdrant
|
|
2
|
+
|
|
3
|
+
Vector store implementation for Qdrant using the official @qdrant/js-client-rest SDK with added telemetry support.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pnpm add @mastra/qdrant
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Usage
|
|
12
|
+
|
|
13
|
+
```typescript
|
|
14
|
+
import { QdrantVector } from '@mastra/qdrant';
|
|
15
|
+
|
|
16
|
+
const vectorStore = new QdrantVector(
|
|
17
|
+
'http://localhost:6333', // url
|
|
18
|
+
'optional-api-key', // optional
|
|
19
|
+
false // https (optional)
|
|
20
|
+
);
|
|
21
|
+
|
|
22
|
+
// Create a new collection
|
|
23
|
+
await vectorStore.createIndex('my-collection', 1536, 'cosine');
|
|
24
|
+
|
|
25
|
+
// Add vectors
|
|
26
|
+
const vectors = [[0.1, 0.2, ...], [0.3, 0.4, ...]];
|
|
27
|
+
const metadata = [{ text: 'doc1' }, { text: 'doc2' }];
|
|
28
|
+
const ids = await vectorStore.upsert('my-collection', vectors, metadata);
|
|
29
|
+
|
|
30
|
+
// Query vectors
|
|
31
|
+
const results = await vectorStore.query(
|
|
32
|
+
'my-collection',
|
|
33
|
+
[0.1, 0.2, ...],
|
|
34
|
+
10, // topK
|
|
35
|
+
{ text: { $eq: 'doc1' } }, // optional filter
|
|
36
|
+
false // includeVector
|
|
37
|
+
);
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
## Configuration
|
|
41
|
+
|
|
42
|
+
Required:
|
|
43
|
+
|
|
44
|
+
- `url`: URL of your Qdrant instance
|
|
45
|
+
|
|
46
|
+
Optional:
|
|
47
|
+
|
|
48
|
+
- `apiKey`: API key for authentication
|
|
49
|
+
- `https`: Whether to use HTTPS (default: false)
|
|
50
|
+
|
|
51
|
+
## Features
|
|
52
|
+
|
|
53
|
+
- Vector similarity search with Cosine, Euclidean, and Dot Product metrics
|
|
54
|
+
- Automatic batching for large upserts (256 vectors per batch)
|
|
55
|
+
- Built-in telemetry support
|
|
56
|
+
- Metadata filtering
|
|
57
|
+
- Optional vector inclusion in query results
|
|
58
|
+
- Automatic UUID generation for vectors
|
|
59
|
+
- Support for both local and cloud deployments
|
|
60
|
+
- Built on top of @qdrant/js-client-rest SDK
|
|
61
|
+
|
|
62
|
+
## Distance Metrics
|
|
63
|
+
|
|
64
|
+
The following distance metrics are supported:
|
|
65
|
+
|
|
66
|
+
- `cosine` → Cosine distance
|
|
67
|
+
- `euclidean` → Euclidean distance
|
|
68
|
+
- `dotproduct` → Dot product
|
|
69
|
+
|
|
70
|
+
## Methods
|
|
71
|
+
|
|
72
|
+
- `createIndex(indexName, dimension, metric?)`: Create a new collection
|
|
73
|
+
- `upsert(indexName, vectors, metadata?, ids?)`: Add or update vectors
|
|
74
|
+
- `query(indexName, queryVector, topK?, filter?, includeVector?)`: Search for similar vectors
|
|
75
|
+
- `listIndexes()`: List all collections
|
|
76
|
+
- `describeIndex(indexName)`: Get collection statistics
|
|
77
|
+
- `deleteIndex(indexName)`: Delete a collection
|
|
78
|
+
|
|
79
|
+
## Related Links
|
|
80
|
+
|
|
81
|
+
- [Qdrant Documentation](https://qdrant.tech/documentation/)
|
|
82
|
+
- [Qdrant REST API Reference](https://qdrant.github.io/qdrant/redoc/index.html)
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { BaseFilterTranslator } from '@mastra/core/filter';
|
|
2
|
+
import type { Filter } from '@mastra/core/filter';
|
|
3
|
+
import type { IndexStats } from '@mastra/core/vector';
|
|
4
|
+
import type { LogicalOperator } from '@mastra/core/filter';
|
|
5
|
+
import { MastraVector } from '@mastra/core/vector';
|
|
6
|
+
import type { OperatorSupport } from '@mastra/core/filter';
|
|
7
|
+
import type { QueryResult } from '@mastra/core/vector';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Translates MongoDB-style filters to Qdrant compatible filters.
|
|
11
|
+
*
|
|
12
|
+
* Key transformations:
|
|
13
|
+
* - $and -> must
|
|
14
|
+
* - $or -> should
|
|
15
|
+
* - $not -> must_not
|
|
16
|
+
* - { field: { $op: value } } -> { key: field, match/range: { value/gt/lt: value } }
|
|
17
|
+
*
|
|
18
|
+
* Custom operators (Qdrant-specific):
|
|
19
|
+
* - $count -> values_count (array length/value count)
|
|
20
|
+
* - $geo -> geo filters (box, radius, polygon)
|
|
21
|
+
* - $hasId -> has_id filter
|
|
22
|
+
* - $nested -> nested object filters
|
|
23
|
+
* - $hasVector -> vector existence check
|
|
24
|
+
* - $datetime -> RFC 3339 datetime range
|
|
25
|
+
* - $null -> is_null check
|
|
26
|
+
* - $empty -> is_empty check
|
|
27
|
+
*/
|
|
28
|
+
export declare class QdrantFilterTranslator extends BaseFilterTranslator {
|
|
29
|
+
protected isLogicalOperator(key: string): key is LogicalOperator;
|
|
30
|
+
protected getSupportedOperators(): OperatorSupport;
|
|
31
|
+
translate(filter?: Filter): Filter | undefined;
|
|
32
|
+
private createCondition;
|
|
33
|
+
private translateNode;
|
|
34
|
+
private buildFinalConditions;
|
|
35
|
+
private handleLogicalOperators;
|
|
36
|
+
private handleFieldConditions;
|
|
37
|
+
private translateCustomOperator;
|
|
38
|
+
private getQdrantLogicalOp;
|
|
39
|
+
private translateOperatorValue;
|
|
40
|
+
private translateGeoFilter;
|
|
41
|
+
private normalizeDatetimeRange;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
declare class QdrantVector extends MastraVector {
|
|
45
|
+
private client;
|
|
46
|
+
constructor(url: string, apiKey?: string, https?: boolean);
|
|
47
|
+
upsert(indexName: string, vectors: number[][], metadata?: Record<string, any>[], ids?: string[]): Promise<string[]>;
|
|
48
|
+
createIndex(indexName: string, dimension: number, metric?: 'cosine' | 'euclidean' | 'dotproduct'): Promise<void>;
|
|
49
|
+
transformFilter(filter?: Filter): Filter | undefined;
|
|
50
|
+
query(indexName: string, queryVector: number[], topK?: number, filter?: Filter, includeVector?: boolean): Promise<QueryResult[]>;
|
|
51
|
+
listIndexes(): Promise<string[]>;
|
|
52
|
+
describeIndex(indexName: string): Promise<IndexStats>;
|
|
53
|
+
deleteIndex(indexName: string): Promise<void>;
|
|
54
|
+
}
|
|
55
|
+
export { QdrantVector }
|
|
56
|
+
export { QdrantVector as QdrantVector_alias_1 }
|
|
57
|
+
|
|
58
|
+
export { }
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { BaseFilterTranslator } from '@mastra/core/filter';
|
|
2
|
+
import type { Filter } from '@mastra/core/filter';
|
|
3
|
+
import type { IndexStats } from '@mastra/core/vector';
|
|
4
|
+
import type { LogicalOperator } from '@mastra/core/filter';
|
|
5
|
+
import { MastraVector } from '@mastra/core/vector';
|
|
6
|
+
import type { OperatorSupport } from '@mastra/core/filter';
|
|
7
|
+
import type { QueryResult } from '@mastra/core/vector';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Translates MongoDB-style filters to Qdrant compatible filters.
|
|
11
|
+
*
|
|
12
|
+
* Key transformations:
|
|
13
|
+
* - $and -> must
|
|
14
|
+
* - $or -> should
|
|
15
|
+
* - $not -> must_not
|
|
16
|
+
* - { field: { $op: value } } -> { key: field, match/range: { value/gt/lt: value } }
|
|
17
|
+
*
|
|
18
|
+
* Custom operators (Qdrant-specific):
|
|
19
|
+
* - $count -> values_count (array length/value count)
|
|
20
|
+
* - $geo -> geo filters (box, radius, polygon)
|
|
21
|
+
* - $hasId -> has_id filter
|
|
22
|
+
* - $nested -> nested object filters
|
|
23
|
+
* - $hasVector -> vector existence check
|
|
24
|
+
* - $datetime -> RFC 3339 datetime range
|
|
25
|
+
* - $null -> is_null check
|
|
26
|
+
* - $empty -> is_empty check
|
|
27
|
+
*/
|
|
28
|
+
export declare class QdrantFilterTranslator extends BaseFilterTranslator {
|
|
29
|
+
protected isLogicalOperator(key: string): key is LogicalOperator;
|
|
30
|
+
protected getSupportedOperators(): OperatorSupport;
|
|
31
|
+
translate(filter?: Filter): Filter | undefined;
|
|
32
|
+
private createCondition;
|
|
33
|
+
private translateNode;
|
|
34
|
+
private buildFinalConditions;
|
|
35
|
+
private handleLogicalOperators;
|
|
36
|
+
private handleFieldConditions;
|
|
37
|
+
private translateCustomOperator;
|
|
38
|
+
private getQdrantLogicalOp;
|
|
39
|
+
private translateOperatorValue;
|
|
40
|
+
private translateGeoFilter;
|
|
41
|
+
private normalizeDatetimeRange;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
declare class QdrantVector extends MastraVector {
|
|
45
|
+
private client;
|
|
46
|
+
constructor(url: string, apiKey?: string, https?: boolean);
|
|
47
|
+
upsert(indexName: string, vectors: number[][], metadata?: Record<string, any>[], ids?: string[]): Promise<string[]>;
|
|
48
|
+
createIndex(indexName: string, dimension: number, metric?: 'cosine' | 'euclidean' | 'dotproduct'): Promise<void>;
|
|
49
|
+
transformFilter(filter?: Filter): Filter | undefined;
|
|
50
|
+
query(indexName: string, queryVector: number[], topK?: number, filter?: Filter, includeVector?: boolean): Promise<QueryResult[]>;
|
|
51
|
+
listIndexes(): Promise<string[]>;
|
|
52
|
+
describeIndex(indexName: string): Promise<IndexStats>;
|
|
53
|
+
deleteIndex(indexName: string): Promise<void>;
|
|
54
|
+
}
|
|
55
|
+
export { QdrantVector }
|
|
56
|
+
export { QdrantVector as QdrantVector_alias_1 }
|
|
57
|
+
|
|
58
|
+
export { }
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,336 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var vector = require('@mastra/core/vector');
|
|
4
|
+
var jsClientRest = require('@qdrant/js-client-rest');
|
|
5
|
+
var filter = require('@mastra/core/filter');
|
|
6
|
+
|
|
7
|
+
// src/vector/index.ts
|
|
8
|
+
var QdrantFilterTranslator = class extends filter.BaseFilterTranslator {
|
|
9
|
+
isLogicalOperator(key) {
|
|
10
|
+
return super.isLogicalOperator(key) || key === "$hasId" || key === "$hasVector";
|
|
11
|
+
}
|
|
12
|
+
getSupportedOperators() {
|
|
13
|
+
return {
|
|
14
|
+
...filter.BaseFilterTranslator.DEFAULT_OPERATORS,
|
|
15
|
+
logical: ["$and", "$or", "$not"],
|
|
16
|
+
array: ["$in", "$nin"],
|
|
17
|
+
regex: ["$regex"],
|
|
18
|
+
custom: ["$count", "$geo", "$nested", "$datetime", "$null", "$empty", "$hasId", "$hasVector"]
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
translate(filter) {
|
|
22
|
+
if (this.isEmpty(filter)) return filter;
|
|
23
|
+
this.validateFilter(filter);
|
|
24
|
+
return this.translateNode(filter);
|
|
25
|
+
}
|
|
26
|
+
createCondition(type, value, fieldKey) {
|
|
27
|
+
const condition = { [type]: value };
|
|
28
|
+
return fieldKey ? { key: fieldKey, ...condition } : condition;
|
|
29
|
+
}
|
|
30
|
+
translateNode(node, isNested = false, fieldKey) {
|
|
31
|
+
if (!this.isEmpty(node) && typeof node === "object" && "must" in node) {
|
|
32
|
+
return node;
|
|
33
|
+
}
|
|
34
|
+
if (this.isPrimitive(node)) {
|
|
35
|
+
if (node === null) {
|
|
36
|
+
return { is_null: { key: fieldKey } };
|
|
37
|
+
}
|
|
38
|
+
return this.createCondition("match", { value: this.normalizeComparisonValue(node) }, fieldKey);
|
|
39
|
+
}
|
|
40
|
+
if (this.isRegex(node)) {
|
|
41
|
+
throw new Error("Direct regex pattern format is not supported in Qdrant");
|
|
42
|
+
}
|
|
43
|
+
if (Array.isArray(node)) {
|
|
44
|
+
return node.length === 0 ? { is_empty: { key: fieldKey } } : this.createCondition("match", { any: this.normalizeArrayValues(node) }, fieldKey);
|
|
45
|
+
}
|
|
46
|
+
const entries = Object.entries(node);
|
|
47
|
+
const logicalResult = this.handleLogicalOperators(entries, isNested);
|
|
48
|
+
if (logicalResult) {
|
|
49
|
+
return logicalResult;
|
|
50
|
+
}
|
|
51
|
+
const { conditions, range, matchCondition } = this.handleFieldConditions(entries, fieldKey);
|
|
52
|
+
if (Object.keys(range).length > 0) {
|
|
53
|
+
conditions.push({ key: fieldKey, range });
|
|
54
|
+
}
|
|
55
|
+
if (matchCondition) {
|
|
56
|
+
conditions.push({ key: fieldKey, match: matchCondition });
|
|
57
|
+
}
|
|
58
|
+
return this.buildFinalConditions(conditions, isNested);
|
|
59
|
+
}
|
|
60
|
+
buildFinalConditions(conditions, isNested) {
|
|
61
|
+
if (conditions.length === 0) {
|
|
62
|
+
return {};
|
|
63
|
+
} else if (conditions.length === 1 && isNested) {
|
|
64
|
+
return conditions[0];
|
|
65
|
+
} else {
|
|
66
|
+
return { must: conditions };
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
handleLogicalOperators(entries, isNested) {
|
|
70
|
+
const firstKey = entries[0]?.[0];
|
|
71
|
+
if (firstKey && this.isLogicalOperator(firstKey) && !this.isCustomOperator(firstKey)) {
|
|
72
|
+
const [key, value] = entries[0];
|
|
73
|
+
const qdrantOp = this.getQdrantLogicalOp(key);
|
|
74
|
+
return {
|
|
75
|
+
[qdrantOp]: Array.isArray(value) ? value.map((v) => this.translateNode(v, true)) : [this.translateNode(value, true)]
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
if (entries.length > 1 && !isNested && entries.every(([key]) => !this.isOperator(key) && !this.isCustomOperator(key))) {
|
|
79
|
+
return {
|
|
80
|
+
must: entries.map(([key, value]) => this.translateNode(value, true, key))
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
return null;
|
|
84
|
+
}
|
|
85
|
+
handleFieldConditions(entries, fieldKey) {
|
|
86
|
+
const conditions = [];
|
|
87
|
+
let range = {};
|
|
88
|
+
let matchCondition = null;
|
|
89
|
+
for (const [key, value] of entries) {
|
|
90
|
+
if (this.isCustomOperator(key)) {
|
|
91
|
+
const customOp = this.translateCustomOperator(key, value, fieldKey);
|
|
92
|
+
conditions.push(customOp);
|
|
93
|
+
} else if (this.isOperator(key)) {
|
|
94
|
+
const opResult = this.translateOperatorValue(key, value);
|
|
95
|
+
if (opResult.range) {
|
|
96
|
+
Object.assign(range, opResult.range);
|
|
97
|
+
} else {
|
|
98
|
+
matchCondition = opResult;
|
|
99
|
+
}
|
|
100
|
+
} else {
|
|
101
|
+
const nestedKey = fieldKey ? `${fieldKey}.${key}` : key;
|
|
102
|
+
const nestedCondition = this.translateNode(value, true, nestedKey);
|
|
103
|
+
if (nestedCondition.must) {
|
|
104
|
+
conditions.push(...nestedCondition.must);
|
|
105
|
+
} else if (!this.isEmpty(nestedCondition)) {
|
|
106
|
+
conditions.push(nestedCondition);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
return { conditions, range, matchCondition };
|
|
111
|
+
}
|
|
112
|
+
translateCustomOperator(op, value, fieldKey) {
|
|
113
|
+
switch (op) {
|
|
114
|
+
case "$count":
|
|
115
|
+
const countConditions = Object.entries(value).reduce(
|
|
116
|
+
(acc, [k, v]) => ({
|
|
117
|
+
...acc,
|
|
118
|
+
[k.replace("$", "")]: v
|
|
119
|
+
}),
|
|
120
|
+
{}
|
|
121
|
+
);
|
|
122
|
+
return { key: fieldKey, values_count: countConditions };
|
|
123
|
+
case "$geo":
|
|
124
|
+
const geoOp = this.translateGeoFilter(value.type, value);
|
|
125
|
+
return { key: fieldKey, ...geoOp };
|
|
126
|
+
case "$hasId":
|
|
127
|
+
return { has_id: Array.isArray(value) ? value : [value] };
|
|
128
|
+
case "$nested":
|
|
129
|
+
return {
|
|
130
|
+
nested: {
|
|
131
|
+
key: fieldKey,
|
|
132
|
+
filter: this.translateNode(value)
|
|
133
|
+
}
|
|
134
|
+
};
|
|
135
|
+
case "$hasVector":
|
|
136
|
+
return { has_vector: value };
|
|
137
|
+
case "$datetime":
|
|
138
|
+
return {
|
|
139
|
+
key: fieldKey,
|
|
140
|
+
range: this.normalizeDatetimeRange(value.range)
|
|
141
|
+
};
|
|
142
|
+
case "$null":
|
|
143
|
+
return { is_null: { key: fieldKey } };
|
|
144
|
+
case "$empty":
|
|
145
|
+
return { is_empty: { key: fieldKey } };
|
|
146
|
+
default:
|
|
147
|
+
throw new Error(`Unsupported custom operator: ${op}`);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
getQdrantLogicalOp(op) {
|
|
151
|
+
switch (op) {
|
|
152
|
+
case "$and":
|
|
153
|
+
return "must";
|
|
154
|
+
case "$or":
|
|
155
|
+
return "should";
|
|
156
|
+
case "$not":
|
|
157
|
+
return "must_not";
|
|
158
|
+
default:
|
|
159
|
+
throw new Error(`Unsupported logical operator: ${op}`);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
translateOperatorValue(operator, value) {
|
|
163
|
+
const normalizedValue = this.normalizeComparisonValue(value);
|
|
164
|
+
switch (operator) {
|
|
165
|
+
case "$eq":
|
|
166
|
+
return { value: normalizedValue };
|
|
167
|
+
case "$ne":
|
|
168
|
+
return { except: [normalizedValue] };
|
|
169
|
+
case "$gt":
|
|
170
|
+
return { range: { gt: normalizedValue } };
|
|
171
|
+
case "$gte":
|
|
172
|
+
return { range: { gte: normalizedValue } };
|
|
173
|
+
case "$lt":
|
|
174
|
+
return { range: { lt: normalizedValue } };
|
|
175
|
+
case "$lte":
|
|
176
|
+
return { range: { lte: normalizedValue } };
|
|
177
|
+
case "$in":
|
|
178
|
+
return { any: this.normalizeArrayValues(value) };
|
|
179
|
+
case "$nin":
|
|
180
|
+
return { except: this.normalizeArrayValues(value) };
|
|
181
|
+
case "$regex":
|
|
182
|
+
return { text: value };
|
|
183
|
+
case "exists":
|
|
184
|
+
return value ? {
|
|
185
|
+
must_not: [{ is_null: { key: value } }, { is_empty: { key: value } }]
|
|
186
|
+
} : {
|
|
187
|
+
is_empty: { key: value }
|
|
188
|
+
};
|
|
189
|
+
default:
|
|
190
|
+
throw new Error(`Unsupported operator: ${operator}`);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
translateGeoFilter(type, value) {
|
|
194
|
+
switch (type) {
|
|
195
|
+
case "box":
|
|
196
|
+
return {
|
|
197
|
+
geo_bounding_box: {
|
|
198
|
+
top_left: value.top_left,
|
|
199
|
+
bottom_right: value.bottom_right
|
|
200
|
+
}
|
|
201
|
+
};
|
|
202
|
+
case "radius":
|
|
203
|
+
return {
|
|
204
|
+
geo_radius: {
|
|
205
|
+
center: value.center,
|
|
206
|
+
radius: value.radius
|
|
207
|
+
}
|
|
208
|
+
};
|
|
209
|
+
case "polygon":
|
|
210
|
+
return {
|
|
211
|
+
geo_polygon: {
|
|
212
|
+
exterior: value.exterior,
|
|
213
|
+
interiors: value.interiors
|
|
214
|
+
}
|
|
215
|
+
};
|
|
216
|
+
default:
|
|
217
|
+
throw new Error(`Unsupported geo filter type: ${type}`);
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
normalizeDatetimeRange(value) {
|
|
221
|
+
const range = {};
|
|
222
|
+
for (const [op, val] of Object.entries(value)) {
|
|
223
|
+
if (val instanceof Date) {
|
|
224
|
+
range[op] = val.toISOString();
|
|
225
|
+
} else if (typeof val === "string") {
|
|
226
|
+
range[op] = val;
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
return range;
|
|
230
|
+
}
|
|
231
|
+
};
|
|
232
|
+
|
|
233
|
+
// src/vector/index.ts
|
|
234
|
+
var BATCH_SIZE = 256;
|
|
235
|
+
var DISTANCE_MAPPING = {
|
|
236
|
+
cosine: "Cosine",
|
|
237
|
+
euclidean: "Euclid",
|
|
238
|
+
dotproduct: "Dot"
|
|
239
|
+
};
|
|
240
|
+
var QdrantVector = class extends vector.MastraVector {
|
|
241
|
+
client;
|
|
242
|
+
constructor(url, apiKey, https) {
|
|
243
|
+
super();
|
|
244
|
+
const baseClient = new jsClientRest.QdrantClient({
|
|
245
|
+
url,
|
|
246
|
+
apiKey,
|
|
247
|
+
https
|
|
248
|
+
});
|
|
249
|
+
const telemetry = this.__getTelemetry();
|
|
250
|
+
this.client = telemetry?.traceClass(baseClient, {
|
|
251
|
+
spanNamePrefix: "qdrant-vector",
|
|
252
|
+
attributes: {
|
|
253
|
+
"vector.type": "qdrant"
|
|
254
|
+
}
|
|
255
|
+
}) ?? baseClient;
|
|
256
|
+
}
|
|
257
|
+
async upsert(indexName, vectors, metadata, ids) {
|
|
258
|
+
const pointIds = ids || vectors.map(() => crypto.randomUUID());
|
|
259
|
+
const records = vectors.map((vector, i) => ({
|
|
260
|
+
id: pointIds[i],
|
|
261
|
+
vector,
|
|
262
|
+
payload: metadata?.[i] || {}
|
|
263
|
+
}));
|
|
264
|
+
for (let i = 0; i < records.length; i += BATCH_SIZE) {
|
|
265
|
+
const batch = records.slice(i, i + BATCH_SIZE);
|
|
266
|
+
await this.client.upsert(indexName, {
|
|
267
|
+
// @ts-expect-error
|
|
268
|
+
points: batch,
|
|
269
|
+
wait: true
|
|
270
|
+
});
|
|
271
|
+
}
|
|
272
|
+
return pointIds;
|
|
273
|
+
}
|
|
274
|
+
async createIndex(indexName, dimension, metric = "cosine") {
|
|
275
|
+
if (!Number.isInteger(dimension) || dimension <= 0) {
|
|
276
|
+
throw new Error("Dimension must be a positive integer");
|
|
277
|
+
}
|
|
278
|
+
await this.client.createCollection(indexName, {
|
|
279
|
+
vectors: {
|
|
280
|
+
// @ts-expect-error
|
|
281
|
+
size: dimension,
|
|
282
|
+
// @ts-expect-error
|
|
283
|
+
distance: DISTANCE_MAPPING[metric]
|
|
284
|
+
}
|
|
285
|
+
});
|
|
286
|
+
}
|
|
287
|
+
transformFilter(filter) {
|
|
288
|
+
const translator = new QdrantFilterTranslator();
|
|
289
|
+
return translator.translate(filter);
|
|
290
|
+
}
|
|
291
|
+
async query(indexName, queryVector, topK = 10, filter, includeVector = false) {
|
|
292
|
+
const translatedFilter = this.transformFilter(filter);
|
|
293
|
+
const results = (await this.client.query(indexName, {
|
|
294
|
+
query: queryVector,
|
|
295
|
+
limit: topK,
|
|
296
|
+
filter: translatedFilter,
|
|
297
|
+
with_payload: true,
|
|
298
|
+
with_vector: includeVector
|
|
299
|
+
})).points;
|
|
300
|
+
return results.map((match) => {
|
|
301
|
+
let vector = [];
|
|
302
|
+
if (includeVector) {
|
|
303
|
+
if (Array.isArray(match.vector)) {
|
|
304
|
+
vector = match.vector;
|
|
305
|
+
} else if (typeof match.vector === "object" && match.vector !== null) {
|
|
306
|
+
vector = Object.values(match.vector).filter((v) => typeof v === "number");
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
return {
|
|
310
|
+
id: match.id,
|
|
311
|
+
score: match.score || 0,
|
|
312
|
+
metadata: match.payload,
|
|
313
|
+
...includeVector && { vector }
|
|
314
|
+
};
|
|
315
|
+
});
|
|
316
|
+
}
|
|
317
|
+
async listIndexes() {
|
|
318
|
+
const response = await this.client.getCollections();
|
|
319
|
+
return response.collections.map((collection) => collection.name) || [];
|
|
320
|
+
}
|
|
321
|
+
async describeIndex(indexName) {
|
|
322
|
+
const { config, points_count } = await this.client.getCollection(indexName);
|
|
323
|
+
const distance = config.params.vectors?.distance;
|
|
324
|
+
return {
|
|
325
|
+
dimension: config.params.vectors?.size,
|
|
326
|
+
count: points_count || 0,
|
|
327
|
+
// @ts-expect-error
|
|
328
|
+
metric: Object.keys(DISTANCE_MAPPING).find((key) => DISTANCE_MAPPING[key] === distance)
|
|
329
|
+
};
|
|
330
|
+
}
|
|
331
|
+
async deleteIndex(indexName) {
|
|
332
|
+
await this.client.deleteCollection(indexName);
|
|
333
|
+
}
|
|
334
|
+
};
|
|
335
|
+
|
|
336
|
+
exports.QdrantVector = QdrantVector;
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { QdrantVector } from './_tsup-dts-rollup.cjs';
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { QdrantVector } from './_tsup-dts-rollup.js';
|