Share via


Azure Cosmos DB-bifogade filer

GÄLLER FÖR: Nosql Mongodb

Azure Cosmos DB-bifogade filer är särskilda objekt som innehåller referenser till en associerad metadata med en extern blob eller mediefil.

Azure Cosmos DB stöder två typer av bifogade filer:

  • Ohanterade bifogade filer är en omslutning kring en URI-referens till en blob som lagras i en extern tjänst (till exempel Azure Storage, OneDrive osv.). Den här metoden liknar lagring av en URI-egenskap i ett Azure Cosmos DB-standardobjekt.
  • Hanterade bifogade filer är blobar som hanteras och lagras internt av Azure Cosmos DB och exponeras via ett systemgenererat mediaLink.

Anteckning

Bifogade filer är en äldre funktion. Deras support är begränsad för att erbjuda fortsatt funktionalitet om du redan använder den här funktionen.

I stället för att använda bifogade filer rekommenderar vi att du använder Azure Blob Storage som en specialbyggd bloblagringstjänst för att lagra blobdata. Du kan fortsätta att lagra metadata relaterade till blobar, tillsammans med referens-URI-länkar, i Azure Cosmos DB som objektegenskaper. Genom att lagra dessa data i Azure Cosmos DB kan du fråga efter metadata och länkar till blobar som lagras i Azure Blob Storage.

Microsoft har åtagit sig att tillhandahålla minst 36 månaders varsel innan de helt föråldrade bilagorna – som kommer att meddelas vid ett ytterligare datum.

Kända begränsningar

Azure Cosmos DB:s hanterade bifogade filer skiljer sig från dess stöd för standardobjekt – för vilka det erbjuder obegränsad skalbarhet, global distribution och integrering med andra Azure-tjänster.

  • Bifogade filer stöds inte i alla versioner av Azure Cosmos DB SDK:er.
  • Hanterade bifogade filer är begränsade till 2 GB lagringsutrymme per databaskonto.
  • Hanterade bifogade filer är inte kompatibla med Azure Cosmos DB:s globala distribution och replikeras inte mellan regioner.

Anteckning

Azure Cosmos DB för MongoDB version 3.2 använder hanterade bifogade filer för GridFS och dessa omfattas av samma begränsningar.

Vi rekommenderar att utvecklare som använder Funktionen MongoDB GridFS uppgraderar till Azure Cosmos DB för MongoDB version 3.6 eller senare, vilket är frikopplat från bifogade filer och ger en bättre upplevelse. Utvecklare som använder MongoDB GridFS-funktionsuppsättningen bör också överväga att använda Azure Blob Storage – som är specialbyggt för lagring av blobinnehåll och erbjuder utökade funktioner till lägre kostnad jämfört med GridFS.

Migrera bifogade filer till Azure Blob Storage

Vi rekommenderar att du migrerar Azure Cosmos DB-bifogade filer till Azure Blob Storage genom att följa dessa steg:

  1. Kopiera bifogade filer från din Azure Cosmos DB-källcontainer till målcontainern Azure Blob Storage.
  2. Verifiera de uppladdade blobdata i Azure Blob Storage-målcontainern.
  3. Om tillämpligt lägger du till URI-referenser till blobarna som finns i Azure Blob Storage som strängegenskaper i din Azure Cosmos DB-datauppsättning.
  4. Omstrukturera programkoden för att läsa och skriva blobar från den nya Azure Blob Storage containern.

Följande kodexempel visar hur du kopierar bifogade filer från Azure Cosmos DB till Azure Blob Storage som en del av ett migreringsflöde med hjälp av Azure Cosmos DB:s .NET SDK v2 och Azure Blob Storage .NET SDK v12. Se till att ersätta <placeholder values> för Azure Cosmos DB-källkontot och azure Blob Storage-målcontainern.


using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;

namespace attachments
{
    class Program
    {
        private static string cosmosAccount = "<Your_Azure_Cosmos_account_URI>";
        private static string cosmosKey = "<Your_Azure_Cosmos_account_PRIMARY_KEY>";
        private static string cosmosDatabaseName = "<Your_Azure_Cosmos_database>";
        private static string cosmosCollectionName = "<Your_Azure_Cosmos_collection>";
        private static string storageConnectionString = "<Your_Azure_Storage_connection_string>";
        private static string storageContainerName = "<Your_Azure_Storage_container_name>";
        private static DocumentClient cosmosClient = new DocumentClient(new Uri(cosmosAccount), cosmosKey);
        private static BlobServiceClient storageClient = new BlobServiceClient(storageConnectionString);
        private static BlobContainerClient storageContainerClient = storageClient.GetBlobContainerClient(storageContainerName);

        static void Main(string[] args)
        {
            CopyAttachmentsToBlobsAsync().Wait();
        }

        private async static Task CopyAttachmentsToBlobsAsync()
        {
            Console.WriteLine("Copying Azure Cosmos DB Attachments to Azure Blob Storage ...");

            int totalCount = 0;
            string docContinuation = null;

            // Iterate through each item (document in v2) in the Azure Cosmos DB container (collection in v2) to look for attachments.
            do
            {
                FeedResponse<dynamic> response = await cosmosClient.ReadDocumentFeedAsync(
                    UriFactory.CreateDocumentCollectionUri(cosmosDatabaseName, cosmosCollectionName),
                    new FeedOptions
                    {
                        MaxItemCount = -1,
                        RequestContinuation = docContinuation
                    });
                docContinuation = response.ResponseContinuation;

                foreach (Document document in response)
                {
                    string attachmentContinuation = null;
                    PartitionKey docPartitionKey = new PartitionKey(document.Id);

                    // Iterate through each attachment within the item (if any).
                    do
                    {
                        FeedResponse<Attachment> attachments = await cosmosClient.ReadAttachmentFeedAsync(
                            document.SelfLink,
                            new FeedOptions
                            {
                                PartitionKey = docPartitionKey,
                                RequestContinuation = attachmentContinuation
                            }
                        );
                        attachmentContinuation = attachments.ResponseContinuation;

                        foreach (var attachment in attachments)
                        {
                            // Download the attachment in to local memory.
                            MediaResponse content = await cosmosClient.ReadMediaAsync(attachment.MediaLink);

                            byte[] buffer = new byte[content.ContentLength];
                            await content.Media.ReadAsync(buffer, 0, buffer.Length);

                            // Upload the locally buffered attachment to blob storage
                            string blobId = String.Concat(document.Id, "-", attachment.Id);

                            Azure.Response<BlobContentInfo> uploadedBob = await storageContainerClient.GetBlobClient(blobId).UploadAsync(
                                new MemoryStream(buffer, writable: false),
                                true
                            );

                            Console.WriteLine("Copied attachment ... Item Id: {0} , Attachment Id: {1}, Blob Id: {2}", document.Id, attachment.Id, blobId);
                            totalCount++;

                            // Clean up attachment from Azure Cosmos DB.
                            // Warning: please verify you've succesfully migrated attachments to blog storage prior to cleaning up Azure Cosmos DB.
                            // await cosmosClient.DeleteAttachmentAsync(
                            //     attachment.SelfLink,
                            //     new RequestOptions { PartitionKey = docPartitionKey }
                            // );

                            // Console.WriteLine("Cleaned up attachment ... Document Id: {0} , Attachment Id: {1}", document.Id, attachment.Id);
                        }

                    } while (!string.IsNullOrEmpty(attachmentContinuation));
                }
            }
            while (!string.IsNullOrEmpty(docContinuation));

            Console.WriteLine("Finished copying {0} attachments to blob storage", totalCount);
        }
    }
}

Nästa steg