SE APLICA A:
NoSQL
La API para NoSQL en Azure Cosmos DB admite el registro e invocación de procedimientos almacenados, desencadenadores y funciones definidas por el usuario (UDF) escritas en JavaScript. Después de que defina uno o varios procedimientos, desencadenadores y funciones definidas por el usuario, puede cargarlos y verlos en Azure Portal mediante Data Explorer.
Puede usar el SDK de API para NoSQL en varias plataformas, como los SDK de .NET v2 (heredado), .NET v3, Java, JavaScript o Python para realizar estas tareas. Si no ha trabajado con uno de estos SDK antes, consulte el artículo Inicio rápido para ver el SDK adecuado:
Importante
En los ejemplos de código siguientes se supone que ya tiene las variables client
y container
. Si necesita crear esas variables, consulte el inicio rápido adecuado para la plataforma.
Ejecución de procedimientos almacenados
Los procedimientos almacenados se escriben con JavaScript. Pueden crear, actualizar, leer, consultar y eliminar elementos dentro de un contenedor de Azure Cosmos DB. Para obtener más información, vea Cómo escribir procedimientos almacenados.
Los ejemplos siguientes muestran cómo registrar y llamar a un procedimiento almacenado mediante los SDK de Azure Cosmos DB. Para el origen de este procedimiento almacenado, guardado como spCreateToDoItem.js, consulte Creación de elementos mediante procedimientos almacenados.
Nota:
Para los contenedores con particiones, al ejecutar un procedimiento almacenado, debe proporcionar un valor de clave de partición en las opciones de solicitud. Los procedimientos almacenados siempre se limitan a una clave de partición. Los elementos que tienen un valor de clave de partición diferente no están visibles para el procedimiento almacenado. Este principio se aplica también a los desencadenadores.
El siguiente ejemplo muestra cómo registrar un procedimiento almacenado con el SDK de .NET v2:
string storedProcedureId = "spCreateToDoItems";
StoredProcedure newStoredProcedure = new StoredProcedure
{
Id = storedProcedureId,
Body = File.ReadAllText($@"..\js\{storedProcedureId}.js")
};
Uri containerUri = UriFactory.CreateDocumentCollectionUri("myDatabase", "myContainer");
var response = await client.CreateStoredProcedureAsync(containerUri, newStoredProcedure);
StoredProcedure createdStoredProcedure = response.Resource;
El siguiente código muestra cómo llamar a un procedimiento almacenado con el SDK de .NET v2:
dynamic[] newItems = new dynamic[]
{
new {
category = "Personal",
name = "Groceries",
description = "Pick up strawberries",
isComplete = false
},
new {
category = "Personal",
name = "Doctor",
description = "Make appointment for check up",
isComplete = false
}
};
Uri uri = UriFactory.CreateStoredProcedureUri("myDatabase", "myContainer", "spCreateToDoItem");
RequestOptions options = new RequestOptions { PartitionKey = new PartitionKey("Personal") };
var result = await client.ExecuteStoredProcedureAsync<string>(uri, options, new[] { newItems });
El siguiente ejemplo muestra cómo registrar un procedimiento almacenado con el SDK de .NET v3:
string storedProcedureId = "spCreateToDoItems";
StoredProcedureResponse storedProcedureResponse = await client.GetContainer("myDatabase", "myContainer").Scripts.CreateStoredProcedureAsync(new StoredProcedureProperties
{
Id = storedProcedureId,
Body = File.ReadAllText($@"..\js\{storedProcedureId}.js")
});
El siguiente código muestra cómo llamar a un procedimiento almacenado con el SDK de .NET v3:
dynamic[] newItems = new dynamic[]
{
new {
category = "Personal",
name = "Groceries",
description = "Pick up strawberries",
isComplete = false
},
new {
category = "Personal",
name = "Doctor",
description = "Make appointment for check up",
isComplete = false
}
};
var result = await client.GetContainer("database", "container").Scripts.ExecuteStoredProcedureAsync<string>("spCreateToDoItem", new PartitionKey("Personal"), new[] { newItems });
El siguiente es un ejemplo de cómo registrar un procedimiento almacenado con el SDK de Java:
CosmosStoredProcedureProperties definition = new CosmosStoredProcedureProperties(
"spCreateToDoItems",
Files.readString(Paths.get("createToDoItems.js"))
);
CosmosStoredProcedureResponse response = container
.getScripts()
.createStoredProcedure(definition);
El siguiente código muestra cómo llamar a un procedimiento almacenado con el SDK de Java:
CosmosStoredProcedure sproc = container
.getScripts()
.getStoredProcedure("spCreateToDoItems");
List<Object> items = new ArrayList<Object>();
ToDoItem firstItem = new ToDoItem();
firstItem.category = "Personal";
firstItem.name = "Groceries";
firstItem.description = "Pick up strawberries";
firstItem.isComplete = false;
items.add(firstItem);
ToDoItem secondItem = new ToDoItem();
secondItem.category = "Personal";
secondItem.name = "Doctor";
secondItem.description = "Make appointment for check up";
secondItem.isComplete = true;
items.add(secondItem);
CosmosStoredProcedureRequestOptions options = new CosmosStoredProcedureRequestOptions();
options.setPartitionKey(
new PartitionKey("Personal")
);
CosmosStoredProcedureResponse response = sproc.execute(
items,
options
);
El siguiente es un ejemplo de cómo registrar un procedimiento almacenado con el SDK de JavaScript:
const container = client.database("myDatabase").container("myContainer");
const sprocId = "spCreateToDoItems";
await container.scripts.storedProcedures.create({
id: sprocId,
body: require(`../js/${sprocId}`)
});
El siguiente código muestra cómo llamar a un procedimiento almacenado con el SDK de JavaScript:
const newItem = [{
category: "Personal",
name: "Groceries",
description: "Pick up strawberries",
isComplete: false
}];
const container = client.database("myDatabase").container("myContainer");
const sprocId = "spCreateToDoItems";
const {resource: result} = await container.scripts.storedProcedure(sprocId).execute(newItem, {partitionKey: newItem[0].category});
En el siguiente ejemplo se muestra cómo registrar un procedimiento almacenado con el SDK de Python:
import azure.cosmos.cosmos_client as cosmos_client
url = "your_cosmos_db_account_URI"
key = "your_cosmos_db_account_key"
database_name = 'your_cosmos_db_database_name'
container_name = 'your_cosmos_db_container_name'
with open('../js/spCreateToDoItems.js') as file:
file_contents = file.read()
sproc = {
'id': 'spCreateToDoItem',
'serverScript': file_contents,
}
client = cosmos_client.CosmosClient(url, key)
database = client.get_database_client(database_name)
container = database.get_container_client(container_name)
created_sproc = container.scripts.create_stored_procedure(body=sproc)
El siguiente código muestra cómo llamar a un procedimiento almacenado mediante el SDK de Python:
import uuid
new_id= str(uuid.uuid4())
# Creating a document for a container with "id" as a partition key.
new_item = {
"id": new_id,
"category":"Personal",
"name":"Groceries",
"description":"Pick up strawberries",
"isComplete":False
}
result = container.scripts.execute_stored_procedure(sproc=created_sproc,params=[new_item], partition_key=new_id)
Ejecución de desencadenadores previos
Los ejemplos siguientes muestran cómo registrar y llamar a un pretrigger mediante los SDK de Azure Cosmos DB. Para obtener el origen de este ejemplo de desencadenador previo, guardado como trgPreValidateToDoItemTimestamp.js, consulte Desencadenadores previos.
Cuando ejecuta una operación al especificar PreTriggerInclude
y pasar el nombre del desencadenador en un objeto List
, los desencadenadores previos se pasan en el objeto RequestOptions
.
Nota:
Aunque el nombre del desencadenador se pasa como List
, puede ejecutar solo un desencadenador por cada operación.
El código siguiente muestra cómo registrar un desencadenador previo mediante el SDK de .NET v2.
string triggerId = "trgPreValidateToDoItemTimestamp";
Trigger trigger = new Trigger
{
Id = triggerId,
Body = File.ReadAllText($@"..\js\{triggerId}.js"),
TriggerOperation = TriggerOperation.Create,
TriggerType = TriggerType.Pre
};
Uri containerUri = UriFactory.CreateDocumentCollectionUri("myDatabase", "myContainer");
await client.CreateTriggerAsync(containerUri, trigger);
El código siguiente muestra cómo llamar a un pretrigger mediante el SDK de .NET v2:
dynamic newItem = new
{
category = "Personal",
name = "Groceries",
description = "Pick up strawberries",
isComplete = false
};
Uri containerUri = UriFactory.CreateDocumentCollectionUri("myDatabase", "myContainer");
RequestOptions requestOptions = new RequestOptions { PreTriggerInclude = new List<string> { "trgPreValidateToDoItemTimestamp" } };
await client.CreateDocumentAsync(containerUri, newItem, requestOptions);
El código siguiente muestra cómo registrar un desencadenador previo mediante el SDK de. NET v3:
await client.GetContainer("database", "container").Scripts.CreateTriggerAsync(new TriggerProperties
{
Id = "trgPreValidateToDoItemTimestamp",
Body = File.ReadAllText("@..\js\trgPreValidateToDoItemTimestamp.js"),
TriggerOperation = TriggerOperation.Create,
TriggerType = TriggerType.Pre
});
El código siguiente muestra cómo llamar a un pretrigger mediante el SDK de .NET v3:
dynamic newItem = new
{
category = "Personal",
name = "Groceries",
description = "Pick up strawberries",
isComplete = false
};
await client.GetContainer("database", "container").CreateItemAsync(newItem, null, new ItemRequestOptions { PreTriggers = new List<string> { "trgPreValidateToDoItemTimestamp" } });
El código siguiente muestra cómo registrar un desencadenador previo mediante el SDK de Java:
CosmosTriggerProperties definition = new CosmosTriggerProperties(
"preValidateToDoItemTimestamp",
Files.readString(Paths.get("validateToDoItemTimestamp.js"))
);
definition.setTriggerOperation(TriggerOperation.CREATE);
definition.setTriggerType(TriggerType.PRE);
CosmosTriggerResponse response = container
.getScripts()
.createTrigger(definition);
El código siguiente muestra cómo llamar a un desencadenador previo mediante el SDK de Java:
ToDoItem item = new ToDoItem();
item.category = "Personal";
item.name = "Groceries";
item.description = "Pick up strawberries";
item.isComplete = false;
CosmosItemRequestOptions options = new CosmosItemRequestOptions();
options.setPreTriggerInclude(
Arrays.asList("preValidateToDoItemTimestamp")
);
CosmosItemResponse<ToDoItem> response = container.createItem(item, options);
El código siguiente muestra cómo registrar un desencadenador previo mediante el SDK de JavaScript:
const container = client.database("myDatabase").container("myContainer");
const triggerId = "trgPreValidateToDoItemTimestamp";
await container.scripts.triggers.create({
id: triggerId,
body: require(`../js/${triggerId}`),
triggerOperation: "create",
triggerType: "pre"
});
El código siguiente muestra cómo llamar a un desencadenador previo mediante el SDK de JavaScript:
const container = client.database("myDatabase").container("myContainer");
const triggerId = "trgPreValidateToDoItemTimestamp";
await container.items.create({
category: "Personal",
name: "Groceries",
description: "Pick up strawberries",
isComplete: false
}, {preTriggerInclude: [triggerId]});
El código siguiente muestra cómo registrar un desencadenador previo mediante el SDK de Python:
import azure.cosmos.cosmos_client as cosmos_client
from azure.cosmos import documents
url = "your_cosmos_db_account_URI"
key = "your_cosmos_db_account_key"
database_name = 'your_cosmos_db_database_name'
container_name = 'your_cosmos_db_container_name'
with open('../js/trgPreValidateToDoItemTimestamp.js') as file:
file_contents = file.read()
trigger_definition = {
'id': 'trgPreValidateToDoItemTimestamp',
'serverScript': file_contents,
'triggerType': documents.TriggerType.Pre,
'triggerOperation': documents.TriggerOperation.All
}
client = cosmos_client.CosmosClient(url, key)
database = client.get_database_client(database_name)
container = database.get_container_client(container_name)
trigger = container.scripts.create_trigger(trigger_definition)
El código siguiente muestra cómo llamar a un desencadenador previo mediante el SDK de Python:
item = {'category': 'Personal', 'name': 'Groceries',
'description': 'Pick up strawberries', 'isComplete': False}
result = container.create_item(item, pre_trigger_include='trgPreValidateToDoItemTimestamp')
Ejecución de desencadenadores posteriores
Los ejemplos siguientes muestran cómo registrar un desencadenador posterior mediante los SDK de Azure Cosmos DB. Para obtener el origen de este ejemplo de desencadenador posterior, guardado como trgPostUpdateMetadata.js, consulte Desencadenadores posteriores
El código siguiente muestra cómo registrar un desencadenador posterior mediante el SDK de .NET v2:
string triggerId = "trgPostUpdateMetadata";
Trigger trigger = new Trigger
{
Id = triggerId,
Body = File.ReadAllText($@"..\js\{triggerId}.js"),
TriggerOperation = TriggerOperation.Create,
TriggerType = TriggerType.Post
};
Uri containerUri = UriFactory.CreateDocumentCollectionUri("myDatabase", "myContainer");
await client.CreateTriggerAsync(containerUri, trigger);
El código siguiente muestra cómo llamar a un desencadenador posterior mediante el SDK de .NET v2:
var newItem = {
name: "artist_profile_1023",
artist: "The Band",
albums: ["Hellujah", "Rotators", "Spinning Top"]
};
RequestOptions options = new RequestOptions { PostTriggerInclude = new List<string> { "trgPostUpdateMetadata" } };
Uri containerUri = UriFactory.CreateDocumentCollectionUri("myDatabase", "myContainer");
await client.createDocumentAsync(containerUri, newItem, options);
El código siguiente muestra cómo registrar un desencadenador posterior mediante el SDK de .NET v3:
await client.GetContainer("database", "container").Scripts.CreateTriggerAsync(new TriggerProperties
{
Id = "trgPostUpdateMetadata",
Body = File.ReadAllText(@"..\js\trgPostUpdateMetadata.js"),
TriggerOperation = TriggerOperation.Create,
TriggerType = TriggerType.Post
});
El código siguiente muestra cómo llamar a un desencadenador posterior mediante el SDK de .NET v3:
var newItem = {
name: "artist_profile_1023",
artist: "The Band",
albums: ["Hellujah", "Rotators", "Spinning Top"]
};
await client.GetContainer("database", "container").CreateItemAsync(newItem, null, new ItemRequestOptions { PostTriggers = new List<string> { "trgPostUpdateMetadata" } });
El código siguiente muestra cómo registrar un desencadenador posterior mediante el SDK de. Java:
CosmosTriggerProperties definition = new CosmosTriggerProperties(
"postUpdateMetadata",
Files.readString(Paths.get("updateMetadata.js"))
);
definition.setTriggerOperation(TriggerOperation.CREATE);
definition.setTriggerType(TriggerType.POST);
CosmosTriggerResponse response = container
.getScripts()
.createTrigger(definition);
El código siguiente muestra cómo llamar a un desencadenador posterior mediante el SDK de. Java:
ToDoItem item = new ToDoItem();
item.category = "Personal";
item.name = "Doctor";
item.description = "Make appointment for check up";
item.isComplete = true;
CosmosItemRequestOptions options = new CosmosItemRequestOptions();
options.setPostTriggerInclude(
Arrays.asList("postUpdateMetadata")
);
CosmosItemResponse<ToDoItem> response = container.createItem(item, options);
El código siguiente muestra cómo registrar un desencadenador posterior mediante el SDK de. JavaScript:
const container = client.database("myDatabase").container("myContainer");
const triggerId = "trgPostUpdateMetadata";
await container.scripts.triggers.create({
id: triggerId,
body: require(`../js/${triggerId}`),
triggerOperation: "create",
triggerType: "post"
});
El código siguiente muestra cómo llamar a un desencadenador posterior mediante el SDK de. JavaScript:
const item = {
name: "artist_profile_1023",
artist: "The Band",
albums: ["Hellujah", "Rotators", "Spinning Top"]
};
const container = client.database("myDatabase").container("myContainer");
const triggerId = "trgPostUpdateMetadata";
await container.items.create(item, {postTriggerInclude: [triggerId]});
El código siguiente muestra cómo registrar un desencadenador posterior mediante el SDK de Python:
import azure.cosmos.cosmos_client as cosmos_client
from azure.cosmos import documents
url = "your_cosmos_db_account_URI"
key = "your_cosmos_db_account_key"
database_name = 'your_cosmos_db_database_name'
container_name = 'your_cosmos_db_container_name'
with open('../js/trgPostValidateToDoItemTimestamp.js') as file:
file_contents = file.read()
trigger_definition = {
'id': 'trgPostValidateToDoItemTimestamp',
'serverScript': file_contents,
'triggerType': documents.TriggerType.Post,
'triggerOperation': documents.TriggerOperation.All
}
client = cosmos_client.CosmosClient(url, key)
database = client.get_database_client(database_name)
container = database.get_container_client(container_name)
trigger = container.scripts.create_trigger(trigger_definition)
El código siguiente muestra cómo llamar a un desencadenador posterior mediante el SDK de Python:
item = {'category': 'Personal', 'name': 'Groceries',
'description': 'Pick up strawberries', 'isComplete': False}
container.create_item(item, pre_trigger_include='trgPreValidateToDoItemTimestamp')
Trabajo con funciones definidas por el usuario
Los ejemplos siguientes muestran cómo registrar una función definida por el usuario mediante los SDK de Azure Cosmos DB. Para obtener el origen de este ejemplo de función definida por el usuario, guardado como udfTax.js, vea Cómo escribir funciones definidas por el usuario.
El código siguiente muestra cómo registrar una función definida por el usuario mediante el SDK de .NET v2:
string udfId = "Tax";
var udfTax = new UserDefinedFunction
{
Id = udfId,
Body = File.ReadAllText($@"..\js\{udfId}.js")
};
Uri containerUri = UriFactory.CreateDocumentCollectionUri("myDatabase", "myContainer");
await client.CreateUserDefinedFunctionAsync(containerUri, udfTax);
El código siguiente muestra cómo llamar a una función definida por el usuario mediante el SDK de .NET v2:
Uri containerUri = UriFactory.CreateDocumentCollectionUri("myDatabase", "myContainer");
var results = client.CreateDocumentQuery<dynamic>(containerUri, "SELECT * FROM Incomes t WHERE udf.Tax(t.income) > 20000"));
foreach (var result in results)
{
//iterate over results
}
El código siguiente muestra cómo registrar una función definida por el usuario mediante el SDK de .NET v3:
await client.GetContainer("database", "container").Scripts.CreateUserDefinedFunctionAsync(new UserDefinedFunctionProperties
{
Id = "Tax",
Body = File.ReadAllText(@"..\js\Tax.js")
});
El código siguiente muestra cómo llamar a una función definida por el usuario mediante el SDK de .NET v3:
var iterator = client.GetContainer("database", "container").GetItemQueryIterator<dynamic>("SELECT * FROM Incomes t WHERE udf.Tax(t.income) > 20000");
while (iterator.HasMoreResults)
{
var results = await iterator.ReadNextAsync();
foreach (var result in results)
{
//iterate over results
}
}
El código siguiente muestra cómo registrar una función definida por el usuario mediante el SDK de Java:
CosmosUserDefinedFunctionProperties definition = new CosmosUserDefinedFunctionProperties(
"udfTax",
Files.readString(Paths.get("tax.js"))
);
CosmosUserDefinedFunctionResponse response = container
.getScripts()
.createUserDefinedFunction(definition);
El código siguiente muestra cómo llamar a una función definida por el usuario mediante el SDK de Java:
CosmosQueryRequestOptions options = new CosmosQueryRequestOptions();
CosmosPagedIterable<ToDoItem> iterable = container.queryItems(
"SELECT t.cost, udf.udfTax(t.cost) AS costWithTax FROM t",
options,
ToDoItem.class);
El código siguiente muestra cómo registrar una función definida por el usuario mediante el SDK de JavaScript:
const container = client.database("myDatabase").container("myContainer");
const udfId = "Tax";
await container.userDefinedFunctions.create({
id: udfId,
body: require(`../js/${udfId}`)
El código siguiente muestra cómo llamar a una función definida por el usuario mediante el SDK de JavaScript:
const container = client.database("myDatabase").container("myContainer");
const sql = "SELECT * FROM Incomes t WHERE udf.Tax(t.income) > 20000";
const {result} = await container.items.query(sql).toArray();
El código siguiente muestra cómo registrar una función definida por el usuario mediante el SDK de Python:
import azure.cosmos.cosmos_client as cosmos_client
url = "your_cosmos_db_account_URI"
key = "your_cosmos_db_account_key"
database_name = 'your_cosmos_db_database_name'
container_name = 'your_cosmos_db_container_name'
with open('../js/udfTax.js') as file:
file_contents = file.read()
udf_definition = {
'id': 'Tax',
'serverScript': file_contents,
}
client = cosmos_client.CosmosClient(url, key)
database = client.get_database_client(database_name)
container = database.get_container_client(container_name)
udf = container.scripts.create_user_defined_function(udf_definition)
El código siguiente muestra cómo llamar a una función definida por el usuario mediante el SDK de Python:
results = list(container.query_items(
'query': 'SELECT * FROM Incomes t WHERE udf.Tax(t.income) > 20000'))
Pasos siguientes
Aprenda más conceptos y cómo escribir o utilizar procedimientos almacenados, desencadenadores y funciones definidas por el usuario en Azure Cosmos DB: