UNPKG

@zilliz/milvus2-sdk-node

Version:

Official Node.js SDK for [Milvus](https://github.com/milvus-io/milvus) vector database. Provides gRPC and HTTP clients for vector similarity search, metadata filtering, and full collection/index/user management.

1,883 lines • 91.7 kB
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Collection = void 0;
const Database_1 = require("./Database");
const lru_cache_1 = require("lru-cache");
const grpc_js_1 = require("@grpc/grpc-js");
const __1 = require("../");
const formatFormattedGrpcFieldSchema = (schema) => {
    let defaultValue = schema.defaultValue;
    if (defaultValue) {
        defaultValue = {
            [(0, __1.getDataKey)(schema.dataType)]: defaultValue[(0, __1.getDataKey)(schema.dataType, true)],
        };
    }
    return {
        fieldID: schema.fieldID,
        name: schema.name,
        is_primary_key: schema.isPrimaryKey,
        description: schema.description,
        data_type: schema.dataType,
        type_params: schema.typeParams,
        index_params: schema.indexParams,
        autoID: schema.autoID,
        state: schema.state,
        element_type: schema.elementType,
        default_value: defaultValue,
        is_dynamic: schema.isDynamic,
        is_partition_key: schema.isPartitionKey,
        is_clustering_key: schema.isClusteringKey,
        nullable: schema.nullable,
        is_function_output: schema.isFunctionOutput,
        external_field: schema.externalField,
    };
};
const formatGrpcFieldSchema = (field, schemaTypes) => {
    return formatFormattedGrpcFieldSchema((0, __1.formatFieldSchema)(field, schemaTypes));
};
const formatGrpcStructArrayFieldSchema = (field, schemaTypes) => {
    const schema = (0, __1.formatStructArrayFieldSchema)(field, schemaTypes);
    return {
        fieldID: schema.fieldID,
        name: schema.name,
        description: schema.description,
        type_params: schema.typeParams,
        nullable: schema.nullable,
        fields: schema.fields.map(formatFormattedGrpcFieldSchema),
    };
};
const EXTERNAL_COLLECTION_ALTER_SCHEMA_UNSUPPORTED = 'alter collection schema operation is not supported for external collection';
/**
 * @see [collection operation examples](https://github.com/milvus-io/milvus-sdk-node/blob/main/example/Collection.ts)
 */
class Collection extends Database_1.Database {
    constructor() {
        super(...arguments);
        // LRU cache for describe collection
        this.collectionInfoCache = new lru_cache_1.LRUCache({
            max: 256,
            // how long to live in ms, 12h
            ttl: 1000 * 60 * 12,
            // return stale items before removing from cache?
            allowStale: false,
            updateAgeOnGet: false,
            updateAgeOnHas: false,
        });
        /**
         * @deprecated Use alterCollectionProperties instead.
         */
        this.alterCollection = this.alterCollectionProperties;
        // alias
        this.list_collections = this.showCollections;
        // alias
        this.listCollections = this.showCollections;
        // alias
        this.getCollectionStats = this.getCollectionStatistics;
        this.loadCollectionSync = this.loadCollection;
        // alias
        this.drop_collection = this.dropCollection;
        // alias
        this.describeReplicas = this.getReplicas;
    }
    getCollectionInfoCacheKey(data) {
        return `${data.db_name || this.metadata.get(__1.METADATA.DATABASE)}:${data.collection_name}`;
    }
    invalidateCollectionInfo(data) {
        this.collectionInfoCache.delete(this.getCollectionInfoCacheKey(data));
    }
    callAlterCollectionSchema(data, action) {
        return __awaiter(this, void 0, void 0, function* () {
            (0, __1.checkCollectionName)(data);
            const req = {
                collection_name: data.collection_name,
                action,
            };
            if (data.db_name) {
                req.db_name = data.db_name;
            }
            const result = yield (0, __1.promisify)(this.channelPool, 'AlterCollectionSchema', req, data.timeout || this.timeout, data);
            if (!(result === null || result === void 0 ? void 0 : result.alter_status)) {
                throw new Error(__1.ERROR_REASONS.ALTER_COLLECTION_SCHEMA_STATUS_IS_REQUIRED);
            }
            if (result.alter_status.error_code === __1.ErrorCode.SUCCESS) {
                this.invalidateCollectionInfo(data);
            }
            return result;
        });
    }
    /**
     * Creates a new collection in Milvus.
     *
     * @param {CreateCollectionReq} data - The data for the new collection.
     * @param {string} data.collection_name - The name of the new collection.
     * @param {string} [data.description] - The description of the new collection.
     * @param {number} [data.num_partitions] - The number of partitions allowed in the new collection.
     * @param {string} [data.consistency_level] - The consistency level of the new collection. Can be "Strong" (Milvus default), "Session", "Bounded", "Eventually", or "Customized".
     * @param {FieldType[]} data.fields - The fields of the new collection. See [FieldType](https://github.com/milvus-io/milvus-sdk-node/blob/main/milvus/types/Collection.ts#L8) for more details.
     * @param {properties} [data.properties] - An optional object containing key-value pairs of properties for the collection.
     * @param {number} [data.timeout] - An optional duration of time in milliseconds 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 {Promise<ResStatus>} The response status of the operation.
     * @returns {string} status.error_code - The error code of the operation.
     * @returns {string} status.reason - The reason for the error, if any.
     *
     * @example
     * ```
     *  const milvusClient = new milvusClient(MILUVS_ADDRESS);
     *  const resStatus = await milvusClient.createCollection({
     *    collection_name: 'my_collection',
     *    fields: [
     *      {
     *        name: "vector_01",
     *        description: "vector field",
     *        data_type: DataType.FloatVect,
     *        type_params: {
     *          dim: "8"
     *        }
     *      },
     *      {
     *        name: "age",
     *        data_type: DataType.Int64,
     *        autoID: true,
     *        is_primary_key: true,
     *        description: "",
     *      },
     *    ],
     *  });
     * ```
     */
    _createCollection(data) {
        var _a;
        return __awaiter(this, void 0, void 0, function* () {
            // Destructure the data object and set default values for consistency_level and description.
            const { collection_name, consistency_level = data.consistency_level || 'Bounded', num_partitions, } = data || {};
            let fields = data.fields;
            if (data.schema) {
                fields = data.schema;
            }
            // Check if fields and collection_name are present, otherwise throw an error.
            if (!(fields === null || fields === void 0 ? void 0 : fields.length) || !collection_name) {
                throw new Error(__1.ERROR_REASONS.CREATE_COLLECTION_CHECK_PARAMS);
            }
            const isExternalCollection = !!data.external_source;
            if (isExternalCollection &&
                ('auto_id' in data || fields.some(field => field.autoID))) {
                throw new Error(__1.ERROR_REASONS.CREATE_EXTERNAL_COLLECTION_AUTO_ID);
            }
            if (isExternalCollection && fields.some(field => field.is_primary_key)) {
                throw new Error(__1.ERROR_REASONS.CREATE_EXTERNAL_COLLECTION_PRIMARY_KEY);
            }
            // Check if the fields are valid.
            (0, __1.checkCollectionFieldsWithOptions)(fields, { isExternalCollection });
            // if num_partitions is set, validate it
            if (typeof num_partitions !== 'undefined') {
                (0, __1.validatePartitionNumbers)(num_partitions);
            }
            // Get the CollectionSchemaType and FieldSchemaType from the schemaProto object.
            const schemaTypes = {
                collectionSchemaType: this.schemaProto.lookupType(this.protoInternalPath.collectionSchema),
                fieldSchemaType: this.schemaProto.lookupType(this.protoInternalPath.fieldSchema),
                functionSchemaType: this.schemaProto.lookupType(this.protoInternalPath.functionSchema),
                structArrayFieldSchemaType: this.schemaProto.lookupType(this.protoInternalPath.structArrayFieldSchema),
            };
            // Create the payload object with the collection_name, description, and fields.
            // it should follow CollectionSchema in schema.proto
            const payload = (0, __1.formatCollectionSchema)(data, schemaTypes);
            // Create the collectionParams object from the payload.
            const collectionSchema = schemaTypes.collectionSchemaType.create(payload);
            // Encode the collectionParams object to bytes.
            const schemaBytes = schemaTypes.collectionSchemaType
                .encode(collectionSchema)
                .finish();
            // Get the consistency level value from the ConsistencyLevelEnum object.
            const level = (_a = __1.ConsistencyLevelEnum[consistency_level]) !== null && _a !== void 0 ? _a : __1.ConsistencyLevelEnum.Bounded;
            // build the request object
            const req = Object.assign(Object.assign({}, data), { schema: schemaBytes, consistency_level: level, enable_dynamic_field: data.enableDynamicField || data.enable_dynamic_field });
            // if properties is set, parse it to key-value pairs
            if (data.properties) {
                req.properties = (0, __1.parseToKeyValue)(data.properties);
            }
            // Call the promisify function to create the collection.
            // traceid will be automatically extracted from data by promisify
            const createPromise = yield (0, __1.promisify)(this.channelPool, 'CreateCollection', req, data.timeout || this.timeout);
            // Return the promise.
            return createPromise;
        });
    }
    /**
     * Add a new field to an existing collection in Milvus.
     *
     * @param {AddCollectionFieldReq} data - The request parameters.
     * @param {string} data.collection_name - The name of the collection to add the field to.
     * @param {FieldType} data.field - The field schema to be added.
     * @param {number} [data.timeout] - An optional duration of time in milliseconds 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 {Promise<ResStatus>} The result of the operation.
     * @returns {string} status.error_code - The error code of the operation.
     * @returns {string} status.reason - The reason for the error, if any.
     *
     * @example
     * ```
     * const milvusClient = new MilvusClient(MILVUS_ADDRESS);
     * const resStatus = await milvusClient.addCollectionField({
     *   collection_name: 'my_collection',
     *   field: {
     *     name: 'new_field',
     *     data_type: 'Int64',
     *     is_primary_key: false,
     *     description: 'A new field'
     *   }
     * });
     * ```
     */
    addCollectionField(data) {
        var _a;
        return __awaiter(this, void 0, void 0, function* () {
            (0, __1.checkCollectionName)(data);
            const dataType = (0, __1.convertToDataType)(data.field.data_type);
            const elementType = typeof data.field.element_type === 'undefined'
                ? __1.DataType.None
                : (0, __1.convertToDataType)(data.field.element_type);
            const isStructArray = dataType === __1.DataType.Array && elementType === __1.DataType.Struct;
            if (isStructArray) {
                if (data.field.nullable !== true) {
                    throw new Error(__1.ERROR_REASONS.ADD_COLLECTION_STRUCT_FIELD_NULLABLE_REQUIRED);
                }
                const schemaTypes = {
                    fieldSchemaType: this.schemaProto.lookupType(this.protoInternalPath.fieldSchema),
                    structArrayFieldSchemaType: this.schemaProto.lookupType(this.protoInternalPath.structArrayFieldSchema),
                };
                const result = yield (0, __1.promisify)(this.channelPool, 'AddCollectionStructField', Object.assign(Object.assign({ collection_name: data.collection_name }, (data.db_name ? { db_name: data.db_name } : {})), { struct_array_field_schema: formatGrpcStructArrayFieldSchema(data.field, schemaTypes) }), data.timeout || this.timeout, data);
                if (result.error_code === __1.ErrorCode.SUCCESS) {
                    this.invalidateCollectionInfo(data);
                }
                return result;
            }
            if ((0, __1.isVectorType)(dataType) && data.field.nullable !== true) {
                throw new Error(__1.ERROR_REASONS.ADD_COLLECTION_FIELD_VECTOR_NULLABLE_REQUIRED);
            }
            // Get the CollectionSchemaType and FieldSchemaType from the schemaProto object.
            const schemaTypes = {
                fieldSchemaType: this.schemaProto.lookupType(this.protoInternalPath.fieldSchema),
            };
            try {
                const result = yield this.callAlterCollectionSchema(data, {
                    add_request: {
                        field_infos: [
                            {
                                field_schema: formatGrpcFieldSchema(data.field, schemaTypes),
                            },
                        ],
                    },
                });
                if (!((_a = result.alter_status.reason) === null || _a === void 0 ? void 0 : _a.includes(EXTERNAL_COLLECTION_ALTER_SCHEMA_UNSUPPORTED))) {
                    return result.alter_status;
                }
            }
            catch (error) {
                if ((error === null || error === void 0 ? void 0 : error.code) !== grpc_js_1.status.UNIMPLEMENTED) {
                    throw error;
                }
            }
            // Create the payload object with the collection_name, description, and fields.
            // it should follow CollectionSchema in schema.proto
            const payload = (0, __1.formatFieldSchema)(data.field, schemaTypes);
            const schema = schemaTypes.fieldSchemaType.create(payload);
            const schemaBytes = schemaTypes.fieldSchemaType.encode(schema).finish();
            const result = yield (0, __1.promisify)(this.channelPool, 'AddCollectionField', Object.assign(Object.assign({}, data), { schema: schemaBytes }), data.timeout || this.timeout);
            if (result.error_code === __1.ErrorCode.SUCCESS) {
                this.invalidateCollectionInfo(data);
            }
            return result;
        });
    }
    /**
     * Add multiple new fields to an existing collection in Milvus.
     *
     * @param {AddCollectionFieldsReq} data - The request parameters.
     * @param {string} data.collection_name - The name of the collection to add the fields to.
     * @param {FieldType[]} data.fields - Array of field schemas to be added.
     * @param {number} [data.timeout] - An optional duration of time in milliseconds 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 {Promise<ResStatus>} The result of the operation.
     * @returns {string} status.error_code - The error code of the operation.
     * @returns {string} status.reason - The reason for the error, if any.
     *
     * @example
     * ```
     * const milvusClient = new MilvusClient(MILVUS_ADDRESS);
     * const resStatus = await milvusClient.addCollectionFields({
     *   collection_name: 'my_collection',
     *   fields: [
     *     {
     *       name: 'new_field_1',
     *       data_type: 'Int64',
     *       is_primary_key: false,
     *       description: 'First new field'
     *     },
     *     {
     *       name: 'new_field_2',
     *       data_type: 'FloatVector',
     *       dim: 128,
     *       description: 'Second new field'
     *     }
     *   ]
     * });
     * ```
     */
    addCollectionFields(data) {
        return __awaiter(this, void 0, void 0, function* () {
            for (const field of data.fields) {
                const result = yield this.addCollectionField({
                    collection_name: data.collection_name,
                    db_name: data.db_name,
                    field,
                    timeout: data.timeout,
                });
                if (result.error_code !== __1.ErrorCode.SUCCESS) {
                    return result;
                }
            }
            return {
                error_code: __1.ErrorCode.SUCCESS,
                reason: '',
                code: 0,
                extra_info: {},
                retriable: false,
                detail: '',
            };
        });
    }
    /**
     * Checks if a collection exists.
     *
     * @param {HasCollectionReq} data - The request parameters.
     * @param {string} data.collection_name - The name of the collection to check.
     * @param {number} [data.timeout] - An optional duration of time in milliseconds 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 {Promise<BoolResponse>} The response from the server.
     * @returns {string} status.error_code - The error code of the operation.
     * @returns {string} status.reason - The reason for the error, if any.
     * @returns {boolean} value - `true` if the collection exists, `false` otherwise.
     *
     * @example
     * ```
     *  const milvusClient = new milvusClient(MILUVS_ADDRESS);
     *  const res = await milvusClient.hasCollection({ collection_name: 'my_collection' });
     * ```
     */
    hasCollection(data) {
        return __awaiter(this, void 0, void 0, function* () {
            (0, __1.checkCollectionName)(data);
            let response = {
                status: {
                    error_code: 'Success',
                    reason: '',
                    code: 0,
                    extra_info: {},
                    retriable: false,
                    detail: '',
                },
                value: true,
            };
            // avoid to call describe collection, because it has cache
            const res = yield (0, __1.promisify)(this.channelPool, 'DescribeCollection', data, data.timeout || this.timeout);
            if (res.status.error_code !== __1.ErrorCode.SUCCESS) {
                response.value = false;
            }
            return response;
        });
    }
    /**
     * Lists all collections or gets the loading status of a collection.
     *
     * @param {ShowCollectionsReq} data - The request parameters.
     * @param {ShowCollectionsType} [data.type] - The type of collections to show. Can be "All" (default) or "Loaded".
     * @param {string[]} [data.collection_names] - If `type` is "Loaded", Milvus will return `collection_names` along with their in-memory percentages.
     * @param {number} [data.timeout] - An optional duration of time in milliseconds 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 {Promise<ShowCollectionsResponse>} The response from the server.
     * @returns {string} status.error_code - The error code of the operation.
     * @returns {string} status.reason - The reason for the error, if any.
     * @returns {CollectionData[]} data - An array containing information about each collection, including its name, ID, creation timestamp (UTC), and loaded percentage (100 means fully loaded).
     *
     * @example
     * ```
     *  const milvusClient = new milvusClient(MILUVS_ADDRESS);
     *  const res = await milvusClient.showCollections();
     * ```
     */
    showCollections(data) {
        return __awaiter(this, void 0, void 0, function* () {
            const req = {
                type: data ? data.type : __1.ShowCollectionsType.All,
                collection_names: (data === null || data === void 0 ? void 0 : data.collection_names) || [],
            };
            if (data === null || data === void 0 ? void 0 : data.db_name) {
                req.db_name = data.db_name;
            }
            const promise = yield (0, __1.promisify)(this.channelPool, 'ShowCollections', req, (data === null || data === void 0 ? void 0 : data.timeout) || this.timeout);
            const result = [];
            promise.collection_names.forEach((name, index) => {
                result.push({
                    name,
                    id: promise.collection_ids[index],
                    timestamp: promise.created_utc_timestamps[index],
                    loadedPercentage: promise.inMemory_percentages[index],
                });
            });
            promise.data = result;
            return promise;
        });
    }
    /**
     * Modifies collection properties.
     *
     * @param {AlterCollectionReq} data - The request parameters.
     * @param {string} data.collection_name - The name of the collection to modify.
     * @param {Object} data.properties - The properties to modify. For example, to change the TTL, use {"collection.ttl.seconds": 18000}.
     * @param {number} [data.timeout] - An optional duration of time in milliseconds 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 {Promise<ResStatus>} The response status of the operation.
     * @returns {string} status.error_code - The error code of the operation.
     * @returns {string} status.reason - The reason for the error, if any.
     *
     * @example
     * ```
     *  const milvusClient = new milvusClient(MILUVS_ADDRESS);
     *  const resStatus = await milvusClient.alterCollection({
     *    collection_name: 'my-collection',
     *    properties: {"collection.ttl.seconds": 18000}
     *  });
     * ```
     */
    alterCollectionProperties(data) {
        return __awaiter(this, void 0, void 0, function* () {
            (0, __1.checkCollectionName)(data);
            const req = {
                collection_name: data.collection_name,
                properties: (0, __1.parseToKeyValue)(data.properties),
            };
            if (data.db_name) {
                req.db_name = data.db_name;
            }
            const promise = yield (0, __1.promisify)(this.channelPool, 'AlterCollection', req, (data === null || data === void 0 ? void 0 : data.timeout) || this.timeout);
            return promise;
        });
    }
    /**
     * Drops collection properties.
     * Note that this operation only deletes the properties of the collection, not the collection itself.
     * If you want to delete the collection, use the dropCollection method.
     *
     * @param {DropCollectionPropertiesReq} data - The request parameters.
     * @param {string} data.collection_name - The name of the collection to modify.
     * @param {string[]} data.properties - The properties to delete. For example, to delete the TTL, use ["collection.ttl.seconds"].
     * @param {string} [data.db_name] - The name of the database where the collection is located.
     * @param {number} [data.timeout] - An optional duration of time in milliseconds 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 {Promise<ResStatus>} The response status of the operation.
     * @returns {string} status.error_code - The error code of the operation.
     * @returns {string} status.reason - The reason for the error, if any.
     *
     * @example
     * ```
     * const milvusClient = new milvusClient(MILUVS_ADDRESS);
     * const resStatus = await milvusClient.dropCollectionProperties({
     *  collection_name: 'my-collection',
     *  delete_keys: ["collection.ttl.seconds"]
     * });
     * ```
     *
     */
    dropCollectionProperties(data) {
        return __awaiter(this, void 0, void 0, function* () {
            const req = {
                collection_name: data.collection_name,
                properties: [],
                delete_keys: data.properties,
            };
            if (data.db_name) {
                req.db_name = data.db_name;
            }
            const promise = yield (0, __1.promisify)(this.channelPool, 'AlterCollection', Object.assign({}, req), (data === null || data === void 0 ? void 0 : data.timeout) || this.timeout);
            return promise;
        });
    }
    /**
     * Modifies a collection field's properties.
     * Note that this operation only modifies the properties of the field, not the field itself.
     *
     * @param {AlterCollectionFieldPropertiesReq} data - The request parameters.
     * @param {string} data.collection_name - The name of the collection to modify.
     * @param {string} data.field_name - The name of the field to modify.
     * @param {Object} data.properties - The properties to modify. For example, to change field mmap setting and max_length, use { 'mmap.enabled', true, max_length: 128}.
     * @param {string} [data.db_name] - The name of the database where the collection is located.
     * @param {number} [data.timeout] - An optional duration of time in milliseconds 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 {Promise<ResStatus>} The response status of the operation.
     * @returns {string} status.error_code - The error code of the operation.
     * @returns {string} status.reason - The reason for the error, if any.
     *
     * @example
     * ```
     * const milvusClient = new milvusClient(MILUVS_ADDRESS);
     * const resStatus = await milvusClient.alterCollectionField({
     *   collection_name: 'my-collection',
     *   field_name: 'my-field',
     *   properties: {"mmap.enabled": true}
     * });
     * ```
     */
    alterCollectionFieldProperties(data) {
        return __awaiter(this, void 0, void 0, function* () {
            const req = {
                collection_name: data.collection_name,
                field_name: data.field_name,
                properties: (0, __1.parseToKeyValue)(data.properties),
            };
            if (data.db_name) {
                req.db_name = data.db_name;
            }
            const promise = yield (0, __1.promisify)(this.channelPool, 'AlterCollectionField', req, (data === null || data === void 0 ? void 0 : data.timeout) || this.timeout);
            return promise;
        });
    }
    /**
     * Shows the details of a collection, such as its name and schema.
     *
     * @param {DescribeCollectionReq} data - The request parameters.
     * @param {string} data.collection_name - The name of the collection to describe.
     * @param {number} [data.timeout] - An optional duration of time in milliseconds 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 {Promise<DescribeCollectionResponse>} The response from the server.
     * @returns {string} status.error_code - The error code of the operation.
     * @returns {string} status.reason - The reason for the error, if any.
     * @returns {FieldSchema[]} schema - Information of all fields in this collection.
     * @returns {string} collectionID - The ID of the collection.
     *
     * @example
     * ```
     *  const milvusClient = new milvusClient(MILUVS_ADDRESS);
     *  const res = await milvusClient.describeCollection({ collection_name: 'my_collection' });
     * ```
     */
    describeCollection(data) {
        return __awaiter(this, void 0, void 0, function* () {
            (0, __1.checkCollectionName)(data);
            const key = this.getCollectionInfoCacheKey(data);
            // if we have cache return cache data
            if (this.collectionInfoCache.has(key) && data.cache === true) {
                return Promise.resolve(this.collectionInfoCache.get(key));
            }
            // get new data
            const promise = yield (0, __1.promisify)(this.channelPool, 'DescribeCollection', data, data.timeout || this.timeout);
            // check if collection exists before formatting
            if (promise.status.error_code !== __1.ErrorCode.SUCCESS) {
                return promise;
            }
            const results = (0, __1.formatDescribedCol)(promise);
            // update cache
            this.collectionInfoCache.set(key, results);
            return results;
        });
    }
    /**
     * Batch describe collections. Returns schema and details for multiple collections in one call.
     *
     * @param {BatchDescribeCollectionReq} data - The request parameters.
     * @param {string[]} data.collection_names - The names of the collections to describe.
     * @param {string} [data.db_name] - The database name.
     * @param {number[]} [data.collectionIDs] - The IDs of the collections to describe.
     * @param {number} [data.timeout] - An optional duration of time in milliseconds to allow for the RPC.
     *
     * @returns {Promise<BatchDescribeCollectionResponse>} The response from the server.
     * @returns {string} status.error_code - The error code of the operation.
     * @returns {string} status.reason - The reason for the error, if any.
     * @returns {DescribeCollectionResponse[]} responses - Array of describe collection responses.
     *
     * @example
     * ```
     *  const milvusClient = new MilvusClient(MILVUS_ADDRESS);
     *  const res = await milvusClient.batchDescribeCollections({
     *    collection_names: ['collection1', 'collection2'],
     *  });
     * ```
     */
    batchDescribeCollections(data) {
        return __awaiter(this, void 0, void 0, function* () {
            const promise = yield (0, __1.promisify)(this.channelPool, 'BatchDescribeCollection', {
                collection_name: data.collection_names,
                db_name: data.db_name,
                collectionID: data.collectionIDs || [],
            }, data.timeout || this.timeout);
            if (promise.status.error_code !== __1.ErrorCode.SUCCESS || !promise.responses) {
                return promise;
            }
            // format each collection response
            promise.responses = promise.responses.map(__1.formatDescribedCol);
            return promise;
        });
    }
    /**
     * Show the statistics information of a collection.
     *
     * @param {GetCollectionStatisticsReq} data - The request parameters.
     * @param {string} data.collection_name - The name of the collection to get statistics for.
     * @param {number} [data.timeout] - An optional duration of time in milliseconds 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 {Promise<StatisticsResponse>} The response from the server.
     * @returns {string} status.error_code - The error code of the operation.
     * @returns {string} status.reason - The reason for the error, if any.
     * @returns {Object[]} stats - An array of objects, each containing a key-value pair representing a statistic.
     * @returns {Object} data - Transforms every **stats** entry to an object,
     * including schema-version Backfill progress when reported by Milvus (for
     * example, `schema_version_consistent_segments` and
     * `schema_version_total_segments`).
     *
     * @example
     * ```
     *  const milvusClient = new milvusClient(MILUVS_ADDRESS);
     *  const res = await milvusClient.getCollectionStatistics({ collection_name: 'my_collection' });
     * ```
     */
    getCollectionStatistics(data) {
        return __awaiter(this, void 0, void 0, function* () {
            (0, __1.checkCollectionName)(data);
            const promise = yield (0, __1.promisify)(this.channelPool, 'GetCollectionStatistics', data, data.timeout || this.timeout);
            promise.data = (0, __1.formatKeyValueData)(promise.stats, promise.stats.map(({ key }) => key));
            return promise;
        });
    }
    /**
     * Load collection data into query nodes, then you can do vector search on this collection.
     * It's an async function, but you can use showCollections to check loading status.
     *
     * @param {LoadCollectionReq} data - The request parameters.
     * @param {string} data.collection_name - The name of the collection to load.
     * @param {number} [data.replica_number] - The number of replicas.
     * @param {string[]} [data.resource_groups] - The names of the resource groups.
     * @param {number} [data.timeout] - An optional duration of time in milliseconds 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 {Promise<ResStatus>} The response status of the operation.
     * @returns {string} status.error_code - The error code of the operation.
     * @returns {string} status.reason - The reason for the error, if any.
     *
     * @example
     * ```
     *  const milvusClient = new milvusClient(MILUVS_ADDRESS);
     *  const resStatus = await milvusClient.loadCollection({ collection_name: 'my_collection' });
     * ```
     */
    loadCollectionAsync(data) {
        return __awaiter(this, void 0, void 0, function* () {
            (0, __1.checkCollectionName)(data);
            const promise = yield (0, __1.promisify)(this.channelPool, 'LoadCollection', data, data.timeout || this.timeout);
            return promise;
        });
    }
    /**
     * Refresh the loading status of a collection.
     *
     * @param {RefreshLoadReq} data - The request parameters.
     * @param {string} data.collection_name - The name of the collection to refresh.
     * @param {string} [data.db_name] - The name of the database where the collection is located.
     * @param {number} [data.timeout] - An optional duration of time in milliseconds 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 {Promise<ResStatus>} The response status of the operation.
     * @returns {string} status.error_code - The error code of the operation.
     * @returns {string} status.reason - The reason for the error, if any.
     *
     * @example
     * ```
     *  const milvusClient = new milvusClient(MILUVS_ADDRESS);
     *  const resStatus = await milvusClient.refreshLoad({ collection_name: 'my_collection' });
     * ```
     */
    refreshLoad(data) {
        return __awaiter(this, void 0, void 0, function* () {
            return this.loadCollectionAsync(Object.assign(Object.assign({}, data), { refresh: true }));
        });
    }
    /**
     * Same function as loadCollection, but it's a synchronous function.
     * Helps to ensure this collection is loaded.
     *
     * @param {LoadCollectionReq} data - The request parameters.
     * @param {string} data.collection_name - The name of the collection to load.
     * @param {number} [data.replica_number] - The number of replicas.
     * @param {string[]} [data.resource_groups] - The names of the resource groups.
     * @param {number} [data.timeout] - An optional duration of time in milliseconds 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 {Promise<ResStatus>} The response status of the operation.
     * @returns {string} status.error_code - The error code of the operation.
     * @returns {string} status.reason - The reason for the error, if any.
     *
     * @example
     * ```
     *  const milvusClient = new milvusClient(MILUVS_ADDRESS);
     *  const resStatus = await milvusClient.loadCollectionSync({ collection_name: 'my_collection' });
     * ```
     */
    loadCollection(data) {
        return __awaiter(this, void 0, void 0, function* () {
            (0, __1.checkCollectionName)(data);
            const promise = yield (0, __1.promisify)(this.channelPool, 'LoadCollection', data, data.timeout || this.timeout);
            if (promise.error_code !== __1.ErrorCode.SUCCESS) {
                throw new Error(`ErrorCode: ${promise.error_code}. Reason: ${promise.reason}`);
            }
            let loadedPercentage = 0;
            while (Number(loadedPercentage) < 100) {
                const getLoadingProgressParam = {
                    collection_name: data.collection_name,
                };
                if (data.db_name) {
                    getLoadingProgressParam.db_name = data.db_name;
                }
                let res = yield this.getLoadingProgress(getLoadingProgressParam);
                if (res.status.error_code !== __1.ErrorCode.SUCCESS) {
                    throw new Error(`ErrorCode: ${res.status.error_code}. Reason: ${res.status.reason}`);
                }
                loadedPercentage = Number(res.progress);
                // sleep 400ms
                yield (0, __1.sleep)(400);
            }
            return promise;
        });
    }
    /**
     * Release a collection from cache to reduce cache usage.
     * Note that you cannot search while the corresponding collection is unloaded.
     *
     * @param {ReleaseLoadCollectionReq} data - The request parameters.
     * @param {string} data.collection_name - The name of the collection to release.
     * @param {number} [data.timeout] - An optional duration of time in milliseconds 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 {Promise<ResStatus>} The response status of the operation.
     * @returns {string} status.error_code - The error code of the operation.
     * @returns {string} status.reason - The reason for the error, if any.
     *
     * @example
     * ```
     *  const milvusClient = new milvusClient(MILUVS_ADDRESS);
     *  const resStatus = await milvusClient.releaseCollection({ collection_name: 'my_collection' });
     * ```
     */
    releaseCollection(data) {
        return __awaiter(this, void 0, void 0, function* () {
            (0, __1.checkCollectionName)(data);
            const promise = yield (0, __1.promisify)(this.channelPool, 'ReleaseCollection', data, data.timeout || this.timeout);
            return promise;
        });
    }
    /**
     * Rename a collection.
     *
     * @param {RenameCollectionReq} data - The request parameters.
     * @param {string} data.collection_name - The current name of the collection.
     * @param {string} data.new_collection_name - The new name for the collection.
     * @param {string} data.db_name - Optional, the name of the database where the collection is located.
     * @param {string} data.new_db_name - Optional, the name of the database where the new collection will be located.
     * @param {number} [data.timeout] - An optional duration of time in milliseconds 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 {Promise<ResStatus>} The response status of the operation.
     * @returns {string} status.error_code - The error code of the operation.
     * @returns {string} status.reason - The reason for the error, if any.
     *
     * @example
     * ```
     *  const milvusClient = new milvusClient(MILUVS_ADDRESS);
     *  const resStatus = await milvusClient.renameCollection({
     *    collection_name: 'my_collection',
     *    new_collection_name: 'my_new_collection'
     *  });
     * ```
     */
    renameCollection(data) {
        return __awaiter(this, void 0, void 0, function* () {
            const req = {
                oldName: data.collection_name,
                newName: data.new_collection_name,
            };
            // if db_name is set, add it to the request
            if (data.db_name) {
                req.db_name = data.db_name;
            }
            // if new_db_name is set, add it to the request
            if (data.new_db_name) {
                req.newDBName = data.new_db_name;
            }
            const promise = yield (0, __1.promisify)(this.channelPool, 'RenameCollection', req, data.timeout || this.timeout);
            return promise;
        });
    }
    /**
     * Drop a collection. Note that this drops all data in the collection.
     *
     * @param {DropCollectionReq} data - The request parameters.
     * @param {string} data.collection_name - The name of the collection to drop.
     * @param {number} [data.timeout] - An optional duration of time in milliseconds 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 {Promise<ResStatus>} The response status of the operation.
     * @returns {string} status.error_code - The error code of the operation.
     * @returns {string} status.reason - The reason for the error, if any.
     *
     * @example
     * ```
     *  const milvusClient = new milvusClient(MILUVS_ADDRESS);
     *  const resStatus = await milvusClient.dropCollection({ collection_name: 'my_collection' });
     * ```
     */
    dropCollection(data) {
        return __awaiter(this, void 0, void 0, function* () {
            (0, __1.checkCollectionName)(data);
            const promise = yield (0, __1.promisify)(this.channelPool, 'DropCollection', data, data.timeout || this.timeout);
            this.invalidateCollectionInfo(data);
            return promise;
        });
    }
    /**
     * Truncate a collection. This removes all data in the collection but keeps the collection schema.
     *
     * @param {DropCollectionReq} data - The request parameters.
     * @param {string} data.collection_name - The name of the collection to truncate.
     * @param {string} [data.db_name] - The database name.
     * @param {number} [data.timeout] - An optional duration of time in milliseconds to allow for the RPC.
     *
     * @returns {Promise<ResStatus>} The response status of the operation.
     * @returns {string} status.error_code - The error code of the operation.
     * @returns {string} status.reason - The reason for the error, if any.
     *
     * @example
     * ```
     *  const milvusClient = new MilvusClient(MILVUS_ADDRESS);
     *  const resStatus = await milvusClient.truncateCollection({ collection_name: 'my_collection' });
     * ```
     */
    truncateCollection(data) {
        return __awaiter(this, void 0, void 0, function* () {
            (0, __1.checkCollectionName)(data);
            const promise = yield (0, __1.promisify)(this.channelPool, 'TruncateCollection', data, data.timeout || this.timeout);
            return promise;
        });
    }
    /**
     * Create a collection alias, then you can use the alias instead of the collection_name when you perform a vector search.
     *
     * @param {CreateAliasReq} data - The request parameters.
     * @param {string} data.alias - The alias name.
     * @param {string} data.collection_name - The name of the collection.
     * @param {number} [data.timeout] - An optional duration of time in milliseconds 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 {Promise<ResStatus>} The response status of the operation.
     * @returns {string} status.error_code - The error code of the operation.
     * @returns {string} status.reason - The reason for the error, if any.
     *
     * @example
     * ```
     *  const milvusClient = new milvusClient(MILUVS_ADDRESS);
     *  const resStatus = await milvusClient.createAlias({
     *    alias: 'my_collection_alias',
     *    collection_name: 'my_collection',
     *  });
     * ```
     */
    createAlias(data) {
        return __awaiter(this, void 0, void 0, function* () {
            (0, __1.checkCollectionName)(data);
            if (!data.alias) {
                throw new Error(__1.ERROR_REASONS.ALIAS_NAME_IS_REQUIRED);
            }
            const promise = yield (0, __1.promisify)(this.channelPool, 'CreateAlias', data, data.timeout || this.timeout);
            return promise;
        });
    }
    /**
     * Describe a collection alias.
     *
     * @param {DescribeAliasReq} data - The request parameters.
     * @param {string} data.alias - The alias name.
     * @param {string} data.collection_name - The name of the collection.
     * @param {number} [data.timeout] - An optional duration of time in milliseconds 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 {Promise<DescribeAliasResponse>} The response from the server.
     * @returns {string} status.error_code - The error code of the operation.
     * @returns {string} status.reason - The reason for the error, if any.
     * @returns {string} collection - The name of the collection that the alias points to.
     * @returns {string} alias - The alias of the collection.
     *
     * @example
     * ```
     *  const milvusClient = new milvusClient(MILUVS_ADDRESS);
     *  const res = await milvusClient.describeAlias({
     *    alias: 'my_collection_alias',
     *    collection_name: 'my_collection',
     *  });
     * ```
     */
    describeAlias(data) {
        return __awaiter(this, void 0, void 0, function* () {
            (0, __1.checkCollectionName)(data);
            if (!data.alias) {
                throw new Error(__1.ERROR_REASONS.ALIAS_NAME_IS_REQUIRED);
            }
            const promise = yield (0, __1.promisify)(this.channelPool, 'DescribeAlias', data, data.timeout || this.timeout);
            return promise;
        });
    }
    /**
     * List all aliases of a collection.
     *
     * @param {ListAliasesReq} data - The request parameters.
     * @param {string} data.collection_name - The name of the collection.
     * @param {number} [data.timeout] - An optional duration of time in milliseconds 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 {Promise<ListAliasesResponse>} The response from the server.
     * @returns {string} status.error_code - The error code of the operation.
     * @returns {string} status.reason - The reason for the error, if any.
     * @returns {string[]} aliases - The list of aliases of the collection.
     *
     * @example
     * ```
     *  const milvusClient = new milvusClient(MILUVS_ADDRESS);
     *  const res = await milvusClient.listAliases({
     *    collection_name: 'my_collection',
     *  });
     * ```
     */
    listAliases(data) {
        return __awaiter(this, void 0, void 0, function* () {
            (0, __1.checkCollectionName)(data);
            if (!data.collection_name) {
                throw new Error(__1.ERROR_REASONS.COLLECTION_NAME_IS_REQUIRED);
            }
            const promise = yield (0, __1.promisify)(this.channelPool, 'ListAliases', data, data.timeout || this.timeout);
            return promise;
        });
    }
    /**
     * Drop a collection alias.
     *
     * @param {DropAliasReq} data - The request parameters.
     * @param {string} data.alias - The alias name.
     * @param {string} data.collection_name - The name of the collection.
     * @param {number} [data.timeout] - An optional duration of time in milliseconds 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 {Promise<ResStatus>} The response status of the operation.
     * @returns {string} status.error_code - The error code of the operation.
     * @returns {string} status.reason - The reason for the error, if any.
     *
     * @example
     * ```
     *  const milvusClient = new milvusClient(MILUVS_ADDRESS);
     *  const resStatus = await milvusClient.dropAlias({
     *    alias: 'my_collection_alias',
     *    collection_name: 'my_collection',
     *  });
     * ```
     */
    dropAlias(data) {
        return __awaiter(this, void 0, void 0, function* () {
            if (!data.alias) {
                throw new Error(__1.ERROR_REASONS.ALIAS_NAME_IS_REQUIRED);
            }
            const promise = yield (0, __1.promisify)(this.channelPool, 'DropAlias', data, data.timeout || this.timeout);
            return promise;
        });
    }
    /**
     * Alter a collection alias.
     *
     * @param {AlterAliasReq} data - The request parameters.
     * @param {string} data.alias - The alias name.
     * @param {string} data.collection_name - The name of the collection.
     * @param {number} [data.timeout] - An optional duration of time in milliseconds 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 {Promise<ResStatus>} The response status of the operation.
     * @returns {string} status.error_code - The error code of the operation.
     * @returns {string} status.reason - The reason for the error, if any.
     *
     * @example
     * ```
     *  const milvusClient = new milvusClient(MILUVS_ADDRESS);
     *  const resStatus = await milvusClient.alterAlias({
     *    alias: 'my_collection_alias',
     *    collection_name: 'my_collection',
     *  });
     * ```
     */
    alterAlias(data) {
        return __awaiter(this, void 0, void 0, function* () {
            (0, __1.checkCollectionName)(data);
            if (!data.alias) {
                throw new Error(__1.ERROR_REASONS.ALIAS_NAME_IS_REQUIRED);
            }
            const promise = yield (0, __1.promisify)(this.channelPool, 'AlterAlias', data, data.timeout || this.timeout);
            return promise;
        });
    }
    /**
     * Perform compaction on a collection. This operation reduces the storage space used by the collection by removing deleted data and optimizing the data layout.
     *
     * @param {CompactReq} data - The request parameters.
     * @param {string} data.collection_name - The name of the collection to compact.
     * @param {number} [data.timeout] - An optional duration of time in milliseconds 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 {Promise<CompactionResponse>} The response of the operation.
     * @returns {string} status.error_code - The error code of the operation.
     * @returns {string} status.reason - The reason for the error, if any.
     * @returns {string} compactionID - The ID of the compaction operation.
     *
     * @example
     * ```
     *  const milvusClient = new milvusClient(MILUVS_ADDRESS);
     *  const resStatus = await milvusClient.compact({
     *    collection_name: 'my_collection',
     *  });
     * ```
     */
    compact(data) {
        return __awaiter(this, void 0, void 0, function* () {
            (0, __1.checkCollectionName)(data);
            const describeReq = {
                collection_name: data.collection_name,
            };
            if (data.db_name) {
                describeReq.db_name = data.db_name;
            }
            if (typeof data.timeout !== 'undefined') {
                describeReq.timeout = data.timeout;
            }
            const collectionInfo = yield this.describeCollection(describeReq);
            const { timeout } = data, compactionReq = __rest(data, ["timeout"]);
            const res = yield (0, __1.promisify)(this.channelPool, 'ManualCompaction', Object.assign(Object.assign({}, compactionReq), { collectionID: collectionInfo.collectionID }), timeout || this.timeout);
            return res;
        });
    }
    /**
     * Get the compaction state of a targeted compaction id.
     *
     * @param {GetCompactionStateReq} data - The request parameters.
     * @param {number|string} data.compactionID - The ID of the compaction operation, returned by the compact method.
     * @param {number} [data.timeout] - An optional duration of time in milliseconds 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 {Promise<GetCompactionStateResponse>} The response of the operation.
     * @returns {string} status.error_code - The error code of the operation.
     * @returns {string} status.reason - The reason for the error, if any.
     * @returns {string} state - The state of the compaction operation.
     *
     * @example
     * ```
     *  const milvusClient = new milvusClient(MILUVS_ADDRESS);
     *  const resStatus = await milvusClient.getCompactionState({
     *    compactionID: 'your_compaction_id',
     *  });
     * ```
     */
    getCompactionState(data) {
        return __awaiter(this, void 0, void 0, function* () {
            if (!data || !data.compactionID) {
                throw new Error(__1.ERROR_REASONS.COMPACTION_ID_IS_REQUIRED);
            }
            const res = yield (0, __1.promisify)(this.channelPool, 'GetCompactionState', data, data.timeout || this.timeout);
            return res;
        });
    }
    /**
     * Get the compaction states of a targeted compaction id.
     *
     * @param {GetCompactionPlansReq} data - The request parameters.
     * @param {number|string} data.compactionID - The ID of the compaction operation, returned by the compact method.
     * @param {number} [data.timeout] - An optional duration of time in milliseconds 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 {Promise<GetCompactionPlansResponse>} The response of the operation.
     * @returns {string} status.error_code - The error code of the operation.
     * @returns {string} status.reason - The reason for the error, if any.
     * @returns {string} state - The state of the compaction operation.
     *
     * @example
     * ```
     *  const milvusClient = new milvusClient(MILUVS_ADDRESS);
     *  const resStatus = await milvusClient.getCompactionStateWithPlans({
     *    compactionID: 'your_compaction_id',
     *  });
     * ```
     */
    getCompactionStateWithPlans(data) {
        return __awaiter(this, void 0, void 0, function* () {
            if (!data || !data.compactionID) {
                throw new Error(__1.ERROR_REASONS.COMPACTION_ID_IS_REQUIRED);
            }
            const res = yield (0, __1.promisify)(this.channelPool, 'GetCompactionStateWithPlans', data, data.timeout || this.timeout);
            return res;
        });
    }
    /**
     * Get replicas of a collection.
     *
     * @param {GetReplicaReq} data - The request parameters.
     * @param {number|string} data.collectionID - The ID of the collection.
     * @param {boolean} [data.with_shard_nodes] - Whether to include shard nodes information.
     * @param {string} [data.collection_name] - The name of the collection.
     * @param {string} [data.db_name] - The name of the database.
     * @param {number} [data.timeout] - An optional duration of time in milliseconds 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 {Promise<ReplicasResponse>} The response of the operation.
     * @returns {string} status.error_code - The error code of the operation.
     * @returns {string} status.reason - The reason for the error, if any.
     * @returns {ReplicaInfo[]} replicas - An array of replica information.
     *
     * @example
     * ```
     *  const milvusClient = new milvusClient(MILUVS_ADDRESS);
     *  const resStatus = await milvusClient.getReplicas({
     *    collectionID: 'your_collection_id',
     *  });
     * ```
     *
     * @returns
     * ```
     * {
     *  replicas: [
     *     {
     *      partition_ids: [Array],
     *      shard_replicas: [Array],
     *      node_ids: [Array],
     *      replicaID: '436724291187770258',
     *      collectionID: '436777253933154305',
     *      resource_group_name: '__default_resource_group',
     *      num_outbound_node: {}
     *    }
     *  ],
     *  status: { error_code: 'Success', reason: '' }
     * }
     * ```
     */
    getReplicas(data) {
        return __awaiter(this, void 0, void 0, function* () {
            if (!data || !data.collectionID) {
                throw new Error(__1.ERROR_REASONS.COLLECTION_ID_IS_REQUIRED);
            }
            const res = yield (0, __1.promisify)(this.channelPool, 'GetReplicas', data, data.timeout || this.timeout);
            return res;
        });
    }
    /**
     * Get the loading progress of a collection.
     *
     * @param {GetLoadingProgressReq} data - The request parameters.
     * @param {string} data.collection_name - The name of the collection.
     * @param {number} [data.timeout] - An optional duration of time in milliseconds 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 {Promise<GetLoadingProgressResponse>} The response of the operation.
     * @returns {string} status.error_code - The error code of the operation.
     * @returns {string} status.reason - The reason for the error, if any.
     * @returns {number} total_row_num - The total number of rows in the collection.
     * @returns {number} total_loaded_row_num - The total number of loaded rows in the collection.
     *
     * @throws {Error} if `collection_name` property is not present in `data`.
     *
     * @example
     * ```
     *  const milvusClient = new milvusClient(MILUVS_ADDRESS);
     *  const resStatus = await milvusClient.getLoadingProgress({
     *    collection_name: 'my_collection',
     *  });
     * ```
     */
    getLoadingProgress(data) {
        return __awaiter(this, void 0, void 0, function* () {
            if (!data || !data.collection_name) {
                throw new Error(__1.ERROR_REASONS.COLLECTION_NAME_IS_REQUIRED);
            }
            const res = yield (0, __1.promisify)(this.channelPool, 'GetLoadingProgress', data, data.timeout || this.timeout);
            return res;
        });
    }
    /**
     * Get the loading state of a collection.
     *
     * @param {GetLoadStateReq} data - The request parameters.
     * @param {string} data.collection_name - The name of the collection.
     * @param {number} [data.timeout] - An optional duration of time in milliseconds 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 {Promise<GetLoadStateResponse>} The response of the operation.
     * @returns {string} status.error_code - The error code of the operation.
     * @returns {string} status.reason - The reason for the error, if any.
     * @returns {string} state - The loading state of the collection.
     *
     * @throws {Error} if `collection_name` property is not present in `data`.
     *
     * @example
     * ```
     *  const milvusClient = new milvusClient(MILUVS_ADDRESS);
     *  const resStatus = await milvusClient.getLoadState({
     *    collection_name: 'my_collection',
     *  });
     * ```
     */
    getLoadState(data) {
        return __awaiter(this, void 0, void 0, function* () {
            if (!data || !data.collection_name) {
                throw new Error(__1.ERROR_REASONS.COLLECTION_NAME_IS_REQUIRED);
            }
            const res = yield (0, __1.promisify)(this.channelPool, 'GetLoadState', data, data.timeout || this.timeout);
            return res;
        });
    }
    /**
     * Get the primary key field name of a collection.
     *
     * @param {DescribeCollectionReq} data - The request parameters.
     * @param {string} data.collection_name - The name of the collection.
     * @param {number} [data.timeout] - An optional duration of time in milliseconds 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 {Promise<string>} The primary key field name of the collection.
     *
     * @throws {Error} if `collection_name` property is not present in `data`.
     *
     * @example
     * ```
     *  const milvusClient = new milvusClient(MILUVS_ADDRESS);
     *  const pkFieldName = await milvusClient.getPkFieldName({
     *    collection_name: 'my_collection',
     *  });
     * ```
     */
    getPkFieldName(data, desc) {
        return __awaiter(this, void 0, void 0, function* () {
            // get collection info
            const collectionInfo = desc ? desc : yield this.describeCollection(data);
            // pk field
            let pkField = '';
            // extract key information
            for (let i = 0; i < collectionInfo.schema.fields.length; i++) {
                const f = collectionInfo.schema.fields[i];
                // get pk field info
                if (f.is_primary_key) {
                    pkField = f.name;
                    break;
                }
            }
            return pkField;
        });
    }
    /**
     * Get the primary key field type.
     *
     * @param {DescribeCollectionReq} data - The request parameters.
     * @param {string} data.collection_name - The name of the collection.
     * @param {number} [data.timeout] - An optional duration of time in milliseconds 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 {Promise<keyof typeof DataType>} The primary key field type.
     *
     * @throws {Error} if `collection_name` property is not present in `data`.
     *
     * @example
     * ```
     *  const milvusClient = new milvusClient(MILUVS_ADDRESS);
     *  const pkFieldType = await milvusClient.getPkFieldType({
     *    collection_name: 'my_collection',
     *  });
     * ```
     */
    getPkFieldType(data, desc) {
        return __awaiter(this, void 0, void 0, function* () {
            // get collection info
            const collectionInfo = desc ? desc : yield this.describeCollection(data);
            // pk field type
            let pkFieldType = 'Int64';
            // extract key information
            for (let i = 0; i < collectionInfo.schema.fields.length; i++) {
                const f = collectionInfo.schema.fields[i];
                // get pk field type info
                if (f.is_primary_key) {
                    pkFieldType = f.data_type;
                    break;
                }
            }
            return pkFieldType;
        });
    }
    /**
     * Get the primary field
     */
    getPkField(data) {
        return __awaiter(this, void 0, void 0, function* () {
            // get collection info
            const collectionInfo = yield this.describeCollection(data);
            // pk field
            let pkField = collectionInfo.schema.fields[0];
            // extract key information
            for (let i = 0; i < collectionInfo.schema.fields.length; i++) {
                const f = collectionInfo.schema.fields[i];
                // get pk field info
                if (f.is_primary_key) {
                    pkField = f;
                    break;
                }
            }
            return pkField;
        });
    }
    /**
     * Alter collection schema by adding a function-backed output field.
     *
     * For vector function outputs, provide bound-index metadata with an explicit
     * index_type. Milvus creates the bound index atomically with the schema change.
     *
     * @param {AlterCollectionSchemaReq} data - The request parameters.
     * @param {string} data.collection_name - The collection name.
     * @param {FieldType} data.field - The function output field schema.
     * @param {FunctionObject} data.function - The function schema.
     * @param {string} [data.db_name] - The database name.
     * @param {number} [data.timeout] - Optional RPC timeout in milliseconds.
     *
     * @returns {Promise<AlterCollectionSchemaResponse>} The response from Milvus.
     */
    alterCollectionSchema(data) {
        return __awaiter(this, void 0, void 0, function* () {
            (0, __1.checkCollectionName)(data);
            if (!data.field) {
                throw new Error(__1.ERROR_REASONS.FUNCTION_FIELD_SCHEMA_IS_REQUIRED);
            }
            if (!data.function) {
                throw new Error(__1.ERROR_REASONS.FUNCTION_SCHEMA_IS_REQUIRED);
            }
            const schemaTypes = {
                fieldSchemaType: this.schemaProto.lookupType(this.protoInternalPath.fieldSchema),
            };
            return yield this.callAlterCollectionSchema(data, {
                add_request: {
                    field_infos: [
                        {
                            field_schema: formatGrpcFieldSchema(data.field, schemaTypes),
                            index_name: data.index_name || '',
                            extra_params: (0, __1.parseToKeyValue)(data.extra_params, true),
                        },
                    ],
                    func_schema: [(0, __1.formatFunctionSchema)(data.function)],
                },
            });
        });
    }
    /**
     * Add a function-backed vector field and its bound index to an existing collection.
     *
     * BM25 requires a SparseFloatVector output field. MinHash requires a
     * BinaryVector output field. The bound index must provide an explicit
     * index_type and cannot use AUTOINDEX. Milvus backfills existing sealed
     * segments asynchronously through schema-bump compaction; this RPC returns
     * after the schema change is accepted, not after backfill finishes.
     *
     * @param {AddFunctionFieldReq} data - The request parameters.
     * @returns {Promise<ResStatus>} The AlterCollectionSchema alter status.
     */
    addFunctionField(data) {
        var _a;
        return __awaiter(this, void 0, void 0, function* () {
            if (!data.field) {
                throw new Error(__1.ERROR_REASONS.FUNCTION_FIELD_SCHEMA_IS_REQUIRED);
            }
            if (!data.function) {
                throw new Error(__1.ERROR_REASONS.FUNCTION_SCHEMA_IS_REQUIRED);
            }
            const functionType = typeof data.function.type === 'number'
                ? data.function.type
                : ((_a = __1.FunctionType[data.function.type]) !== null && _a !== void 0 ? _a : __1.FunctionType[String(data.function.type).toUpperCase()]);
            if (functionType !== __1.FunctionType.BM25 &&
                functionType !== __1.FunctionType.MINHASH) {
                throw new Error(__1.ERROR_REASONS.ADD_FUNCTION_FIELD_TYPE_NOT_SUPPORTED);
            }
            const fieldType = (0, __1.convertToDataType)(data.field.data_type);
            if ((functionType === __1.FunctionType.BM25 &&
                fieldType !== __1.DataType.SparseFloatVector) ||
                (functionType === __1.FunctionType.MINHASH &&
                    fieldType !== __1.DataType.BinaryVector)) {
                throw new Error(__1.ERROR_REASONS.ADD_FUNCTION_FIELD_OUTPUT_TYPE_NOT_SUPPORTED);
            }
            const extraParams = Object.assign({}, (data.extra_params || {}));
            for (const key of Object.keys(extraParams)) {
                if (typeof extraParams[key] === 'undefined') {
                    delete extraParams[key];
                }
            }
            const nestedParams = extraParams.params;
            let nestedIndexParams;
            if (nestedParams &&
                typeof nestedParams === 'object' &&
                !Array.isArray(nestedParams)) {
                nestedIndexParams = nestedParams;
            }
            else if (typeof nestedParams === 'string') {
                try {
                    const parsed = JSON.parse(nestedParams);
                    if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
                        nestedIndexParams = parsed;
                    }
                }
                catch (_b) {
                    // Leave malformed params for Milvus to validate.
                }
            }
            if (nestedIndexParams &&
                Object.keys(nestedIndexParams).some(key => Object.prototype.hasOwnProperty.call(extraParams, key))) {
                throw new Error(__1.ERROR_REASONS.ADD_FUNCTION_FIELD_DUPLICATED_INDEX_PARAM);
            }
            const indexType = extraParams.index_type || (nestedIndexParams === null || nestedIndexParams === void 0 ? void 0 : nestedIndexParams.index_type);
            if (typeof indexType !== 'string' || indexType.length === 0) {
                throw new Error(__1.ERROR_REASONS.ADD_FUNCTION_FIELD_INDEX_TYPE_IS_REQUIRED);
            }
            if (indexType === __1.IndexType.AUTOINDEX) {
                throw new Error(__1.ERROR_REASONS.ADD_FUNCTION_FIELD_AUTOINDEX_NOT_SUPPORTED);
            }
            const result = yield this.alterCollectionSchema(Object.assign(Object.assign({}, data), { extra_params: extraParams }));
            return result.alter_status;
        });
    }
    /**
     * Drop a field from an existing collection by name or ID.
     *
     * @param {DropCollectionFieldReq} data - The request parameters.
     * @returns {Promise<ResStatus>} The AlterCollectionSchema alter status.
     */
    dropCollectionField(data) {
        return __awaiter(this, void 0, void 0, function* () {
            (0, __1.checkCollectionName)(data);
            const validFieldName = typeof data.field_name === 'string' && data.field_name.length > 0;
            const validFieldID = (typeof data.field_id === 'number' &&
                Number.isSafeInteger(data.field_id) &&
                data.field_id > 0) ||
                (typeof data.field_id === 'string' &&
                    /^[1-9]\d*$/.test(data.field_id) &&
                    BigInt(data.field_id) <= BigInt('9223372036854775807'));
            if (validFieldName === validFieldID) {
                throw new Error(__1.ERROR_REASONS.DROP_COLLECTION_FIELD_IDENTIFIER_IS_REQUIRED);
            }
            const result = yield this.callAlterCollectionSchema(data, {
                drop_request: validFieldName
                    ? { field_name: data.field_name }
                    : { field_id: data.field_id },
            });
            return result.alter_status;
        });
    }
    /**
     * Drop a function and its output fields and indexes from a collection.
     *
     * @param {DropFunctionFieldReq} data - The request parameters.
     * @returns {Promise<ResStatus>} The AlterCollectionSchema alter status.
     */
    dropFunctionField(data) {
        return __awaiter(this, void 0, void 0, function* () {
            (0, __1.checkCollectionName)(data);
            if (!data.function_name) {
                throw new Error(__1.ERROR_REASONS.FUNCTION_NAME_IS_REQUIRED);
            }
            const result = yield this.callAlterCollectionSchema(data, {
                drop_request: {
                    function_name: data.function_name,
                    drop_function_output_fields: true,
                },
            });
            return result.alter_status;
        });
    }
    /**
     * Add a function to a collection.
     *
     * @deprecated Use addFunctionField instead.
     *
     * @param {AddCollectionFunctionReq} data - The request parameters.
     * @param {string} data.collection_name - The name of the collection.
     * @param {FunctionObject} data.function - The function schema to be added.
     * @param {string} [data.db_name] - The name of the database where the collection is located.
     * @param {number} [data.timeout] - An optional duration of time in milliseconds 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 {Promise<ResStatus>} The response status of the operation.
     * @returns {string} status.error_code - The error code of the operation.
     * @returns {string} status.reason - The reason for the error, if any.
     *
     * @example
     * ```
     * const milvusClient = new MilvusClient(MILVUS_ADDRESS);
     * const resStatus = await milvusClient.addCollectionFunction({
     *   collection_name: 'my_collection',
     *   function: {
     *     name: 'my_function',
     *     description: 'A custom function',
     *     type: FunctionType.Rerank,
     *     input_field_names: ['field1', 'field2'],
     *     output_field_names: ['output_field'],
     *     params: { key: 'value' }
     *   }
     * });
     * ```
     */
    addCollectionFunction(data) {
        return __awaiter(this, void 0, void 0, function* () {
            (0, __1.checkCollectionName)(data);
            if (!data.function) {
                throw new Error(__1.ERROR_REASONS.FUNCTION_SCHEMA_IS_REQUIRED);
            }
            const functionSchema = (0, __1.formatFunctionSchema)(data.function);
            const req = {
                collection_name: data.collection_name,
                functionSchema: functionSchema,
            };
            if (data.db_name) {
                req.db_name = data.db_name;
            }
            return yield (0, __1.promisify)(this.channelPool, 'AddCollectionFunction', req, data.timeout || this.timeout);
        });
    }
    /**
     * Alter a function in a collection.
     *
     * @param {AlterCollectionFunctionReq} data - The request parameters.
     * @param {string} data.collection_name - The name of the collection.
     * @param {string} data.function_name - The name of the function to alter.
     * @param {FunctionObject} data.function - The updated function schema.
     * @param {string} [data.db_name] - The name of the database where the collection is located.
     * @param {number} [data.timeout] - An optional duration of time in milliseconds 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 {Promise<ResStatus>} The response status of the operation.
     * @returns {string} status.error_code - The error code of the operation.
     * @returns {string} status.reason - The reason for the error, if any.
     *
     * @example
     * ```
     * const milvusClient = new MilvusClient(MILVUS_ADDRESS);
     * const resStatus = await milvusClient.alterCollectionFunction({
     *   collection_name: 'my_collection',
     *   function_name: 'my_function',
     *   function: {
     *     name: 'my_function',
     *     description: 'Updated function description',
     *     type: FunctionType.Rerank,
     *     input_field_names: ['field1', 'field2'],
     *     output_field_names: ['output_field'],
     *     params: { key: 'updated_value' }
     *   }
     * });
     * ```
     */
    alterCollectionFunction(data) {
        return __awaiter(this, void 0, void 0, function* () {
            (0, __1.checkCollectionName)(data);
            if (!data.function_name) {
                throw new Error(__1.ERROR_REASONS.FUNCTION_NAME_IS_REQUIRED);
            }
            if (!data.function) {
                throw new Error(__1.ERROR_REASONS.FUNCTION_SCHEMA_IS_REQUIRED);
            }
            const functionSchema = (0, __1.formatFunctionSchema)(data.function);
            const req = {
                collection_name: data.collection_name,
                function_name: data.function_name,
                functionSchema: functionSchema,
            };
            if (data.db_name) {
                req.db_name = data.db_name;
            }
            return yield (0, __1.promisify)(this.channelPool, 'AlterCollectionFunction', req, data.timeout || this.timeout);
        });
    }
    /**
     * Drop a function from a collection.
     *
     * @deprecated Use dropFunctionField instead.
     *
     * @param {DropCollectionFunctionReq} data - The request parameters.
     * @param {string} data.collection_name - The name of the collection.
     * @param {string} data.function_name - The name of the function to drop.
     * @param {string} [data.db_name] - The name of the database where the collection is located.
     * @param {number} [data.timeout] - An optional duration of time in milliseconds 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 {Promise<ResStatus>} The response status of the operation.
     * @returns {string} status.error_code - The error code of the operation.
     * @returns {string} status.reason - The reason for the error, if any.
     *
     * @example
     * ```
     * const milvusClient = new MilvusClient(MILVUS_ADDRESS);
     * const resStatus = await milvusClient.dropCollectionFunction({
     *   collection_name: 'my_collection',
     *   function_name: 'my_function'
     * });
     * ```
     */
    dropCollectionFunction(data) {
        return __awaiter(this, void 0, void 0, function* () {
            (0, __1.checkCollectionName)(data);
            if (!data.function_name) {
                throw new Error(__1.ERROR_REASONS.FUNCTION_NAME_IS_REQUIRED);
            }
            const req = {
                collection_name: data.collection_name,
                function_name: data.function_name,
            };
            if (data.db_name) {
                req.db_name = data.db_name;
            }
            return yield (0, __1.promisify)(this.channelPool, 'DropCollectionFunction', req, data.timeout || this.timeout);
        });
    }
    /**
     * Trigger a data refresh for an external collection.
     *
     * @param {RefreshExternalCollectionReq} data - The request parameters.
     * @param {string} data.collection_name - The external collection to refresh.
     * @param {string} [data.external_source] - Optional new external source path.
     * @param {string} [data.external_spec] - Optional new external spec configuration.
     * @param {string} [data.db_name] - The database name.
     * @param {number} [data.timeout] - An optional duration of time in milliseconds to allow for the RPC.
     *
     * @returns {Promise<RefreshExternalCollectionResponse>} The refresh job response.
     */
    refreshExternalCollection(data) {
        return __awaiter(this, void 0, void 0, function* () {
            (0, __1.checkCollectionName)(data);
            return yield (0, __1.promisify)(this.channelPool, 'RefreshExternalCollection', data, data.timeout || this.timeout);
        });
    }
    /**
     * Get the progress of an external collection refresh job.
     *
     * @param {GetRefreshExternalCollectionProgressReq} data - The request parameters.
     * @param {number|string} data.job_id - The job ID returned by refreshExternalCollection().
     * @param {number} [data.timeout] - An optional duration of time in milliseconds to allow for the RPC.
     *
     * @returns {Promise<GetRefreshExternalCollectionProgressResponse>} The refresh job progress response.
     */
    getRefreshExternalCollectionProgress(data) {
        return __awaiter(this, void 0, void 0, function* () {
            if (!data || typeof data.job_id === 'undefined') {
                throw new Error('The `job_id` property is missing.');
            }
            return yield (0, __1.promisify)(this.channelPool, 'GetRefreshExternalCollectionProgress', data, data.timeout || this.timeout);
        });
    }
    /**
     * List external collection refresh jobs.
     *
     * @param {ListRefreshExternalCollectionJobsReq} data - The request parameters.
     * @param {string} [data.collection_name] - Optional collection name filter.
     * @param {string} [data.db_name] - Optional database name filter.
     * @param {number} [data.timeout] - An optional duration of time in milliseconds to allow for the RPC.
     *
     * @returns {Promise<ListRefreshExternalCollectionJobsResponse>} The refresh jobs response.
     */
    listRefreshExternalCollectionJobs(data = {}) {
        return __awaiter(this, void 0, void 0, function* () {
            return yield (0, __1.promisify)(this.channelPool, 'ListRefreshExternalCollectionJobs', data, data.timeout || this.timeout);
        });
    }
    /**
     * Create a snapshot for a collection.
     *
     * @param {CreateSnapshotReq} data - The request parameters.
     * @param {string} data.snapshot_name - The snapshot name.
     * @param {string} data.collection_name - The collection to snapshot.
     * @param {string} [data.db_name] - The database name.
     * @param {string} [data.description] - Optional snapshot description.
     * @param {number|string} [data.compaction_protection_seconds] - Duration to protect referenced segments from compaction.
     * @param {number} [data.timeout] - An optional duration of time in milliseconds to allow for the RPC.
     *
     * @returns {Promise<ResStatus>} The response status of the operation.
     */
    createSnapshot(data) {
        return __awaiter(this, void 0, void 0, function* () {
            (0, __1.checkCollectionName)(data);
            if (!data.snapshot_name) {
                throw new Error('The `snapshot_name` property is missing.');
            }
            const { snapshot_name, timeout } = data, rest = __rest(data, ["snapshot_name", "timeout"]);
            const req = Object.assign(Object.assign({}, rest), { name: snapshot_name });
            return yield (0, __1.promisify)(this.channelPool, 'CreateSnapshot', req, timeout || this.timeout);
        });
    }
    /**
     * Drop a snapshot.
     *
     * @param {DropSnapshotReq} data - The request parameters.
     * @param {string} data.snapshot_name - The snapshot name.
     * @param {string} data.collection_name - The collection the snapshot belongs to.
     * @param {string} [data.db_name] - The database name.
     * @param {number} [data.timeout] - An optional duration of time in milliseconds to allow for the RPC.
     *
     * @returns {Promise<ResStatus>} The response status of the operation.
     */
    dropSnapshot(data) {
        return __awaiter(this, void 0, void 0, function* () {
            (0, __1.checkCollectionName)(data);
            if (!data.snapshot_name) {
                throw new Error('The `snapshot_name` property is missing.');
            }
            const { snapshot_name, timeout } = data, rest = __rest(data, ["snapshot_name", "timeout"]);
            const req = Object.assign(Object.assign({}, rest), { name: snapshot_name });
            return yield (0, __1.promisify)(this.channelPool, 'DropSnapshot', req, timeout || this.timeout);
        });
    }
    /**
     * List snapshots for a collection.
     *
     * @param {ListSnapshotsReq} data - The request parameters.
     * @param {string} data.collection_name - The collection name.
     * @param {string} [data.db_name] - The database name.
     * @param {number} [data.timeout] - An optional duration of time in milliseconds to allow for the RPC.
     *
     * @returns {Promise<ListSnapshotsResponse>} The list snapshots response.
     */
    listSnapshots(data) {
        return __awaiter(this, void 0, void 0, function* () {
            (0, __1.checkCollectionName)(data);
            return yield (0, __1.promisify)(this.channelPool, 'ListSnapshots', data, data.timeout || this.timeout);
        });
    }
    /**
     * Describe a snapshot.
     *
     * @param {DescribeSnapshotReq} data - The request parameters.
     * @param {string} data.snapshot_name - The snapshot name.
     * @param {string} data.collection_name - The collection the snapshot belongs to.
     * @param {string} [data.db_name] - The database name.
     * @param {number} [data.timeout] - An optional duration of time in milliseconds to allow for the RPC.
     *
     * @returns {Promise<DescribeSnapshotResponse>} The snapshot description response.
     */
    describeSnapshot(data) {
        return __awaiter(this, void 0, void 0, function* () {
            (0, __1.checkCollectionName)(data);
            if (!data.snapshot_name) {
                throw new Error('The `snapshot_name` property is missing.');
            }
            const { snapshot_name, timeout } = data, rest = __rest(data, ["snapshot_name", "timeout"]);
            const req = Object.assign(Object.assign({}, rest), { name: snapshot_name });
            return yield (0, __1.promisify)(this.channelPool, 'DescribeSnapshot', req, timeout || this.timeout);
        });
    }
    /**
     * Restore a snapshot into a target collection.
     *
     * @param {RestoreSnapshotReq} data - The request parameters.
     * @param {string} data.snapshot_name - The snapshot name.
     * @param {string} data.source_collection_name - The source collection name.
     * @param {string} data.target_collection_name - The target collection name.
     * @param {string} [data.source_db_name] - The source database name.
     * @param {string} [data.target_db_name] - The target database name.
     * @param {number} [data.timeout] - An optional duration of time in milliseconds to allow for the RPC.
     *
     * @returns {Promise<RestoreSnapshotResponse>} The restore job response.
     */
    restoreSnapshot(data) {
        return __awaiter(this, void 0, void 0, function* () {
            if (!data || !data.snapshot_name) {
                throw new Error('The `snapshot_name` property is missing.');
            }
            if (!data.source_collection_name) {
                throw new Error('The `source_collection_name` property is missing.');
            }
            if (!data.target_collection_name) {
                throw new Error('The `target_collection_name` property is missing.');
            }
            const { snapshot_name, source_collection_name, source_db_name, timeout } = data, rest = __rest(data, ["snapshot_name", "source_collection_name", "source_db_name", "timeout"]);
            const req = Object.assign(Object.assign({}, rest), { name: snapshot_name, db_name: source_db_name, collection_name: source_collection_name });
            return yield (0, __1.promisify)(this.channelPool, 'RestoreSnapshot', req, timeout || this.timeout);
        });
    }
    /**
     * Get the state of a restore snapshot job.
     *
     * @param {GetRestoreSnapshotStateReq} data - The request parameters.
     * @param {number|string} data.job_id - The restore job ID.
     * @param {number} [data.timeout] - An optional duration of time in milliseconds to allow for the RPC.
     *
     * @returns {Promise<GetRestoreSnapshotStateResponse>} The restore job state response.
     */
    getRestoreSnapshotState(data) {
        return __awaiter(this, void 0, void 0, function* () {
            if (!data || typeof data.job_id === 'undefined') {
                throw new Error('The `job_id` property is missing.');
            }
            return yield (0, __1.promisify)(this.channelPool, 'GetRestoreSnapshotState', data, data.timeout || this.timeout);
        });
    }
    /**
     * List restore snapshot jobs.
     *
     * @param {ListRestoreSnapshotJobsReq} data - The request parameters.
     * @param {string} [data.collection_name] - Optional target collection name filter.
     * @param {string} [data.db_name] - Optional database name filter.
     * @param {number} [data.timeout] - An optional duration of time in milliseconds to allow for the RPC.
     *
     * @returns {Promise<ListRestoreSnapshotJobsResponse>} The restore jobs response.
     */
    listRestoreSnapshotJobs(data = {}) {
        return __awaiter(this, void 0, void 0, function* () {
            return yield (0, __1.promisify)(this.channelPool, 'ListRestoreSnapshotJobs', data, data.timeout || this.timeout);
        });
    }
    /**
     * Pin snapshot data to prevent garbage collection while it is being copied out.
     *
     * @param {PinSnapshotDataReq} data - The request parameters.
     * @param {string} data.snapshot_name - The snapshot name.
     * @param {string} data.collection_name - The collection the snapshot belongs to.
     * @param {string} [data.db_name] - The database name.
     * @param {number|string} [data.ttl_seconds] - Optional pin TTL in seconds.
     * @param {number} [data.timeout] - An optional duration of time in milliseconds to allow for the RPC.
     *
     * @returns {Promise<PinSnapshotDataResponse>} The pin response.
     */
    pinSnapshotData(data) {
        return __awaiter(this, void 0, void 0, function* () {
            (0, __1.checkCollectionName)(data);
            if (!data.snapshot_name) {
                throw new Error('The `snapshot_name` property is missing.');
            }
            const { snapshot_name, timeout } = data, rest = __rest(data, ["snapshot_name", "timeout"]);
            const req = Object.assign(Object.assign({}, rest), { name: snapshot_name });
            return yield (0, __1.promisify)(this.channelPool, 'PinSnapshotData', req, timeout || this.timeout);
        });
    }
    /**
     * Release a snapshot data pin.
     *
     * @param {UnpinSnapshotDataReq} data - The request parameters.
     * @param {number|string} data.pin_id - The pin ID returned by pinSnapshotData().
     * @param {number} [data.timeout] - An optional duration of time in milliseconds to allow for the RPC.
     *
     * @returns {Promise<ResStatus>} The response status of the operation.
     */
    unpinSnapshotData(data) {
        return __awaiter(this, void 0, void 0, function* () {
            if (!data || typeof data.pin_id === 'undefined') {
                throw new Error('The `pin_id` property is missing.');
            }
            return yield (0, __1.promisify)(this.channelPool, 'UnpinSnapshotData', data, data.timeout || this.timeout);
        });
    }
}
exports.Collection = Collection;
//# sourceMappingURL=Collection.js.map