AWS S3:我可以通过更改其密钥来移动桶内的对象吗?



我有一个javascript lambda函数,它由文件上传触发,读取内容,验证,将其中包含的数据记录转换为数组并将数据放入DynamoDB表中。当一切正常时,将文件(S3对象)移动到同一桶中的另一个文件夹中—该函数将原始对象复制到另一个文件夹并删除原始对象。此操作需要花费一些时间,并产生"不必要的"内容。数据传输。有没有可能"修改"?对象键,有效地移动它吗?

Amazon S3没有'rename'或'modify'功能。所有的对象都是不可变的,Key不能被改变——它是对象的唯一标识符。

要"移动"一个对象,正确的过程是先到CopyObject(),然后到DeleteObject()。这将创建一个具有所需Key的对象。

简短回答

不幸的是,您将无法获得性能提升,但您可以使用S3高级API抽象出这两个操作

长回答

AWS S3有两个api

  1. s3是一个高级API
  2. s3api是一个低级API

使用s3 mvapi时,您可以发出命令(使用CLI)来移动或重命名(如果移动到相同的目的地,则使用不同的名称)文件。这个API的构造是为了模仿Linuxmv命令的感觉和结果。

语法:

aws s3 mv [S3ObjectSourcePath] [S3ObjectDestinationPath]
aws s3 mv [S3ObjectSourcePath] [LocalFilePath]
aws s3 mv [LocalFilePath] [S3ObjectSourcePath]

这是一个高级API,基本上做两个操作:

  • s3:ObjectCreated:Copy
  • s3:ObjectRemoved:DeleteMarkerCreated,但为您抽象。

可以通过创建S3事件通知并对这些S3 Bucket事件运行Lambda函数并将接收到的事件设置为记录在CloudWatch Logs中来测试。然后运行mv命令,您将看到成功执行的每个mv命令都将记录上述两个操作。


例子:

  1. 将本地文件移动到S3

    aws s3 mv ~/hello.txt s3://my-bucket/
    

    反应:

    upload: ./hello.txt to s3://my-bucket/hello.txt
    
  2. 在S3上重命名文件(移动到相同位置)

    aws s3 mv s3://my-bucket/file.txt s3://my-bucket/file-moved.txt
    

    反应:

    move: s3://my-bucket/file.txt to s3://my-bucket/file-moved.txt
    
  3. 将文件从S3移动到S3

    aws s3 mv s3://my-bucket/file.txt s3://my-bucket/path/
    

    反应:

    move: s3://my-bucket/file.txt to s3://my-bucket/path/
    
  4. 将S3对象移动到本地文件

    aws s3 mv s3://my-bucket/file.txt ~/file-moved-to-local.txt
    

    反应:

    download: s3://my-bucket/file.txt to ~/file-moved-to-local.txt
    
  5. 递归移动S3对象到本地目录

    # my-bucket contains two files: `file.txt` and `file2.txt`
    aws s3 mv s3://my-bucket . --recursive
    

    反应:

    download: s3://mybucket/file.txt to file.txt
    download: s3://mybucket/file2.txt to file2.txt
    
  6. 递归移动本地文件到S3

    # `localFolder` is a local directory containing two files: `file.txt` and `file2.txt`
    aws s3 mv ~/localFolder s3://my-bucket --recursive
    

    反应:

    upload: s3TestFolder/file.txt to s3://my-bucket/file.txt
    upload: s3TestFolder/file2.txt to s3://my-bucket/file2.txt
    

最新更新