first commit

This commit is contained in:
Team 2 2025-08-20 05:04:59 +03:30
commit 5dac1642e7
7 changed files with 678 additions and 0 deletions

3
.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
milvus-backup/backup.yaml
milvus-backup/milvus-backup_0.5.8_Linux_x86_64.tar.gz
milvus-backup/milvus-backup

16
.vscode/launch.json vendored Normal file
View File

@ -0,0 +1,16 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Python Debugger: Current File",
"type": "debugpy",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal",
"justMyCode": false
}
]
}

24
README.md Normal file
View File

@ -0,0 +1,24 @@
# check
```
./milvus-backup check
```
# Create a Backup
```
./milvus-backup create -n my_backup
```
# Restore the Backup
```
./milvus-backup restore -n my_backup -s _recover
```
Note: if you want to restore index as well, add --restore_index, like this:
```
./milvus-backup restore --restore_index -n my_backup -s _recover
```
# run fastapi:
./milvus-backup server -p 3071
http://78.38.161.78:3071/api/v1/docs/index.html

201
milvus-backup/LICENSE Normal file
View File

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

214
milvus-backup/README.md Normal file
View File

@ -0,0 +1,214 @@
# Milvus-backup
<div class="column" align="left">
<a href="https://discord.com/invite/8uyFbECzPX"><img height="20" src="https://img.shields.io/badge/Discord-%235865F2.svg?style=for-the-badge&logo=discord&logoColor=white" alt="license"/></a>
<img src="https://img.shields.io/github/license/milvus-io/milvus" alt="license"/>
</div>
Milvus-Backup is a tool that allows users to backup and restore Milvus data. This tool can be utilized either through the command line or an API server.
The Milvus-backup process has negligible impact on the performance of Milvus. Milvus cluster is fully functional and can operate normally while backup and restoration are in progress.
## Compatibility
Always use the **[latest release](https://github.com/zilliztech/milvus-backup/releases)** of `milvus-backup`, which is backward-compatible with Milvus **v2.2 and above**.
> The backup tool is designed to automatically adapt to version differences in Milvus.
> Using the latest version ensures best compatibility, performance, and bug fixes.
The table below shows which Milvus versions can restore backups created from other versions:
| Backup From ↓ \ Restore To → | 2.4 | 2.5 |
|------------------------------|-----|-----|
| 2.2 | ✅ | ✅ |
| 2.3 | ✅ | ✅ |
| 2.4 | ✅ | ✅ |
| 2.5 | ❌ | ✅ |
> ✅ = Supported❌ = Not supported
>
> **Rules:**
> - Backup is supported from **Milvus 2.2+**
> - Restore is supported **to Milvus 2.4+**
> - A backup can only be restored to **the same or newer Milvus versions**
> - For example, backups created in Milvus 2.5 **cannot** be restored to 2.4
## Installation
* Download binary from [release page](https://github.com/zilliztech/milvus-backup/releases). Usually the latest is recommended.
* Use [homebrew](https://brew.sh/) to install on Mac
```shell
brew install zilliztech/tap/milvus-backup
```
## Usage
Milvus-backup provides command line and API server for usage.
### Configuration
In order to use Milvus-Backup, access to Milvus proxy and Minio cluster is required. Configuration settings related to this access can be edited in [backup.yaml](configs/backup.yaml).
> [!NOTE]
>
> Please ensure that the configuration settings for Minio are accurate. There may be variations in the default value of Minio's configuration depending on how Milvus is deployed, either by docker-compose or k8s.
> |field|docker-compose |helm|
> |---|---|---|
> |bucketName|a-bucket|milvus-bucket|
> |rootPath|files|file|
### Command Line
Milvus-backup establish CLI based on cobra. Use the following command to see all the usage.
```
milvus-backup is a backup&restore tool for milvus.
Usage:
milvus-backup [flags]
milvus-backup [command]
Available Commands:
check check if the connects is right.
create create subcommand create a backup.
delete delete subcommand delete backup by name.
get get subcommand get backup by name.
help Help about any command
list list subcommand shows all backup in the cluster.
restore restore subcommand restore a backup.
server server subcommand start milvus-backup RESTAPI server.
Flags:
--config string config YAML file of milvus (default "backup.yaml")
-h, --help help for milvus-backup
Use "milvus-backup [command] --help" for more information about a command.
```
Here is a [demo](docs/user_guide/e2e_demo_cli.md) for a complete backup and restore process.
### API Server
To start the RESTAPI server, use the following command after building:
```shell
./milvus-backup server
```
The server will listen on port 8080 by default. However, you can change it by using the `-p` parameter as shown below:
```shell
./milvus-backup server -p 443
```
We offer a [demo](docs/user_guide/api_demo.md) of the key APIs; however, please refer to the Swagger UI for the most up-to-date usage details, as the demo may occasionally become outdated.
#### swagger UI
We offer access to our Swagger UI, which displays comprehensive information for our APIs. To view it, simply go to
```
http://localhost:8080/api/v1/docs/index.html
```
---
## Backup.yaml Configurations
Below is a summary of the configurations supported in `backup.yaml`:
| **Section** | **Field** | **Description** | **Default/Example** |
|--------------------|---------------------------------|--------------------------------------------------------------------------------------------------------------|-------------------------|
| `log` | `level` | Logging level. Supported: `debug`, `info`, `warn`, `error`, `panic`, `fatal`. | `info` |
| | `console` | Whether to print logs to the console. | `true` |
| | `file.rootPath` | Path to the log file. | `logs/backup.log` |
| `http` | `simpleResponse` | Whether to enable simple HTTP responses. | `true` |
| `milvus` | `address` | Milvus proxy address. | `localhost` |
| | `port` | Milvus proxy port. | `19530` |
| | `user` | Username for Milvus. | `root` |
| | `password` | Password for Milvus. | `Milvus` |
| | `tlsMode` | TLS mode (0: none, 1: one-way, 2: two-way/mtls). | `0` |
| | `caCertPath` | Path to your ca certificate file | `/path/to/certificate` |
| | `serverName ` | Server name | `localhost` |
| | `mtlsCertPath` | Path to your mtls certificate file | `/path/to/certificate` |
| | `mtlsKeyPath ` | Path to your mtls key file | `/path/to/key` |
| `minio` | `storageType` | Storage type for Milvus (e.g., `local`, `minio`, `s3`, `aws`, `gcp`, `ali(aliyun)`, `azure`, `tc(tencent)`, `gcpnative`). Use `gcpnative` for the Google Cloud Platform provider. | `minio` |
| | `address` | MinIO/S3 address. | `localhost` |
| | `port` | MinIO/S3 port. | `9000` |
| | `accessKeyID` | MinIO/S3 access key ID. | `minioadmin` |
| | `secretAccessKey` | MinIO/S3 secret access key. | `minioadmin` |
| | `gcpCredentialJSON` | Path to your GCP credential JSON key file. Used only for the "gcpnative" cloud provider. | `/path/to/json-key-file` |
| | `useSSL` | Whether to use SSL for MinIO/S3. | `false` |
| | `bucketName` | Bucket name in MinIO/S3. | `a-bucket` |
| | `rootPath` | Storage root path in MinIO/S3. | `files` |
| `minio (backup)` | `backupStorageType` | Backup storage type (e.g., `local`, `minio`, `s3`, `aws`, `gcp`, `ali(aliyun)`, `azure`, `tc(tencent)`, `gcpnative`). Use `gcpnative` for the Google Cloud Platform provider. | `minio` |
| | `backupAddress` | Address of backup storagße. | `localhost` |
| | `backupPort` | Port of backup storage. | `9000` |
| | `backupUseSSL` | Whether to use SSL for backup storage. | `false` |
| | `backupAccessKeyID` | Backup storage access key ID. | `minioadmin` |
| | `backupSecretAccessKey` | Backup storage secret access key. | `minioadmin` |
| | `backupGcpCredentialJSON` | Path to your GCP credential JSON key file. Used only for the "gcpnative" cloud provider. | `/path/to/json-key-file` |
| | `backupBucketName` | Bucket name for backups. | `a-bucket` |
| | `backupRootPath` | Root path to store backup data. | `backup` |
| | `crossStorage` | Enable cross-storage backups (e.g., MinIO to AWS S3). | `false` |
| `backup` | `maxSegmentGroupSize` | Maximum segment group size for backups. | `2G` |
| | `parallelism.backupCollection` | Collection-level parallelism for backup. | `4` |
| | `parallelism.copydata` | Thread pool size for copying data. | `128` |
| | `parallelism.restoreCollection` | Collection-level parallelism for restore. | `2` |
| | `keepTempFiles` | Whether to keep temporary files during restore (for debugging). | `false` |
| | `gcPause.enable` | Pause Milvus garbage collection during backup. | `true` |
| | `gcPause.seconds` | Duration to pause garbage collection (in seconds). | `7200` |
| | `gcPause.address` | Address for Milvus garbage collection API. | `http://localhost:9091` |
For more details, refer to the [backup.yaml](configs/backup.yaml) configuration file.
### Advanced feature
1. [Cross Storage Backup](docs/user_guide/cross_storage.md): Data is read from the source storage and written to a different storage through the Milvus-backup service. Such as, S3 -> local, S3 a -> S3 b.
2. [RBAC Backup&Restore](docs/user_guide/rbac.md): Enable backup and restore RBAC meta with extra parameter.
3. [Segment Merging Restore](docs/user_guide/mul_seg_restore.md): In segment merging restore mode (v2 restore), multiple segments are grouped into a single job and restored together. This significantly improves restore performance, especially in scenarios with many small segments.
## Examples
### Syncing Minio Backups to an AWS S3 Bucket
> **NOTE:** The following configuration is an example only. Replace the placeholders with your actual AWS and Minio settings.
To back up Milvus data to an AWS S3 bucket, you need to configure the `backup.yaml` file with the following settings:
```yaml
# Backup storage configs: Configure the storage where you want to save the backup data
backupStorageType: "aws" # Specifies the storage type as AWS S3
backupAddress: s3.{your-aws-region}.amazonaws.com # Address of AWS S3 (replace {your-aws-region} with your bucket's region)
backupPort: 443 # Default port for AWS S3
backupAccessKeyID: <your-access-key-id> # Access key ID for your AWS S3
backupSecretAccessKey: <your-secret-key> # Secret access key for AWS S3
backupGcpCredentialJSON: "/path/to/file" # Path to your GCP credential JSON key file. Used only for the "gcpnative" cloud provider.
backupBucketName: "your-bucket-name" # Bucket name where the backups will be stored
backupRootPath: "backups" # Root path inside the bucket to store backups
backupUseSSL: true # Use SSL for secure connections (Required)
crossStorage: "true" # Required for minio to S3 backups
```
## Development
### Build
For developers, Milvus-backup is easy to contribute to.
Execute `make all` will generate an executable binary `milvus-backup` in the `{project_path}/bin` directory.
### Test
Developers can also test it using an IDE. You can test it using the command line interface:
```shell
make test
```
## License
milvus-backup is licensed under the Apache License, Version 2.0.

View File

@ -0,0 +1,100 @@
# Configures the system log output.
log:
level: info # Only supports debug, info, warn, error, panic, or fatal. Default 'info'.
console: true # whether print log to console
file:
rootPath: "logs/backup.log"
http:
simpleResponse: true
# Zilliz Cloud config.
# If you want to migrate data to Zilliz Cloud, you need to configure the following parameters.
# Otherwise, you can ignore it.
cloud:
address: https://api.cloud.zilliz.com
apikey: <your-api-key>
# milvus proxy address, compatible to milvus.yaml
milvus:
address: localhost
port: 19530
user: "root"
password: "password"
# tls mode values [0, 1, 2]
# 0 is close, 1 is one-way authentication, 2 is mutual authentication
tlsMode: 0
# tls cert path for validate server, will be used when tlsMode is 1 or 2
caCertPath: ""
serverName: ""
# mutual tls cert path, for server to validate client.
# Will be used when tlsMode is 2
# for backward compatibility, if not set, will use tlsmode 1.
# WARN: in future version, if user set tlsmode 2, but not set mtlsCertPath, will cause error.
mtlsCertPath: ""
mtlsKeyPath: ""
# Milvus replicate msg channel name, default is by-dev-replicate-msg
rpcChannelName: "by-dev-replicate-msg"
# Related configuration of minio, which is responsible for data persistence for Milvus.
minio:
# Milvus storage configs, make them the same with milvus config
storageType: "minio" # support storage type: local, minio, s3, aws, gcp, ali(aliyun), azure, tc(tencent), gcpnative
# You can use "gcpnative" for the Google Cloud Platform provider. Uses service account credentials for authentication.
address: localhost # Address of MinIO/S3
port: 9000 # Port of MinIO/S3
region: "" # region of MinIO/S3
accessKeyID: accessKeyID # accessKeyID of MinIO/S3
secretAccessKey: secretAccessKey # MinIO/S3 encryption string
token: "" # token of MinIO/S3
gcpCredentialJSON: "/path/to/json-key-file" # The JSON content contains the gcs service account credentials.
# Used only for the "gcpnative" cloud provider.
useSSL: false # Access to MinIO/S3 with SSL
useIAM: false
iamEndpoint: ""
bucketName: "a-bucket" # Milvus Bucket name in MinIO/S3, make it the same as your milvus instance
rootPath: "files" # Milvus storage root path in MinIO/S3, make it the same as your milvus instance
# Backup storage configs, the storage you want to put the backup data
backupStorageType: "minio" # support storage type: local, minio, s3, aws, gcp, ali(aliyun), azure, tc(tencent)
backupAddress: cdn.d.aiengines.ir # Address of MinIO/S3
backupRegion: "" # region of MinIO/S3
backupPort: 443 # Port of MinIO/S3
backupAccessKeyID: backupAccessKeyID # accessKeyID of MinIO/S3
backupSecretAccessKey: backupSecretAccessKey # MinIO/S3 encryption string
backupToken: "" # token of MinIO/S3
backupGcpCredentialJSON: "/path/to/json-key-file" # The JSON content contains the gcs service account credentials.
# Used only for the "gcpnative" cloud provider.
backupBucketName: "bi-chatbot" # Bucket name to store backup data. Backup data will store to backupBucketName/backupRootPath
backupRootPath: "milvus_backup" # Rootpath to store backup data. Backup data will store to backupBucketName/backupRootPath
backupUseSSL: true # Access to MinIO/S3 with SSL
# If you need to back up or restore data between two different storage systems, direct client-side copying is not supported.
# Set this option to true to enable data transfer through Milvus Backup.
# Note: This option will be automatically set to true if `minio.storageType` and `minio.backupStorageType` differ.
# However, if they are the same but belong to different services, you must manually set this option to `true`.
crossStorage: "true"
backup:
maxSegmentGroupSize: 2G
parallelism:
# collection level parallelism to backup
backupCollection: 4
# thread pool to copy data. reduce it if blocks your storage's network bandwidth
copydata: 128
# Collection level parallelism to restore
restoreCollection: 2
# max number of import job to run in parallel,
# should be less than milvus's config dataCoord.import.maxImportJobNum
importJobNum: 768
# keep temporary files during restore, only use to debug
keepTempFiles: false
# Pause GC during backup through Milvus Http API.
gcPause:
enable: true
address: http://localhost:9091

120
src/milvus_keeper.py Normal file
View File

@ -0,0 +1,120 @@
from pymilvus import MilvusClient, DataType, Function, FunctionType, AnnSearchRequest, WeightedRanker, Collection, connections
import os
import json
import pickle
import pandas
import tqdm
import numpy
import numbers
class MilvusKeeper:
def __init__(self, db_url, token):
self.file_path = os.path.dirname(__file__)
self.client = MilvusClient(url=db_url, token=token)
connections.connect(alias="default", token=token, host=db_url.split("://")[1].split(":")[0], port=db_url.split("://")[1].split(":")[1])
self.base_dir = self.file_path + "/../data/milvus_export"
def get_collections(self):
collection_names = self.client.list_collections()
return collection_names
def make_dir_for_collections(self, collection_names):
os.makedirs(self.base_dir, exist_ok=True)
for coll in collection_names:
coll_dir = os.path.join(self.base_dir, coll)
os.makedirs(coll_dir, exist_ok=True)
def to_serializable(self, obj):
if hasattr(obj, "to_dict"): # بعضی objectهای Milvus این متد رو دارن
return obj.to_dict()
if isinstance(obj, (list, tuple)):
return [self.to_serializable(i) for i in obj]
if isinstance(obj, dict):
return {k: self.to_serializable(v) for k, v in obj.items()}
if isinstance(obj, (int, float, bool, type(None))):
return obj
if isinstance(obj, numbers.Integral): # هر نوع int (حتی numpy.int)
return int(obj)
if isinstance(obj, numbers.Real): # هر نوع float (حتی numpy.float)
return float(obj)
return str(obj) # fallback → هرچی بود string کن
def save_describe_collection(self, collections):
for coll in collections:
# گرفتن توضیحات کلکسیون
coll_info = self.client.describe_collection(coll)
# ذخیره schema در فایل
schema_path = os.path.join(self.base_dir, coll, "schema.json")
with open(schema_path, "w", encoding="utf-8") as f:
json.dump(self.to_serializable(coll_info), f, ensure_ascii=False, indent=2)
def download_one_collection(self, collection_name):
stats = self.client.get_collection_stats(collection_name)
total_rows = stats["row_count"]
collection = Collection(collection_name)
collection.load()
limit = total_rows
batch_size = 1000
query_iterator = collection.query_iterator(batch_size, limit, "", output_fields=["*"])
all_rows = []
for i in tqdm.trange((total_rows-1)//batch_size+1):
res = query_iterator.next()
if len(res) == 0:
print("query iteration finished, close")
query_iterator.close()
break
all_rows.extend(res)
new_all_rows = self.to_serializable(all_rows)
batc = 10000
for i in range(0, len(new_all_rows), batc):
s = i
p = min(i+batc, len(new_all_rows))
df = pandas.DataFrame(new_all_rows[s:p])
df.to_parquet(data_path, index=False)
df = pandas.DataFrame(new_all_rows)
coll_dir = os.path.join(self.base_dir, collection_name)
data_path = os.path.join(coll_dir, "data.parquet")
df.to_parquet(data_path, index=False)
# with open(data_path, "wb") as f:
# pickle.dump(all_rows, f, protocol=pickle.HIGHEST_PROTOCOL)
print(f"Saved {len(all_rows)} rows for collection '{collection_name}' to {data_path}")
def load_collection(self, data_path):
df_loaded = pandas.read_parquet(data_path)
return df_loaded
def save_entities(self, collections):
for collection_name in collections:
self.download_one_collection(collection_name)
def run(self):
collection_names = self.get_collections()
# self.make_dir_for_collections(collection_names)
# self.save_describe_collection(collections)
self.save_entities(collection_names)
def main():
db_url = "http://localhost:19530"
token = "root:bagher_bagher"
milvus_keeper = MilvusKeeper(db_url, token)
milvus_keeper.run()
if __name__ == "__main__":
main()