En este capÃtulo, aprenderemos cómo crear una colección. Es como crear una base de datos. Puede crear una colección desde el portal o desde el código utilizando.Net SDK.
Paso 1 – Vaya al panel principal de Azure Portal.
Paso 2 – Seleccione myfirstdb de la lista de bases de datos.
Paso 3 – Haga clic en la opción «Agregar colección» y especifique el ID de la colección. Seleccione un nivel de precios para otra opción.
Paso 4 – Seleccione Estándar S1 y presione Seleccionar → Aceptar.
Como puede ver, MyCollection se ha agregado a myfirstdb.
También puede crear una colección a partir del código utilizando.Net SDK. Echemos un vistazo a los siguientes pasos para agregar colecciones desde el código.
Paso 1 – Abra una aplicación de consola en Visual Studio.
Paso 2 – Para crear una colección, primero obtenga la base de datos myfirstdb por su ID en la tarea CreateDocumentClient.
private static async Task CreateDocumentClient() { // Create a new instance of the DocumentClient using (var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey)) { database = client.CreateDatabaseQuery("SELECT * FROM c WHERE c.id = 'myfirstdb'").AsEnumerable().First(); await CreateCollection(client, "MyCollection1"); await CreateCollection(client, "MyCollection2", "S2"); } }
A continuación se muestra la implementación de la tarea CreateCollection.
private async static Task CreateCollection(DocumentClient client, string collectionId, string offerType = "S1") { Console.WriteLine(); Console.WriteLine("**** Create Collection {0} in {1} ****", collectionId, database.Id); var collectionDefinition = new DocumentCollection { Id = collectionId }; var options = new RequestOptions { OfferType = offerType }; var result = await client.CreateDocumentCollectionAsync(database.SelfLink, collectionDefinition, options); var collection = result.Resource; Console.WriteLine("Created new collection"); ViewCollection(collection); }
Creamos un nuevo objeto DocumentCollection que define una nueva colección con el identificador deseado para el método CreateDocumentCollectionAsync, que también toma un parámetro de opciones, que usamos aquà para establecer el nivel de rendimiento de la nueva colección que llamamos offerType.
Por defecto, este es S1, y dado que no pasamos el OfferType para MyCollection1, esta será la colección S1, y para MyCollection2, pasamos S2, lo que hace que esta colección sea S2 como se muestra arriba.
A continuación se muestra la implementación del método ViewCollection.
private static void ViewCollection(DocumentCollection collection) { Console.WriteLine("Collection ID: {0} ", collection.Id); Console.WriteLine("Resource ID: {0} ", collection.ResourceId); Console.WriteLine("Self Link: {0} ", collection.SelfLink); Console.WriteLine("Documents Link: {0} ", collection.DocumentsLink); Console.WriteLine("UDFs Link: {0} ", collection.UserDefinedFunctionsLink); Console.WriteLine(" StoredProcs Link: {0} ", collection.StoredProceduresLink); Console.WriteLine("Triggers Link: {0} ", collection.TriggersLink); Console.WriteLine("Timestamp: {0} ", collection.Timestamp); }
A continuación se muestra la implementación completa del archivo program.cs para colecciones.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Azure.Documents; using Microsoft.Azure.Documents.Client; using Microsoft.Azure.Documents.Linq; using Newtonsoft.Json; namespace DocumentDBDemo { class Program { private const string EndpointUrl = "https://azuredocdbdemo.documents.azure.com:443/"; private const string AuthorizationKey = "BBhjI0gxdVPdDbS4diTjdloJq7Fp4L5RO/ StTt6UtEufDM78qM2CtBZWbyVwFPSJIm8AcfDu2O+AfV T+TYUnBQ=="; private static Database database; static void Main(string[] args) { try { CreateDocumentClient().Wait(); } catch (Exception e) { Exception baseException = e.GetBaseException(); Console.WriteLine("Error: {0}, Message: {1}", e.Message, baseException.Message); } Console.ReadKey(); } private static async Task CreateDocumentClient() { // Create a new instance of the DocumentClient using (var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey)) { database = client.CreateDatabaseQuery("SELECT * FROM c WHERE c.id = 'myfirstdb'").AsEnumerable().First(); await CreateCollection(client, "MyCollection1"); await CreateCollection(client, "MyCollection2", "S2"); //await CreateDatabase(client); //GetDatabases(client); //await DeleteDatabase(client); //GetDatabases(client); } } private async static Task CreateCollection(DocumentClient client, string collectionId, string offerType = "S1") { Console.WriteLine(); Console.WriteLine("**** Create Collection {0} in {1} ****", collectionId, database.Id); var collectionDefinition = new DocumentCollection { Id = collectionId }; var options = new RequestOptions { OfferType = offerType }; var result = await client.CreateDocumentCollectionAsync(database.SelfLink, collectionDefinition, options); var collection = result.Resource; Console.WriteLine("Created new collection"); ViewCollection(collection); } private static void ViewCollection(DocumentCollection collection) { Console.WriteLine("Collection ID: {0} ", collection.Id); Console.WriteLine("Resource ID: {0} ", collection.ResourceId); Console.WriteLine("Self Link: {0} ", collection.SelfLink); Console.WriteLine("Documents Link: {0} ", collection.DocumentsLink); Console.WriteLine("UDFs Link: {0} ", collection.UserDefinedFunctionsLink); Console.WriteLine("StoredProcs Link: {0} ", collection.StoredProceduresLink); Console.WriteLine("Triggers Link: {0} ", collection.TriggersLink); Console.WriteLine("Timestamp: {0} ", collection.Timestamp); } } }
Cuando se compile y ejecute el código anterior, recibirá el siguiente resultado que contiene toda la información relacionada con la colección.
**** Create Collection MyCollection1 in myfirstdb **** Created new collection Collection ID: MyCollection1 Resource ID: Ic8LAPPvnAA= Self Link: dbs/Ic8LAA==/colls/Ic8LAPPvnAA=/ Documents Link: dbs/Ic8LAA==/colls/Ic8LAPPvnAA=/docs/ UDFs Link: dbs/Ic8LAA==/colls/Ic8LAPPvnAA=/udfs/ StoredProcs Link: dbs/Ic8LAA==/colls/Ic8LAPPvnAA=/sprocs/ Triggers Link: dbs/Ic8LAA==/colls/Ic8LAPPvnAA=/triggers/ Timestamp: 12/10/2015 4:55:36 PM **** Create Collection MyCollection2 in myfirstdb **** Created new collection Collection ID: MyCollection2 Resource ID: Ic8LAKGHDwE= Self Link: dbs/Ic8LAA==/colls/Ic8LAKGHDwE=/ Documents Link: dbs/Ic8LAA==/colls/Ic8LAKGHDwE=/docs/ UDFs Link: dbs/Ic8LAA==/colls/Ic8LAKGHDwE=/udfs/ StoredProcs Link: dbs/Ic8LAA==/colls/Ic8LAKGHDwE=/sprocs/ Triggers Link: dbs/Ic8LAA==/colls/Ic8LAKGHDwE=/triggers/ Timestamp: 12/10/2015 4:55:38 PM
🚫