-
Notifications
You must be signed in to change notification settings - Fork 32
/
Data.ts
1105 lines (1025 loc) · 33.7 KB
/
Data.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
DataType,
DataTypeMap,
ERROR_REASONS,
DslType,
DeleteEntitiesReq,
FlushReq,
GetFlushStateReq,
GetQuerySegmentInfoReq,
GePersistentSegmentInfoReq,
InsertReq,
LoadBalanceReq,
ImportReq,
ListImportTasksReq,
ErrorCode,
FlushResult,
GetFlushStateResponse,
GetMetricsResponse,
GetQuerySegmentInfoResponse,
GePersistentSegmentInfoResponse,
MutationResult,
QueryResults,
ResStatus,
SearchResults,
ImportResponse,
ListImportTasksResponse,
GetMetricsRequest,
QueryReq,
GetReq,
DeleteReq,
QueryRes,
SearchReq,
SearchRes,
SearchSimpleReq,
DEFAULT_TOPK,
promisify,
findKeyValue,
sleep,
formatNumberPrecision,
parseToKeyValue,
checkCollectionName,
checkSearchParams,
parseBinaryVectorToBytes,
parseFloatVectorToBytes,
DEFAULT_DYNAMIC_FIELD,
generateDynamicRow,
getFieldDataMap,
ConsistencyLevelEnum,
} from '../';
import { Collection } from './Collection';
export class Data extends Collection {
// vectorTypes
vectorTypes = [DataType.BinaryVector, DataType.FloatVector];
/**
* Insert data into Milvus.
*
* @param data
* | Property | Type | Description |
* | :--- | :-- | :-- |
* | collection_name | String | Collection name |
* | partition_name(optional)| String | Partition name |
* | fields_data or data | { [x: string]: any }[] | If the field type is binary, the vector data length needs to be dimension / 8 |
* | timeout? | number | An optional duration of time in millisecond to allow for the RPC. If it is set to undefined, the client keeps waiting until the server responds or error occurs. Default is undefined |
*
* @returns
* | Property | Description |
* | :-- | :-- |
* | status | { error_code: number, reason: string } |
* | succ_index | Index array of the successfully inserted data |
* | err_index | Index array of the unsuccessfully inserted data |
* | IDs | ID array of the successfully inserted data |
*
*
* #### Example
*
* ```
* new milvusClient(MILUVS_ADDRESS).insert({
* collection_name: COLLECTION_NAME,
* fields_data: [{
* vector_field: [1,2,2,4],
* scalar_field: 1
* }]
* });
* ```
*/
async insert(data: InsertReq): Promise<MutationResult> {
checkCollectionName(data);
// ensure fields data available
data.fields_data = data.fields_data || data.data;
if (
!data.fields_data ||
!Array.isArray(data.fields_data) ||
!data.fields_data.length
) {
throw new Error(ERROR_REASONS.INSERT_CHECK_FIELD_DATA_IS_REQUIRED);
}
const { collection_name } = data;
const collectionInfo = await this.describeCollection({
collection_name,
});
if (collectionInfo.status.error_code !== ErrorCode.SUCCESS) {
throw new Error(collectionInfo.status.reason);
}
// Tip: The field data sequence needs to be set same as `collectionInfo.schema.fields`.
// If primarykey is set `autoid = true`, you cannot insert the data.
const fieldsDataMap = new Map(
collectionInfo.schema.fields
.filter(v => !v.is_primary_key || !v.autoID)
.map(v => [
v.name,
{
name: v.name,
type: v.data_type,
dim: Number(findKeyValue(v.type_params, 'dim')),
value: [], // value container
} as any,
])
);
// The actual data we pass to Milvus gRPC.
const params: any = { ...data, num_rows: data.fields_data.length };
// dynamic field is enabled, create $meta field
const isDynamic = collectionInfo.schema.enable_dynamic_field;
if (isDynamic) {
fieldsDataMap.set(DEFAULT_DYNAMIC_FIELD, {
name: DEFAULT_DYNAMIC_FIELD,
type: 'JSON',
value: [], // value container
});
}
// Loop through each row and set the corresponding field values in the Map.
data.fields_data.forEach((v, i) => {
// if support dynamic field, all field not in the schema would be grouped to a dynamic field
v = isDynamic
? generateDynamicRow(v, fieldsDataMap, DEFAULT_DYNAMIC_FIELD)
: v;
// get each fieldname in the data object
const fieldNames = Object.keys(v);
// go through each fieldname and encode or format data
fieldNames.forEach(name => {
const target = fieldsDataMap.get(name);
if (!target) {
throw new Error(`${ERROR_REASONS.INSERT_CHECK_WRONG_FIELD} ${i}`);
}
if (
DataTypeMap[target.type] === DataType.BinaryVector &&
v[name].length !== target.dim / 8
) {
throw new Error(ERROR_REASONS.INSERT_CHECK_WRONG_DIM);
}
// encode data
switch (DataTypeMap[target.type]) {
case DataType.BinaryVector:
case DataType.FloatVector:
for (let val of v[name]) {
target.value.push(val);
}
break;
case DataType.JSON:
// ensure empty string
target.value[i] = Buffer.from(JSON.stringify(v[name] || {}));
break;
default:
target.value[i] = v[name];
break;
}
});
});
// transform data from map to array, milvus grpc params
params.fields_data = Array.from(fieldsDataMap.values()).map(v => {
// milvus return string for field type, so we define the DataTypeMap to the value we need.
// but if milvus change the string, may cause we cant find value.
const type = DataTypeMap[v.type];
const key = this.vectorTypes.includes(type) ? 'vectors' : 'scalars';
let dataKey = 'float_vector';
switch (type) {
case DataType.FloatVector:
dataKey = 'float_vector';
break;
case DataType.BinaryVector:
dataKey = 'binary_vector';
break;
case DataType.Double:
dataKey = 'double_data';
break;
case DataType.Float:
dataKey = 'float_data';
break;
case DataType.Int64:
dataKey = 'long_data';
break;
case DataType.Int32:
case DataType.Int16:
case DataType.Int8:
dataKey = 'int_data';
break;
case DataType.Bool:
dataKey = 'bool_data';
break;
case DataType.VarChar:
dataKey = 'string_data';
break;
case DataType.JSON:
dataKey = 'json_data';
break;
default:
throw new Error(
`${ERROR_REASONS.INSERT_CHECK_WRONG_DATA_TYPE} "${v.type}."`
);
}
return {
type,
field_name: v.name,
is_dynamic: v.name === DEFAULT_DYNAMIC_FIELD,
[key]:
type === DataType.FloatVector
? {
dim: v.dim,
[dataKey]: {
data: v.value,
},
}
: type === DataType.BinaryVector
? {
dim: v.dim,
[dataKey]: parseBinaryVectorToBytes(v.value),
}
: {
[dataKey]: {
data: v.value,
},
},
};
});
const timeout = typeof data.timeout === 'undefined' ? 0 : data.timeout;
const promise = await promisify(this.client, 'Insert', params, timeout);
return promise;
}
/**
* Delete entities in Milvus
*
* @param data
* | Property | Type | Description |
* | :--- | :-- | :-- |
* | collection_name | String | Collection name |
* | partition_name(optional)| String | Partition name |
* | expr or filter | String | Boolean expression used to filter attribute. |
* | timeout? | number | An optional duration of time in millisecond to allow for the RPC. If it is set to undefined, the client keeps waiting until the server responds or error occurs. Default is undefined |
*
* @returns
* | Property | Description |
* | :-- | :-- |
* | status | { error_code: number, reason: string } |
* | IDs | ID array of the successfully deleted data |
*
*
* #### Example
*
* ```
* new milvusClient(MILUVS_ADDRESS).deleteEntities({
* collection_name: COLLECTION_NAME,
* expr: 'id in [1,2,3,4]'
* });
* ```
*/
async deleteEntities(data: DeleteEntitiesReq): Promise<MutationResult> {
if (!data || !data.collection_name) {
throw new Error(ERROR_REASONS.COLLECTION_NAME_IS_REQUIRED);
}
// check expr or filter
if (!data.filter && !data.expr) {
throw new Error(ERROR_REASONS.FILTER_EXPR_REQUIRED);
}
// filter > expr
data.expr = data.filter || data.expr;
const promise = await promisify(
this.client,
'Delete',
data,
data.timeout || this.timeout
);
return promise;
}
/**
* Delete entities in Milvus
*
* @param data
* | Property | Type | Description |
* | :--- | :-- | :-- |
* | collection_name | String | Collection name |
* | partition_name(optional)| String | Partition name |
* | ids | String[] or Number[] | ids to delete |
* | timeout? | number | An optional duration of time in millisecond to allow for the RPC. If it is set to undefined, the client keeps waiting until the server responds or error occurs. Default is undefined |
*
* @returns
* | Property | Description |
* | :-- | :-- |
* | status | { error_code: number, reason: string } |
* | IDs | ID array of the successfully deleted data |
*
*
* #### Example
*
* ```
* new milvusClient(MILUVS_ADDRESS).deleteEntities({
* collection_name: COLLECTION_NAME,
* expr: 'id in [1,2,3,4]'
* });
* ```
*/
async delete(data: DeleteReq): Promise<MutationResult> {
if (!data || !data.collection_name) {
throw new Error(ERROR_REASONS.COLLECTION_NAME_IS_REQUIRED);
}
if (!data.ids || data.ids.length === 0) {
throw new Error(ERROR_REASONS.IDS_REQUIRED);
}
const pkField = await this.getPkFieldName(data);
// generate expr by different type of ids
const expr =
typeof data.ids[0] === 'string'
? `${pkField} in ["${data.ids.join('","')}"]`
: `${pkField} in [${data.ids.join(',')}]`;
const req = { ...data, expr };
return this.deleteEntities(req);
}
/**
* Perform vector similarity search.
*
* @param data
* | Property | Type | Description |
* | :--- | :-- | :-- |
* | collection_name | String | Collection name |
* | vectors or data or (vector) | Number[][] or Number[] | Original vector to search with |
* | partition_names(optional)| String[] | Array of partition names |
* | limit(optional) | number | topk alias |
* | topk(optional) | number | topk |
* | offset(optional) | number | offset |
* | filter(optional) | String | Scalar field filter expression |
* | expr(optional) | String | filter alias |
* | output_fields(optional) | String[] | Support scalar field |
* | metric_type(optional) | String | similarity metric |
* | params(optional) | key value object | search params |
*
* @returns
* | Property | Description |
* | :-- | :-- |
* | status | { error_code: number, reason: string } |
* | results | {score:number,id:string}[]; |
*
* #### Example
*
* ```
* new milvusClient(MILUVS_ADDRESS).search({
* collection_name: COLLECTION_NAME,
* vector: [1, 2, 3, 4],
* });
* ```
*/
async search(data: SearchReq | SearchSimpleReq): Promise<SearchResults> {
// params check
checkSearchParams(data);
try {
// get collection info
const collectionInfo = await this.describeCollection({
collection_name: data.collection_name,
});
// get information from collection info
let vectorType: DataType;
let defaultOutputFields = [];
let anns_field: string;
for (let i = 0; i < collectionInfo.schema.fields.length; i++) {
const f = collectionInfo.schema.fields[i];
const type = DataTypeMap[f.data_type];
// filter vector field
if (type === DataType.FloatVector || type === DataType.BinaryVector) {
// anns field
anns_field = f.name;
// vector type
vectorType = type;
} else {
// save field name
defaultOutputFields.push(f.name);
}
}
// create search params
const search_params = (data as SearchReq).search_params || {
anns_field: anns_field!,
topk:
(data as SearchSimpleReq).limit ||
(data as SearchSimpleReq).topk ||
DEFAULT_TOPK,
offset: (data as SearchSimpleReq).offset || 0,
metric_type: (data as SearchSimpleReq).metric_type || '', // leave it empty
params: JSON.stringify((data as SearchSimpleReq).params || {}),
ignore_growing: (data as SearchSimpleReq).ignore_growing || false,
};
// create search vectors
let searchVectors: number[] | number[][] =
(data as SearchReq).vectors ||
(data as SearchSimpleReq).data ||
(data as SearchSimpleReq).vector;
// make sure the searchVectors format is correct
if (!Array.isArray(searchVectors[0])) {
searchVectors = [searchVectors as unknown] as number[][];
}
/**
* It will decide the score precision.
* If round_decimal is 3, need return like 3.142
* And if Milvus return like 3.142, Node will add more number after this like 3.142000047683716.
* So the score need to slice by round_decimal
*/
const round_decimal =
(data as SearchReq).search_params?.round_decimal ??
((data as SearchSimpleReq).params?.round_decimal as number);
// create placeholder_group
const PlaceholderGroup = this.milvusProto.lookupType(
'milvus.proto.common.PlaceholderGroup'
);
// tag $0 is hard code in milvus, when dsltype is expr
const placeholderGroupBytes = PlaceholderGroup.encode(
PlaceholderGroup.create({
placeholders: [
{
tag: '$0',
type: vectorType!,
values: searchVectors.map(v =>
vectorType === DataType.BinaryVector
? parseBinaryVectorToBytes(v)
: parseFloatVectorToBytes(v)
),
},
],
})
).finish();
const promise: SearchRes = await promisify(
this.client,
'Search',
{
collection_name: data.collection_name,
partition_names: data.partition_names,
output_fields: data.output_fields || defaultOutputFields,
nq: (data as SearchReq).nq || searchVectors.length,
dsl:
(data as SearchReq).expr || (data as SearchSimpleReq).filter || '',
dsl_type: DslType.BoolExprV1,
placeholder_group: placeholderGroupBytes,
search_params: parseToKeyValue(search_params),
consistency_level:
typeof data.consistency_level === 'undefined'
? ConsistencyLevelEnum.Bounded
: data.consistency_level,
},
data.timeout || this.timeout
);
// if search failed, return empty with status
if (promise.status.error_code !== ErrorCode.SUCCESS) {
return {
status: promise.status,
results: [],
};
}
// build final results array
const results: any[] = [];
const { topks, scores, fields_data, ids } = promise.results;
// build fields data map
const fieldsDataMap = getFieldDataMap(fields_data);
// build output name array
const output_fields = [
'id',
...(promise.results.output_fields ||
fields_data.map(f => f.field_name)),
];
// vector id support int / str id.
const idData = ids ? ids[ids.id_field]?.data : undefined;
// add id column
fieldsDataMap.set('id', idData);
// fieldsDataMap.set('score', scores); TODO: fieldDataMap to support formatter
/**
* This code block formats the search results returned by Milvus into row data for easier use.
* Milvus supports multiple queries to search and returns all columns data, so we need to splice the data for each search result using the `topk` variable.
* The `topk` variable is the key we use to splice data for every search result.
* The `scores` array is spliced using the `topk` value, and the resulting scores are formatted to the specified precision using the `formatNumberPrecision` function. The resulting row data is then pushed to the `results` array.
*/
topks.forEach((v, index) => {
const topk = Number(v);
scores.splice(0, topk).forEach((score, scoreIndex) => {
// get correct index
const i = index === 0 ? scoreIndex : scoreIndex + topk * index;
// fix round_decimal
const fixedScore =
typeof round_decimal === 'undefined' || round_decimal === -1
? score
: formatNumberPrecision(score, round_decimal);
// init result object
const result: any = { score: fixedScore };
// build result,
output_fields.forEach(field_name => {
// Check if the field_name exists in the fieldsDataMap
const isFixedSchema = fieldsDataMap.has(field_name);
// Get the data for the field_name from the fieldsDataMap
// If the field_name is not in the fieldsDataMap, use the DEFAULT_DYNAMIC_FIELD
const data = fieldsDataMap.get(
isFixedSchema ? field_name : DEFAULT_DYNAMIC_FIELD
);
// make dynamic data[i] safe
data[i] = isFixedSchema ? data[i] : data[i] || {};
// extract dynamic info from dynamic field if necessary
result[field_name] = isFixedSchema ? data[i] : data[i][field_name];
});
// init result slot
results[index] = results[index] || [];
// push result data
results[index].push(result);
});
});
return {
status: promise.status,
// if only searching 1 vector, return the first object of results array
results: searchVectors.length === 1 ? results[0] || [] : results,
};
} catch (err) {
/* istanbul ignore next */
throw new Error(err);
}
}
/**
* Milvus temporarily buffers the newly inserted vectors in the cache. Call `flush()` to persist them to the object storage.
* It's async function, so it's will take some times to execute.
* @param data
* | Property | Type | Description |
* | :--- | :-- | :-- |
* | collection_names | String[] | Array of collection names |
* | timeout? | number | An optional duration of time in millisecond to allow for the RPC. If it is set to undefined, the client keeps waiting until the server responds or error occurs. Default is undefined |
*
* @returns
* | Property | Description |
* | :-- | :-- |
* | status | { error_code: number, reason: string } |
*
* #### Example
*
* ```
* new milvusClient(MILUVS_ADDRESS).flush({
* collection_names: ['my_collection'],
* });
* ```
*/
async flush(data: FlushReq): Promise<FlushResult> {
if (
!data ||
!Array.isArray(data.collection_names) ||
!data.collection_names.length
) {
throw new Error(ERROR_REASONS.COLLECTION_NAME_IS_REQUIRED);
}
const res = await promisify(
this.client,
'Flush',
data,
data.timeout || this.timeout
);
return res;
}
/**
* It's same function as flush. But flushSync is sync function.
* So you can ensure it's flushed after function return the result.
*
* @param data
* | Property | Type | Description |
* | :--- | :-- | :-- |
* | collection_names | String[] | Array of collection names |
* | timeout? | number | An optional duration of time in millisecond to allow for the RPC. If it is set to undefined, the client keeps waiting until the server responds or error occurs. Default is undefined |
*
* @returns
* | Property | Description |
* | :-- | :-- |
* | status | { error_code: number, reason: string } |
*
* #### Example
*
* ```
* new milvusClient(MILUVS_ADDRESS).flushSync({
* collection_names: ['my_collection'],
* });
* ```
*/
async flushSync(data: FlushReq): Promise<GetFlushStateResponse> {
if (
!data ||
!Array.isArray(data.collection_names) ||
!data.collection_names.length
) {
throw new Error(ERROR_REASONS.COLLECTION_NAME_IS_REQUIRED);
}
// copy flushed collection names
const res = await promisify(
this.client,
'Flush',
data,
data.timeout || this.timeout
);
// After flush will return collection segment ids, need use GetPersistentSegmentInfo to check segment flush status.
const segIDs = Object.keys(res.coll_segIDs)
.map(v => res.coll_segIDs[v].data)
.reduce((pre, cur) => [...pre, ...cur], []);
let isFlushed = false;
let flushRes = null;
while (!isFlushed) {
flushRes = await this.getFlushState({ segmentIDs: segIDs });
await sleep(100);
isFlushed = flushRes.flushed;
}
// Before Milvus pre-GA will throw error
return flushRes as GetFlushStateResponse;
}
/**
* Query vector data in Milvus. Current release of Milvus only supports expression as fieldname in [id1,id2,id3]
*
* @param data
* | Property | Type | Description |
* | :--- | :-- | :-- |
* | collection_name | String | Collection name |
* | expr or filter | String | Scalar field filter expression |
* | partitions_names(optional) | String[] | Array of partition names |
* | output_fields | String[] | Vector or scalar field to be returned |
* | timeout? | number | An optional duration of time in millisecond to allow for the RPC. If it is set to undefined, the client keeps waiting until the server responds or error occurs. Default is undefined |
* | params | {key: value}[] | An optional key pair json array
*
* @returns
* | Property | Description |
* | :-- | :-- |
* | status | { error_code: number,reason:string } |
* | data | Data of all fields that you defined in `output_fields`, {field_name: value}[] |
*
*
* #### Example
*
* ```
* new milvusClient(MILUVS_ADDRESS).query({
* collection_name: 'my_collection',
* expr: "age in [1,2,3,4,5,6,7,8]",
* output_fields: ["age"],
* });
* ```
*/
async query(data: QueryReq): Promise<QueryResults> {
checkCollectionName(data);
// Set up limits and offset for the query
let limits: { limit: number } | undefined;
let offset: { offset: number } | undefined;
if (typeof data.limit === 'number') {
limits = { limit: data.limit };
}
if (typeof data.offset === 'number') {
offset = { offset: data.offset };
}
// check expr or filter
if (!data.filter && !data.expr) {
throw new Error(ERROR_REASONS.FILTER_EXPR_REQUIRED);
}
// filter > expr
data.expr = data.filter || data.expr;
// Execute the query and get the results
const promise: QueryRes = await promisify(
this.client,
'Query',
{
...data,
query_params: parseToKeyValue({ ...limits, ...offset }),
},
data.timeout || this.timeout
);
// compatible with milvus before v2.2.9
const output_fields =
promise.output_fields || promise.fields_data.map(f => f.field_name);
// Initialize an array to hold the query results
const results: { [x: string]: any }[] = [];
const fieldsDataMap = getFieldDataMap(promise.fields_data);
// For each output field, check if it has a fixed schema or not
const fieldData = output_fields.map(field_name => {
// Check if the field_name exists in the fieldsDataMap
const isFixedSchema = fieldsDataMap.has(field_name);
// Get the data for the field_name from the fieldsDataMap
// If the field_name is not in the fieldsDataMap, use the DEFAULT_DYNAMIC_FIELD
const data = fieldsDataMap.get(
isFixedSchema ? field_name : DEFAULT_DYNAMIC_FIELD
);
// Return an object containing the field_name and its corresponding data
// If the schema is fixed, use the data directly
// If the schema is not fixed, map the data to extract the field_name values
return {
data: isFixedSchema ? data : data.map((d: any) => d[field_name]),
field_name,
};
});
// parse column data to [{fieldname:value}]
fieldData.forEach((v: any) => {
v.data.forEach((d: string | number[], i: number) => {
if (!results[i]) {
results[i] = {
[v.field_name]: d,
};
} else {
results[i] = {
...results[i],
[v.field_name]: d,
};
}
});
});
return {
status: promise.status,
data: results,
};
}
/**
* get vector data by providing ids in Milvus
*
* @param data
* | Property | Type | Description |
* | :--- | :-- | :-- |
* | collection_name | String | Collection name |
* | ids | String[] | ids to get |
* | partitions_names(optional) | String[] | Array of partition names |
* | output_fields | String[] | Vector or scalar field to be returned |
* | timeout? | number | An optional duration of time in millisecond to allow for the RPC. If it is set to undefined, the client keeps waiting until the server responds or error occurs. Default is undefined |
* | params | {key: value}[] | An optional key pair json array
*
* @returns
* | Property | Description |
* | :-- | :-- |
* | status | { error_code: number,reason:string } |
* | data | Data of all fields that you defined in `output_fields`, {field_name: value}[] |
*
*
* #### Example
*
* ```
* new milvusClient(MILUVS_ADDRESS).get({
* collection_name: 'my_collection',
* ids: [1,2,3,4,5,6,7,8],
* output_fields: ["age"],
* });
* ```
*/
async get(data: GetReq): Promise<QueryResults> {
checkCollectionName(data);
const pkField = await this.getPkFieldName(data);
if (!data.ids || data.ids.length === 0) {
throw new Error(ERROR_REASONS.IDS_REQUIRED);
}
// build query req
const req = { ...data, expr: `${pkField} in [${data.ids.join(',')}]` };
return this.query(req);
}
/**
* @ignore
* @param data
* | Property | Type | Description |
* | :--- | :-- | :-- |
* | request | object | Only allow "system_info" for now |
*/
async getMetric(data: GetMetricsRequest): Promise<GetMetricsResponse> {
if (!data || !data.request || !data.request.metric_type) {
throw new Error(ERROR_REASONS.GET_METRIC_CHECK_PARAMS);
}
const res: GetMetricsResponse = await promisify(
this.client,
'GetMetrics',
{
request: JSON.stringify(data.request),
},
data.timeout || this.timeout
);
return {
...res,
response: JSON.parse(res.response),
};
}
/**
* Get flush state by segment ids
*
* @param data
* | Property | Type | Description |
* | :--- | :-- | :-- |
* | segmentIDs | Array | The segment ids |
* | timeout? | number | An optional duration of time in millisecond to allow for the RPC. If it is set to undefined, the client keeps waiting until the server responds or error occurs. Default is undefined |
*
* @returns
* | Property | Description |
* | :--- | :-- |
* | status | { error_code: number,reason:string } |
* | flushed | segments flushed or not |
*
*
* #### Example
*
* ```
* const res = await milvusClient.getFlushState({
* segmentIDs: segIds,
* });
* ```
*/
async getFlushState(data: GetFlushStateReq): Promise<GetFlushStateResponse> {
if (!data || !data.segmentIDs) {
throw new Error(ERROR_REASONS.GET_FLUSH_STATE_CHECK_PARAMS);
}
const res = await promisify(
this.client,
'GetFlushState',
data,
data.timeout || this.timeout
);
return res;
}
/**
* Do load balancing operation from source query node to destination query node.
* Only work in cluster milvus.
*
* @param data
* | Property | Type | Description |
* | :--- | :-- | :-- |
* | src_nodeID | number | The source query node id to balance. |
* | dst_nodeIDs | number[] | The destination query node ids to balance.(optional) |
* | sealed_segmentIDs | number[] | Sealed segment ids to balance.(optional) |
* | timeout? | number | An optional duration of time in millisecond to allow for the RPC. If it is set to undefined, the client keeps waiting until the server responds or error occurs. Default is undefined |
*
* @returns
* | Property | Description |
* | :--- | :-- |
* | status | { error_code: number,reason:string } |
* | infos | segments information |
*
*
* #### Example
*
* ```
* const res = await loadBalance({
* src_nodeID: 31,
* });
* ```
*/
async loadBalance(data: LoadBalanceReq): Promise<ResStatus> {
if (!data || !data.src_nodeID) {
throw new Error(ERROR_REASONS.LOAD_BALANCE_CHECK_PARAMS);
}
const res = await promisify(
this.client,
'LoadBalance',
data,
data.timeout || this.timeout
);
return res;
}
/**
* Notifies Proxy to return segments information from query nodes.
*
* @param data
* | Property | Type | Description |
* | :--- | :-- | :-- |
* | collectionName | String | The name of the collection to get segments info. |
* | timeout? | number | An optional duration of time in millisecond to allow for the RPC. If it is set to undefined, the client keeps waiting until the server responds or error occurs. Default is undefined |
*
*
* @returns
* | Property | Description |
* | :--- | :-- |
* | status | { error_code: number,reason:string } |
* | infos | QuerySegmentInfo is the growing segments's information in query cluster. |
*
*
* #### Example
*
* ```
* const res = await getQuerySegmentInfo({
* collectionName: COLLECTION,
* });
* ```
*/
async getQuerySegmentInfo(
data: GetQuerySegmentInfoReq
): Promise<GetQuerySegmentInfoResponse> {
if (!data || !data.collectionName) {
throw new Error(ERROR_REASONS.COLLECTION_NAME_IS_REQUIRED);
}
const res = await promisify(
this.client,
'GetQuerySegmentInfo',
data,
data.timeout || this.timeout
);
return res;
}
/**data
* Notifies Proxy to return segments information from data nodes.
*
* @param data
* | Property | Type | Description |
* | :--- | :-- | :-- |
* | collectionName | String | The name of the collection to get segments info. |
* | timeout? | number | An optional duration of time in millisecond to allow for the RPC. If it is set to undefined, the client keeps waiting until the server responds or error occurs. Default is undefined |
*
*
* @returns
* | Property | Description |
* | :--- | :-- |
* | status | { error_code: number,reason:string } |
* | infos | getPersistentSegmentInfo is the growing segments's information in query cluster. |
*
*
* #### Example
*
* ```
* const res = await getPersistentSegmentInfo({
* collectionName: COLLECTION,
* });
* ```
*/
async getPersistentSegmentInfo(
data: GePersistentSegmentInfoReq
): Promise<GePersistentSegmentInfoResponse> {
if (!data || !data.collectionName) {
throw new Error(ERROR_REASONS.COLLECTION_NAME_IS_REQUIRED);