Azure Cosmos DB giriş bağlaması SQL API'sini kullanarak bir veya daha fazla Azure Cosmos DB belgesini getirir ve işlevin giriş parametresine iletir. Belge kimliği veya sorgu parametreleri, işlevi çağıran tetikleyiciye göre belirlenebilir.
Bu bölüm aşağıdaki örnekleri içerir:
Örnekler basit bir türe ToDoItem başvurur:
namespace CosmosDBSamplesV2
{
public class ToDoItem
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("partitionKey")]
public string PartitionKey { get; set; }
public string Description { get; set; }
}
}
Kuyruk tetikleyicisi, JSON'dan kimlik ara
Aşağıdaki örnek, tek bir belgeyi alan bir C# işlevini gösterir. İşlev, JSON nesnesi içeren bir kuyruk iletisiyle tetiklenir. Kuyruk tetikleyicisi, JSON'u arayacak kimlik ve bölüm anahtarı değerini ToDoItemLookup içeren türünde bir nesne olarak ayrıştırıyor. Bu kimlik ve bölüm anahtarı değeri, belirtilen veritabanı ve ToDoItem koleksiyondan belge almak için kullanılır.
namespace CosmosDBSamplesV2
{
public class ToDoItemLookup
{
public string ToDoItemId { get; set; }
public string ToDoItemPartitionKeyValue { get; set; }
}
}
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Extensions.Logging;
namespace CosmosDBSamplesV2
{
public static class DocByIdFromJSON
{
[FunctionName("DocByIdFromJSON")]
public static void Run(
[QueueTrigger("todoqueueforlookup")] ToDoItemLookup toDoItemLookup,
[CosmosDB(
databaseName: "ToDoItems",
collectionName: "Items",
ConnectionStringSetting = "CosmosDBConnection",
Id = "{ToDoItemId}",
PartitionKey = "{ToDoItemPartitionKeyValue}")]ToDoItem toDoItem,
ILogger log)
{
log.LogInformation($"C# Queue trigger function processed Id={toDoItemLookup?.ToDoItemId} Key={toDoItemLookup?.ToDoItemPartitionKeyValue}");
if (toDoItem == null)
{
log.LogInformation($"ToDo item not found");
}
else
{
log.LogInformation($"Found ToDo item, Description={toDoItem.Description}");
}
}
}
}
HTTP tetikleyicisi, sorgu dizesinde kimlik arama
Aşağıdaki örnek, tek bir belgeyi alan bir C# işlevini gösterir. İşlev, arama için kimlik ve bölüm anahtarı değerini belirtmek için sorgu dizesi kullanan bir HTTP isteği tarafından tetiklenir. Bu kimlik ve bölüm anahtarı değeri, belirtilen veritabanı ve ToDoItem koleksiyondan belge almak için kullanılır.
Not
HTTP sorgu dizesi parametresi büyük/büyük/büyük harfe duyarlıdır.
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Extensions.Logging;
namespace CosmosDBSamplesV2
{
public static class DocByIdFromQueryString
{
[FunctionName("DocByIdFromQueryString")]
public static IActionResult Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]
HttpRequest req,
[CosmosDB(
databaseName: "ToDoItems",
collectionName: "Items",
ConnectionStringSetting = "CosmosDBConnection",
Id = "{Query.id}",
PartitionKey = "{Query.partitionKey}")] ToDoItem toDoItem,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
if (toDoItem == null)
{
log.LogInformation($"ToDo item not found");
}
else
{
log.LogInformation($"Found ToDo item, Description={toDoItem.Description}");
}
return new OkResult();
}
}
}
HTTP tetikleyicisi, rota verilerinden kimlik ara
Aşağıdaki örnek, tek bir belgeyi alan bir C# işlevini gösterir. İşlev, arama için kimlik ve bölüm anahtarı değerini belirtmek için yol verilerini kullanan bir HTTP isteği tarafından tetiklenir. Bu kimlik ve bölüm anahtarı değeri, belirtilen veritabanı ve ToDoItem koleksiyondan belge almak için kullanılır.
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Extensions.Logging;
namespace CosmosDBSamplesV2
{
public static class DocByIdFromRouteData
{
[FunctionName("DocByIdFromRouteData")]
public static IActionResult Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post",
Route = "todoitems/{partitionKey}/{id}")]HttpRequest req,
[CosmosDB(
databaseName: "ToDoItems",
collectionName: "Items",
ConnectionStringSetting = "CosmosDBConnection",
Id = "{id}",
PartitionKey = "{partitionKey}")] ToDoItem toDoItem,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
if (toDoItem == null)
{
log.LogInformation($"ToDo item not found");
}
else
{
log.LogInformation($"Found ToDo item, Description={toDoItem.Description}");
}
return new OkResult();
}
}
}
HTTP tetikleyicisi, SqlQuery kullanarak yol verilerinden kimlik ara
Aşağıdaki örnek, tek bir belgeyi alan bir C# işlevini gösterir. İşlev, arama kimliğini belirtmek için yol verilerini kullanan bir HTTP isteği tarafından tetiklenir. Bu kimlik, belirtilen veritabanından ToDoItem ve koleksiyondan belge almak için kullanılır.
Örnek, parametresinde bağlama ifadesinin nasıl SqlQuery kullanılageldi. Yol verilerini parametresine gösterildiği SqlQuery gibi gönderebilirsiniz, ancak şu anda sorgu dizesi değerlerini geçemezsiniz.
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Host;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
namespace CosmosDBSamplesV2
{
public static class DocByIdFromRouteDataUsingSqlQuery
{
[FunctionName("DocByIdFromRouteDataUsingSqlQuery")]
public static IActionResult Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post",
Route = "todoitems2/{id}")]HttpRequest req,
[CosmosDB("ToDoItems", "Items",
ConnectionStringSetting = "CosmosDBConnection",
SqlQuery = "select * from ToDoItems r where r.id = {id}")]
IEnumerable<ToDoItem> toDoItems,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
foreach (ToDoItem toDoItem in toDoItems)
{
log.LogInformation(toDoItem.Description);
}
return new OkResult();
}
}
}
HTTP tetikleyicisi, SqlQuery kullanarak birden çok belge elde edin
Aşağıdaki örnek, belgelerin listesini alan bir C# işlevini gösterir. İşlev bir HTTP isteği tarafından tetiklenir. Sorgu öznitelik SqlQuery özelliğinde belirtilir.
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Host;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
namespace CosmosDBSamplesV2
{
public static class DocsBySqlQuery
{
[FunctionName("DocsBySqlQuery")]
public static IActionResult Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]
HttpRequest req,
[CosmosDB(
databaseName: "ToDoItems",
collectionName: "Items",
ConnectionStringSetting = "CosmosDBConnection",
SqlQuery = "SELECT top 2 * FROM c order by c._ts desc")]
IEnumerable<ToDoItem> toDoItems,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
foreach (ToDoItem toDoItem in toDoItems)
{
log.LogInformation(toDoItem.Description);
}
return new OkResult();
}
}
}
HTTP tetikleyicisi, DocumentClient kullanarak birden çok belgeyi al
Aşağıdaki örnek, belgelerin listesini alan bir C# işlevini gösterir. İşlev bir HTTP isteği tarafından tetiklenir. Kod, belge DocumentClient listesini okumak için Azure Cosmos DB bağlaması tarafından sağlanan bir örneği kullanır. Örnek, DocumentClient yazma işlemleri için de kullanılabilir.
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.Documents.Client;
using Microsoft.Azure.Documents.Linq;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Extensions.Logging;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace CosmosDBSamplesV2
{
public static class DocsByUsingDocumentClient
{
[FunctionName("DocsByUsingDocumentClient")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post",
Route = null)]HttpRequest req,
[CosmosDB(
databaseName: "ToDoItems",
collectionName: "Items",
ConnectionStringSetting = "CosmosDBConnection")] DocumentClient client,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
var searchterm = req.Query["searchterm"];
if (string.IsNullOrWhiteSpace(searchterm))
{
return (ActionResult)new NotFoundResult();
}
Uri collectionUri = UriFactory.CreateDocumentCollectionUri("ToDoItems", "Items");
log.LogInformation($"Searching for: {searchterm}");
IDocumentQuery<ToDoItem> query = client.CreateDocumentQuery<ToDoItem>(collectionUri)
.Where(p => p.Description.Contains(searchterm))
.AsDocumentQuery();
while (query.HasMoreResults)
{
foreach (ToDoItem result in await query.ExecuteNextAsync())
{
log.LogInformation(result.Description);
}
}
return new OkResult();
}
}
}
HTTP tetikleyicisi, CosmosClient kullanarak birden çok belgeyi al
Aşağıdaki örnek, belgelerin listesini alan bir C# işlevini gösterir. İşlev bir HTTP isteği tarafından tetiklenir. Kod, belge listesini okumak için Azure Cosmos DB bağlaması tarafından sağlanan CosmosClient ve uzantı sürümü 4.x'tebulunan bir örneği kullanır. Örnek, CosmosClient yazma işlemleri için de kullanılabilir.
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.Cosmos;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
namespace CosmosDBSamplesV2
{
public static class DocsByUsingCosmosClient
{
[FunctionName("DocsByUsingCosmosClient")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post",
Route = null)]HttpRequest req,
[CosmosDB(
databaseName: "ToDoItems",
containerName: "Items",
Connection = "CosmosDBConnection")] CosmosClient client,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
var searchterm = req.Query["searchterm"].ToString();
if (string.IsNullOrWhiteSpace(searchterm))
{
return (ActionResult)new NotFoundResult();
}
Container container = client.GetDatabase("ToDoItems").GetContainer("Items");
log.LogInformation($"Searching for: {searchterm}");
QueryDefinition queryDefinition = new QueryDefinition(
"SELECT * FROM items i WHERE CONTAINS(i.Description, @searchterm)")
.WithParameter("@searchterm", searchterm);
using (FeedIterator<ToDoItem> resultSet = container.GetItemQueryIterator<ToDoItem>(queryDefinition))
{
while (resultSet.HasMoreResults)
{
FeedResponse<ToDoItem> response = await resultSet.ReadNextAsync();
ToDoItem item = response.First();
log.LogInformation(item.Description);
}
}
return new OkResult();
}
}
}
Bu bölüm aşağıdaki örnekleri içerir:
HTTP tetikleyicisi örnekleri basit bir türe ToDoItem başvurur:
namespace CosmosDBSamplesV2
{
public class ToDoItem
{
public string Id { get; set; }
public string Description { get; set; }
}
}
Kuyruk tetikleyicisi, dizeden kimlik arama
Aşağıdaki örnekte function.json dosyasında Cosmos db giriş bağlaması ve bağlamayı kullanan bir C# betik işlevi yer almaktadır. İşlev tek bir belgeyi okur ve belgenin metin değerini günceller.
function.json dosyasındaki bağlama verileri şu şekildedir:
{
"name": "inputDocument",
"type": "cosmosDB",
"databaseName": "MyDatabase",
"collectionName": "MyCollection",
"id" : "{queueTrigger}",
"partitionKey": "{partition key value}",
"connectionStringSetting": "MyAccount_COSMOSDB",
"direction": "in"
}
Yapılandırma bölümünde bu özellikler açık bulunmaktadır.
C# betik kodu şu şekildedir:
using System;
// Change input document contents using Azure Cosmos DB input binding
public static void Run(string myQueueItem, dynamic inputDocument)
{
inputDocument.text = "This has changed.";
}
SqlQuery kullanarak kuyruk tetikleyicisi, birden çok belgeyi al
Aşağıdaki örnekte function.json dosyasındaki azure Cosmos DB giriş bağlaması ve bağlamayı kullanan bir C# betik işlevi yer alır. İşlev, sorgu parametrelerini özelleştirmek için bir SQL tetikleyicisi kullanarak bir sorgu tarafından belirtilen birden çok belgeyi döndürür.
Kuyruk tetikleyicisi bir parametresi departmentId sağlar. kuyruğu { "departmentId" : "Finance" } iletisi, finans departmanının tüm kayıtlarını döndürür.
function.json dosyasındaki bağlama verileri şu şekildedir:
{
"name": "documents",
"type": "cosmosDB",
"direction": "in",
"databaseName": "MyDb",
"collectionName": "MyCollection",
"sqlQuery": "SELECT * from c where c.departmentId = {departmentId}",
"connectionStringSetting": "CosmosDBConnection"
}
Yapılandırma bölümünde bu özellikler açık bulunmaktadır.
C# betik kodu şu şekildedir:
public static void Run(QueuePayload myQueueItem, IEnumerable<dynamic> documents)
{
foreach (var doc in documents)
{
// operate on each document
}
}
public class QueuePayload
{
public string departmentId { get; set; }
}
HTTP tetikleyicisi, sorgu dizesinde kimlik arama
Aşağıdaki örnek, tek bir belgeyi alan bir C# betik işlevini gösterir. İşlev, arama için kimlik ve bölüm anahtarı değerini belirtmek için sorgu dizesi kullanan bir HTTP isteği tarafından tetiklenir. Bu kimlik ve bölüm anahtarı değeri, belirtilen veritabanı ve ToDoItem koleksiyondan belge almak için kullanılır.
function.json dosyası şu şekildedir:
{
"bindings": [
{
"authLevel": "anonymous",
"name": "req",
"type": "httpTrigger",
"direction": "in",
"methods": [
"get",
"post"
]
},
{
"name": "$return",
"type": "http",
"direction": "out"
},
{
"type": "cosmosDB",
"name": "toDoItem",
"databaseName": "ToDoItems",
"collectionName": "Items",
"connectionStringSetting": "CosmosDBConnection",
"direction": "in",
"Id": "{Query.id}",
"PartitionKey" : "{Query.partitionKeyValue}"
}
],
"disabled": false
}
C# betik kodu şu şekildedir:
using System.Net;
using Microsoft.Extensions.Logging;
public static HttpResponseMessage Run(HttpRequestMessage req, ToDoItem toDoItem, ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
if (toDoItem == null)
{
log.LogInformation($"ToDo item not found");
}
else
{
log.LogInformation($"Found ToDo item, Description={toDoItem.Description}");
}
return req.CreateResponse(HttpStatusCode.OK);
}
HTTP tetikleyicisi, rota verilerinden kimlik ara
Aşağıdaki örnek, tek bir belgeyi alan bir C# betik işlevini gösterir. İşlev, arama için kimlik ve bölüm anahtarı değerini belirtmek için yol verilerini kullanan bir HTTP isteği tarafından tetiklenir. Bu kimlik ve bölüm anahtarı değeri, belirtilen veritabanı ve ToDoItem koleksiyondan belge almak için kullanılır.
function.json dosyası şu şekildedir:
{
"bindings": [
{
"authLevel": "anonymous",
"name": "req",
"type": "httpTrigger",
"direction": "in",
"methods": [
"get",
"post"
],
"route":"todoitems/{partitionKeyValue}/{id}"
},
{
"name": "$return",
"type": "http",
"direction": "out"
},
{
"type": "cosmosDB",
"name": "toDoItem",
"databaseName": "ToDoItems",
"collectionName": "Items",
"connectionStringSetting": "CosmosDBConnection",
"direction": "in",
"id": "{id}",
"partitionKey": "{partitionKeyValue}"
}
],
"disabled": false
}
C# betik kodu şu şekildedir:
using System.Net;
using Microsoft.Extensions.Logging;
public static HttpResponseMessage Run(HttpRequestMessage req, ToDoItem toDoItem, ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
if (toDoItem == null)
{
log.LogInformation($"ToDo item not found");
}
else
{
log.LogInformation($"Found ToDo item, Description={toDoItem.Description}");
}
return req.CreateResponse(HttpStatusCode.OK);
}
HTTP tetikleyicisi, SqlQuery kullanarak birden çok belge elde edin
Aşağıdaki örnek, belgelerin listesini alan bir C# betik işlevini gösterir. İşlev bir HTTP isteği tarafından tetiklenir. Sorgu öznitelik SqlQuery özelliğinde belirtilir.
function.json dosyası şu şekildedir:
{
"bindings": [
{
"authLevel": "anonymous",
"name": "req",
"type": "httpTrigger",
"direction": "in",
"methods": [
"get",
"post"
]
},
{
"name": "$return",
"type": "http",
"direction": "out"
},
{
"type": "cosmosDB",
"name": "toDoItems",
"databaseName": "ToDoItems",
"collectionName": "Items",
"connectionStringSetting": "CosmosDBConnection",
"direction": "in",
"sqlQuery": "SELECT top 2 * FROM c order by c._ts desc"
}
],
"disabled": false
}
C# betik kodu şu şekildedir:
using System.Net;
using Microsoft.Extensions.Logging;
public static HttpResponseMessage Run(HttpRequestMessage req, IEnumerable<ToDoItem> toDoItems, ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
foreach (ToDoItem toDoItem in toDoItems)
{
log.LogInformation(toDoItem.Description);
}
return req.CreateResponse(HttpStatusCode.OK);
}
HTTP tetikleyicisi, DocumentClient kullanarak birden çok belgeyi al
Aşağıdaki örnek, belgelerin listesini alan bir C# betik işlevini gösterir. İşlev bir HTTP isteği tarafından tetiklenir. Kod, belge DocumentClient listesini okumak için Azure Cosmos DB bağlaması tarafından sağlanan bir örneği kullanır. Örnek, DocumentClient yazma işlemleri için de kullanılabilir.
İşte function. JSON dosyası:
{
"bindings": [
{
"authLevel": "anonymous",
"name": "req",
"type": "httpTrigger",
"direction": "in",
"methods": [
"get",
"post"
]
},
{
"name": "$return",
"type": "http",
"direction": "out"
},
{
"type": "cosmosDB",
"name": "client",
"databaseName": "ToDoItems",
"collectionName": "Items",
"connectionStringSetting": "CosmosDBConnection",
"direction": "inout"
}
],
"disabled": false
}
C# betik kodu aşağıda verilmiştir:
#r "Microsoft.Azure.Documents.Client"
using System.Net;
using Microsoft.Azure.Documents.Client;
using Microsoft.Azure.Documents.Linq;
using Microsoft.Extensions.Logging;
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, DocumentClient client, ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
Uri collectionUri = UriFactory.CreateDocumentCollectionUri("ToDoItems", "Items");
string searchterm = req.GetQueryNameValuePairs()
.FirstOrDefault(q => string.Compare(q.Key, "searchterm", true) == 0)
.Value;
if (searchterm == null)
{
return req.CreateResponse(HttpStatusCode.NotFound);
}
log.LogInformation($"Searching for word: {searchterm} using Uri: {collectionUri.ToString()}");
IDocumentQuery<ToDoItem> query = client.CreateDocumentQuery<ToDoItem>(collectionUri)
.Where(p => p.Description.Contains(searchterm))
.AsDocumentQuery();
while (query.HasMoreResults)
{
foreach (ToDoItem result in await query.ExecuteNextAsync())
{
log.LogInformation(result.Description);
}
}
return req.CreateResponse(HttpStatusCode.OK);
}
Bu bölüm aşağıdaki örnekleri içerir:
Örnekler basit bir ToDoItem türe başvurur:
public class ToDoItem {
private String id;
private String description;
public String getId() {
return id;
}
public String getDescription() {
return description;
}
@Override
public String toString() {
return "ToDoItem={id=" + id + ",description=" + description + "}";
}
}
HTTP tetikleyicisi, sorgu dizesinden KIMLIĞI ara dize parametresi
Aşağıdaki örnekte, tek bir belgeyi alan bir Java işlevi gösterilmektedir. İşlev, aranacak KIMLIĞI ve bölüm anahtarı değerini belirtmek için bir sorgu dizesi kullanan bir HTTP isteği tarafından tetiklenir. Bu KIMLIK ve bölüm anahtarı değeri, belirtilen veritabanından ve koleksiyondan bir belgeyi dize biçiminde almak için kullanılır.
public class DocByIdFromQueryString {
@FunctionName("DocByIdFromQueryString")
public HttpResponseMessage run(
@HttpTrigger(name = "req",
methods = {HttpMethod.GET, HttpMethod.POST},
authLevel = AuthorizationLevel.ANONYMOUS)
HttpRequestMessage<Optional<String>> request,
@CosmosDBInput(name = "database",
databaseName = "ToDoList",
collectionName = "Items",
id = "{Query.id}",
partitionKey = "{Query.partitionKeyValue}",
connectionStringSetting = "Cosmos_DB_Connection_String")
Optional<String> item,
final ExecutionContext context) {
// Item list
context.getLogger().info("Parameters are: " + request.getQueryParameters());
context.getLogger().info("String from the database is " + (item.isPresent() ? item.get() : null));
// Convert and display
if (!item.isPresent()) {
return request.createResponseBuilder(HttpStatus.BAD_REQUEST)
.body("Document not found.")
.build();
}
else {
// return JSON from Cosmos. Alternatively, we can parse the JSON string
// and return an enriched JSON object.
return request.createResponseBuilder(HttpStatus.OK)
.header("Content-Type", "application/json")
.body(item.get())
.build();
}
}
}
Java işlevleri çalışma zamanı kitaplığı'nda, @CosmosDBInput değeri Cosmos DB gelen işlev parametrelerinde ek açıklamayı kullanın. Bu ek açıklama, kullanılarak yerel Java türleri, POJOs veya null atanabilir değerlerle kullanılabilir Optional<T> .
HTTP tetikleyicisi, sorgu dizesinden KIMLIĞI ara-POJO parametresi
Aşağıdaki örnekte, tek bir belgeyi alan bir Java işlevi gösterilmektedir. İşlev, aranacak KIMLIĞI ve bölüm anahtarı değerini belirtmek için bir sorgu dizesi kullanan bir HTTP isteği tarafından tetiklenir. Bu KIMLIK ve bölüm anahtarı değeri, belirtilen veritabanından ve koleksiyondan bir belgeyi almak için kullanılır. Daha sonra belge daha ToDoItem önce oluşturulan Pojo örneğine dönüştürülür ve işleve bağımsız değişken olarak geçirilir.
public class DocByIdFromQueryStringPojo {
@FunctionName("DocByIdFromQueryStringPojo")
public HttpResponseMessage run(
@HttpTrigger(name = "req",
methods = {HttpMethod.GET, HttpMethod.POST},
authLevel = AuthorizationLevel.ANONYMOUS)
HttpRequestMessage<Optional<String>> request,
@CosmosDBInput(name = "database",
databaseName = "ToDoList",
collectionName = "Items",
id = "{Query.id}",
partitionKey = "{Query.partitionKeyValue}",
connectionStringSetting = "Cosmos_DB_Connection_String")
ToDoItem item,
final ExecutionContext context) {
// Item list
context.getLogger().info("Parameters are: " + request.getQueryParameters());
context.getLogger().info("Item from the database is " + item);
// Convert and display
if (item == null) {
return request.createResponseBuilder(HttpStatus.BAD_REQUEST)
.body("Document not found.")
.build();
}
else {
return request.createResponseBuilder(HttpStatus.OK)
.header("Content-Type", "application/json")
.body(item)
.build();
}
}
}
HTTP tetikleyicisi, rota verilerinden KIMLIK arama
Aşağıdaki örnekte, tek bir belgeyi alan bir Java işlevi gösterilmektedir. İşlev, aranacak KIMLIĞI ve bölüm anahtarı değerini belirtmek için yol parametresi kullanan bir HTTP isteği tarafından tetiklenir. Bu KIMLIK ve bölüm anahtarı değeri, belirtilen veritabanından ve koleksiyondan bir belgeyi almak için kullanılır Optional<String> .
public class DocByIdFromRoute {
@FunctionName("DocByIdFromRoute")
public HttpResponseMessage run(
@HttpTrigger(name = "req",
methods = {HttpMethod.GET, HttpMethod.POST},
authLevel = AuthorizationLevel.ANONYMOUS,
route = "todoitems/{partitionKeyValue}/{id}")
HttpRequestMessage<Optional<String>> request,
@CosmosDBInput(name = "database",
databaseName = "ToDoList",
collectionName = "Items",
id = "{id}",
partitionKey = "{partitionKeyValue}",
connectionStringSetting = "Cosmos_DB_Connection_String")
Optional<String> item,
final ExecutionContext context) {
// Item list
context.getLogger().info("Parameters are: " + request.getQueryParameters());
context.getLogger().info("String from the database is " + (item.isPresent() ? item.get() : null));
// Convert and display
if (!item.isPresent()) {
return request.createResponseBuilder(HttpStatus.BAD_REQUEST)
.body("Document not found.")
.build();
}
else {
// return JSON from Cosmos. Alternatively, we can parse the JSON string
// and return an enriched JSON object.
return request.createResponseBuilder(HttpStatus.OK)
.header("Content-Type", "application/json")
.body(item.get())
.build();
}
}
}
HTTP tetikleyicisi, SqlQuery kullanarak rota verilerinden KIMLIK arama
Aşağıdaki örnekte, tek bir belgeyi alan bir Java işlevi gösterilmektedir. İşlev, aranacak KIMLIĞI belirtmek için yol parametresi kullanan bir HTTP isteği tarafından tetiklenir. Bu KIMLIK, ToDoItem[] sorgu ölçütlerine bağlı olarak çok sayıda belge döndürüldüğünden, belirtilen veritabanından ve koleksiyondan bir belgeyi almak için kullanılır.
Not
Yalnızca KIMLIĞE göre sorgulama yapmanız gerekiyorsa, Önceki örneklerdeolduğu gibi, daha az istek birimitükettiği için bir arama kullanmanız önerilir. Nokta okuma işlemleri (GET), KIMLIĞE göre sorgulardan daha etkilidir .
public class DocByIdFromRouteSqlQuery {
@FunctionName("DocByIdFromRouteSqlQuery")
public HttpResponseMessage run(
@HttpTrigger(name = "req",
methods = {HttpMethod.GET, HttpMethod.POST},
authLevel = AuthorizationLevel.ANONYMOUS,
route = "todoitems2/{id}")
HttpRequestMessage<Optional<String>> request,
@CosmosDBInput(name = "database",
databaseName = "ToDoList",
collectionName = "Items",
sqlQuery = "select * from Items r where r.id = {id}",
connectionStringSetting = "Cosmos_DB_Connection_String")
ToDoItem[] item,
final ExecutionContext context) {
// Item list
context.getLogger().info("Parameters are: " + request.getQueryParameters());
context.getLogger().info("Items from the database are " + item);
// Convert and display
if (item == null) {
return request.createResponseBuilder(HttpStatus.BAD_REQUEST)
.body("Document not found.")
.build();
}
else {
return request.createResponseBuilder(HttpStatus.OK)
.header("Content-Type", "application/json")
.body(item)
.build();
}
}
}
HTTP tetikleyicisi, SqlQuery kullanarak rota verilerinden birden çok belge alın
Aşağıdaki örnekte, birden çok belgeyi alan bir Java işlevi gösterilmektedir. İşlevi, desc alanında aranacak dizeyi belirtmek için bir Route parametresi kullanan BIR http isteği tarafından tetiklenir description . Arama terimi, belirtilen veritabanından ve koleksiyondan bir belge koleksiyonunu almak, sonuç kümesini öğesine dönüştürmek ToDoItem[] ve işleve bağımsız değişken olarak geçirmek için kullanılır.
public class DocsFromRouteSqlQuery {
@FunctionName("DocsFromRouteSqlQuery")
public HttpResponseMessage run(
@HttpTrigger(name = "req",
methods = {HttpMethod.GET},
authLevel = AuthorizationLevel.ANONYMOUS,
route = "todoitems3/{desc}")
HttpRequestMessage<Optional<String>> request,
@CosmosDBInput(name = "database",
databaseName = "ToDoList",
collectionName = "Items",
sqlQuery = "select * from Items r where contains(r.description, {desc})",
connectionStringSetting = "Cosmos_DB_Connection_String")
ToDoItem[] items,
final ExecutionContext context) {
// Item list
context.getLogger().info("Parameters are: " + request.getQueryParameters());
context.getLogger().info("Number of items from the database is " + (items == null ? 0 : items.length));
// Convert and display
if (items == null) {
return request.createResponseBuilder(HttpStatus.BAD_REQUEST)
.body("No documents found.")
.build();
}
else {
return request.createResponseBuilder(HttpStatus.OK)
.header("Content-Type", "application/json")
.body(items)
.build();
}
}
}
Bu bölüm, çeşitli kaynaklardan bir KIMLIK değeri belirterek tek bir belgeyi okuyan aşağıdaki örnekleri içerir:
Kuyruk tetikleyicisi, JSON 'dan KIMLIK arama
aşağıdaki örnek, bir function. json dosyasındaki bir Cosmos DB girişi bağlamasını ve bağlamayı kullanan bir JavaScript işlevini gösterir. İşlevi tek bir belgeyi okur ve belgenin metin değerini güncelleştirir.
Bu, function. JSON dosyasındaki bağlama verileri:
{
"name": "inputDocumentIn",
"type": "cosmosDB",
"databaseName": "MyDatabase",
"collectionName": "MyCollection",
"id" : "{queueTrigger_payload_property}",
"partitionKey": "{queueTrigger_payload_property}",
"connectionStringSetting": "MyAccount_COSMOSDB",
"direction": "in"
},
{
"name": "inputDocumentOut",
"type": "cosmosDB",
"databaseName": "MyDatabase",
"collectionName": "MyCollection",
"createIfNotExists": false,
"partitionKey": "{queueTrigger_payload_property}",
"connectionStringSetting": "MyAccount_COSMOSDB",
"direction": "out"
}
Yapılandırma bölümünde bu özellikler açıklanmaktadır.
JavaScript kodu aşağıda verilmiştir:
// Change input document contents using Azure Cosmos DB input binding, using context.bindings.inputDocumentOut
module.exports = function (context) {
context.bindings.inputDocumentOut = context.bindings.inputDocumentIn;
context.bindings.inputDocumentOut.text = "This was updated!";
context.done();
};
HTTP tetikleyicisi, sorgu dizesinden KIMLIĞI ara
Aşağıdaki örnekte, tek bir belgeyi alan bir JavaScript işlevi gösterilmektedir. İşlev, aranacak KIMLIĞI ve bölüm anahtarı değerini belirtmek için bir sorgu dizesi kullanan bir HTTP isteği tarafından tetiklenir. Bu KIMLIK ve bölüm anahtarı değeri, ToDoItem belirtilen veritabanından ve koleksiyondan bir belge almak için kullanılır.
İşte function. JSON dosyası:
{
"bindings": [
{
"authLevel": "anonymous",
"name": "req",
"type": "httpTrigger",
"direction": "in",
"methods": [
"get",
"post"
]
},
{
"name": "$return",
"type": "http",
"direction": "out"
},
{
"type": "cosmosDB",
"name": "toDoItem",
"databaseName": "ToDoItems",
"collectionName": "Items",
"connectionStringSetting": "CosmosDBConnection",
"direction": "in",
"Id": "{Query.id}",
"PartitionKey": "{Query.partitionKeyValue}"
}
],
"disabled": false
}
JavaScript kodu aşağıda verilmiştir:
module.exports = function (context, req, toDoItem) {
context.log('JavaScript queue trigger function processed work item');
if (!toDoItem)
{
context.log("ToDo item not found");
}
else
{
context.log("Found ToDo item, Description=" + toDoItem.Description);
}
context.done();
};
HTTP tetikleyicisi, rota verilerinden KIMLIK arama
Aşağıdaki örnekte, tek bir belgeyi alan bir JavaScript işlevi gösterilmektedir. İşlev, aranacak KIMLIĞI ve bölüm anahtarı değerini belirtmek için rota verilerini kullanan bir HTTP isteği tarafından tetiklenir. Bu KIMLIK ve bölüm anahtarı değeri, ToDoItem belirtilen veritabanından ve koleksiyondan bir belge almak için kullanılır.
İşte function. JSON dosyası:
{
"bindings": [
{
"authLevel": "anonymous",
"name": "req",
"type": "httpTrigger",
"direction": "in",
"methods": [
"get",
"post"
],
"route":"todoitems/{partitionKeyValue}/{id}"
},
{
"name": "$return",
"type": "http",
"direction": "out"
},
{
"type": "cosmosDB",
"name": "toDoItem",
"databaseName": "ToDoItems",
"collectionName": "Items",
"connectionStringSetting": "CosmosDBConnection",
"direction": "in",
"Id": "{id}",
"PartitionKey": "{partitionKeyValue}"
}
],
"disabled": false
}
JavaScript kodu aşağıda verilmiştir:
module.exports = function (context, req, toDoItem) {
context.log('JavaScript queue trigger function processed work item');
if (!toDoItem)
{
context.log("ToDo item not found");
}
else
{
context.log("Found ToDo item, Description=" + toDoItem.Description);
}
context.done();
};
Kuyruk tetikleyicisi, SqlQuery kullanarak birden çok belge alma
aşağıdaki örnek, bir function. json dosyasındaki bir Azure Cosmos DB girişi bağlamasını ve bağlamayı kullanan bir JavaScript işlevini gösterir. işlevi, sorgu parametrelerini özelleştirmek için bir kuyruk tetikleyicisi kullanarak bir SQL sorgusuyla belirtilen birden çok belgeyi alır.
Sıra tetikleyicisi bir parametre sağlar departmentId . Bir kuyruk iletisi { "departmentId" : "Finance" } , finans departmanı için tüm kayıtları döndürür.
Bu, function. JSON dosyasındaki bağlama verileri:
{
"name": "documents",
"type": "cosmosDB",
"direction": "in",
"databaseName": "MyDb",
"collectionName": "MyCollection",
"sqlQuery": "SELECT * from c where c.departmentId = {departmentId}",
"connectionStringSetting": "CosmosDBConnection"
}
Yapılandırma bölümünde bu özellikler açıklanmaktadır.
JavaScript kodu aşağıda verilmiştir:
module.exports = function (context, input) {
var documents = context.bindings.documents;
for (var i = 0; i < documents.length; i++) {
var document = documents[i];
// operate on each document
}
context.done();
};
Kuyruk tetikleyicisi, JSON 'dan KIMLIK arama
aşağıdaki örnek, tek bir Cosmos DB belgesinin nasıl okunacağını ve güncelleşdiğini gösterir. Belgenin benzersiz tanımlayıcısı, bir kuyruk iletisindeki JSON değeri aracılığıyla sağlanır.
Cosmos DB girişi bağlama öncelikle işlevin yapılandırma dosyasında bulunan bağlamalar listesinde (function. json) listelenir.
{
"name": "InputDocumentIn",
"type": "cosmosDB",
"databaseName": "MyDatabase",
"collectionName": "MyCollection",
"id": "{queueTrigger_payload_property}",
"partitionKey": "{queueTrigger_payload_property}",
"connectionStringSetting": "CosmosDBConnection",
"direction": "in"
},
{
"name": "InputDocumentOut",
"type": "cosmosDB",
"databaseName": "MyDatabase",
"collectionName": "MyCollection",
"createIfNotExists": false,
"partitionKey": "{queueTrigger_payload_property}",
"connectionStringSetting": "CosmosDBConnection",
"direction": "out"
}
run.ps1 dosyası, gelen belgeyi okuyan ve değişiklikleri çıktılar olan PowerShell koduna sahiptir.
param($QueueItem, $InputDocumentIn, $TriggerMetadata)
$Document = $InputDocumentIn
$Document.text = 'This was updated!'
Push-OutputBinding -Name InputDocumentOut -Value $Document
HTTP tetikleyicisi, sorgu dizesinden KIMLIĞI ara
aşağıdaki örnek, bir web apı 'sinden tek bir Cosmos DB belgesinin nasıl okunacağını ve güncelleşdiğini gösterir. Belgenin benzersiz tanımlayıcısı, bağlamanın özelliğinde tanımlandığı şekilde HTTP isteğinden bir QueryString parametresi aracılığıyla sağlanır "Id": "{Query.Id}" .
Cosmos DB girişi bağlama öncelikle işlevin yapılandırma dosyasında bulunan bağlamalar listesinde (function. json) listelenir.
{
"bindings": [
{
"type": "cosmosDB",
"name": "ToDoItem",
"databaseName": "ToDoItems",
"collectionName": "Items",
"connectionStringSetting": "CosmosDBConnection",
"direction": "in",
"Id": "{Query.id}",
"PartitionKey": "{Query.partitionKeyValue}"
},
{
"authLevel": "anonymous",
"name": "Request",
"type": "httpTrigger",
"direction": "in",
"methods": [
"get",
"post"
]
},
{
"name": "Response",
"type": "http",
"direction": "out"
},
],
"disabled": false
}
run.ps1 dosyası, gelen belgeyi okuyan ve değişiklikleri çıktılar olan PowerShell koduna sahiptir.
using namespace System.Net
param($Request, $ToDoItem, $TriggerMetadata)
Write-Host 'PowerShell HTTP trigger function processed a request'
if (-not $ToDoItem) {
Write-Host 'ToDo item not found'
Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
StatusCode = [HttpStatusCode]::NotFound
Body = $ToDoItem.Description
})
} else {
Write-Host "Found ToDo item, Description=$($ToDoItem.Description)"
Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
StatusCode = [HttpStatusCode]::OK
Body = $ToDoItem.Description
})
}
HTTP tetikleyicisi, rota verilerinden KIMLIK arama
aşağıdaki örnek, bir web apı 'sinden tek bir Cosmos DB belgesinin nasıl okunacağını ve güncelleşdiğini gösterir. Belgenin benzersiz tanımlayıcısı bir rota parametresi aracılığıyla sağlanır. route parametresi HTTP istek bağlamanın route özelliğinde tanımlanır ve Cosmos DB "Id": "{Id}" binding özelliğinde başvurulur.
Cosmos DB girişi bağlama öncelikle işlevin yapılandırma dosyasında bulunan bağlamalar listesinde (function. json) listelenir.
{
"bindings": [
{
"type": "cosmosDB",
"name": "ToDoItem",
"databaseName": "ToDoItems",
"collectionName": "Items",
"connectionStringSetting": "CosmosDBConnection",
"direction": "in",
"Id": "{id}",
"PartitionKey": "{partitionKeyValue}"
},
{
"authLevel": "anonymous",
"name": "Request",
"type": "httpTrigger",
"direction": "in",
"methods": [
"get",
"post"
],
"route": "todoitems/{partitionKeyValue}/{id}"
},
{
"name": "Response",
"type": "http",
"direction": "out"
}
],
"disabled": false
}
run.ps1 dosyası, gelen belgeyi okuyan ve değişiklikleri çıktılar olan PowerShell koduna sahiptir.
using namespace System.Net
param($Request, $ToDoItem, $TriggerMetadata)
Write-Host 'PowerShell HTTP trigger function processed a request'
if (-not $ToDoItem) {
Write-Host 'ToDo item not found'
Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
StatusCode = [HttpStatusCode]::NotFound
Body = $ToDoItem.Description
})
} else {
Write-Host "Found ToDo item, Description=$($ToDoItem.Description)"
Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
StatusCode = [HttpStatusCode]::OK
Body = $ToDoItem.Description
})
}
Kuyruk tetikleyicisi, SqlQuery kullanarak birden çok belge alma
aşağıdaki örnek, birden çok Cosmos DB belgenin nasıl okunacağını gösterir. İşlevin yapılandırma dosyası (function. JSON), öğesini içeren bağlama özelliklerini tanımlar sqlQuery . özelliğine sunulan SQL deyimleri, sqlQuery işlevine sunulan belge kümesini seçer.
{
"name": "Documents",
"type": "cosmosDB",
"direction": "in",
"databaseName": "MyDb",
"collectionName": "MyCollection",
"sqlQuery": "SELECT * from c where c.departmentId = {departmentId}",
"connectionStringSetting": "CosmosDBConnection"
}
Run1.PS dosyası, gelen belgeleri okuyan PowerShell koduna sahiptir.
param($QueueItem, $Documents, $TriggerMetadata)
foreach ($Document in $Documents) {
# operate on each document
}
Bu bölüm, çeşitli kaynaklardan bir KIMLIK değeri belirterek tek bir belgeyi okuyan aşağıdaki örnekleri içerir:
Kuyruk tetikleyicisi, JSON 'dan KIMLIK arama
Aşağıdaki örnekte bir function.json Cosmos db giriş bağlaması ve bağlamayı kullanan bir Python işlevi yer almaktadır. İşlev tek bir belgeyi okur ve belgenin metin değerini günceller.
function.json dosyasındaki bağlama verileri şu şekildedir:
{
"name": "documents",
"type": "cosmosDB",
"databaseName": "MyDatabase",
"collectionName": "MyCollection",
"id" : "{queueTrigger_payload_property}",
"partitionKey": "{queueTrigger_payload_property}",
"connectionStringSetting": "MyAccount_COSMOSDB",
"direction": "in"
},
{
"name": "$return",
"type": "cosmosDB",
"databaseName": "MyDatabase",
"collectionName": "MyCollection",
"createIfNotExists": false,
"partitionKey": "{queueTrigger_payload_property}",
"connectionStringSetting": "MyAccount_COSMOSDB",
"direction": "out"
}
Yapılandırma bölümünde bu özellikler açık bulunmaktadır.
Python kodu şu şekildedir:
import azure.functions as func
def main(queuemsg: func.QueueMessage, documents: func.DocumentList) -> func.Document:
if documents:
document = documents[0]
document['text'] = 'This was updated!'
return document
HTTP tetikleyicisi, sorgu dizesinde kimlik arama
Aşağıdaki örnek, tek bir belgeyi alan bir Python işlevini gösterir. İşlev, arama için kimlik ve bölüm anahtarı değerini belirtmek için sorgu dizesi kullanan bir HTTP isteği tarafından tetiklenir. Bu kimlik ve bölüm anahtarı değeri, belirtilen veritabanı ve ToDoItem koleksiyondan belge almak için kullanılır.
function.json dosyası şu şekildedir:
{
"bindings": [
{
"authLevel": "anonymous",
"name": "req",
"type": "httpTrigger",
"direction": "in",
"methods": [
"get",
"post"
]
},
{
"name": "$return",
"type": "http",
"direction": "out"
},
{
"type": "cosmosDB",
"name": "todoitems",
"databaseName": "ToDoItems",
"collectionName": "Items",
"connectionStringSetting": "CosmosDBConnection",
"direction": "in",
"Id": "{Query.id}",
"PartitionKey": "{Query.partitionKeyValue}"
}
],
"scriptFile": "__init__.py"
}
Python kodu şu şekildedir:
import logging
import azure.functions as func
def main(req: func.HttpRequest, todoitems: func.DocumentList) -> str:
if not todoitems:
logging.warning("ToDo item not found")
else:
logging.info("Found ToDo item, Description=%s",
todoitems[0]['description'])
return 'OK'
HTTP tetikleyicisi, rota verilerinden kimlik ara
Aşağıdaki örnek, tek bir belgeyi alan bir Python işlevini gösterir. İşlev, arama için kimlik ve bölüm anahtarı değerini belirtmek için yol verilerini kullanan bir HTTP isteği tarafından tetiklenir. Bu kimlik ve bölüm anahtarı değeri, belirtilen veritabanı ve ToDoItem koleksiyondan belge almak için kullanılır.
function.json dosyası şu şekildedir:
{
"bindings": [
{
"authLevel": "anonymous",
"name": "req",
"type": "httpTrigger",
"direction": "in",
"methods": [
"get",
"post"
],
"route":"todoitems/{partitionKeyValue}/{id}"
},
{
"name": "$return",
"type": "http",
"direction": "out"
},
{
"type": "cosmosDB",
"name": "todoitems",
"databaseName": "ToDoItems",
"collectionName": "Items",
"connection": "CosmosDBConnection",
"direction": "in",
"Id": "{id}",
"PartitionKey": "{partitionKeyValue}"
}
],
"disabled": false,
"scriptFile": "__init__.py"
}
Python kodu şu şekildedir:
import logging
import azure.functions as func
def main(req: func.HttpRequest, todoitems: func.DocumentList) -> str:
if not todoitems:
logging.warning("ToDo item not found")
else:
logging.info("Found ToDo item, Description=%s",
todoitems[0]['description'])
return 'OK'
SqlQuery kullanarak kuyruk tetikleyicisi, birden çok belgeyi al
Aşağıdaki örnekte function.json dosyasındaki azure Cosmos DB giriş bağlaması ve bağlamayı kullanan python işlevi yer almaktadır. İşlev, sorgu parametrelerini özelleştirmek için bir SQL tetikleyicisi kullanarak bir sorgu tarafından belirtilen birden çok belgeyi döndürür.
Kuyruk tetikleyicisi bir parametresi departmentId sağlar. kuyruğu { "departmentId" : "Finance" } iletisi, finans departmanının tüm kayıtlarını döndürür.
function.json dosyasındaki bağlama verileri şu şekildedir:
{
"name": "documents",
"type": "cosmosDB",
"direction": "in",
"databaseName": "MyDb",
"collectionName": "MyCollection",
"sqlQuery": "SELECT * from c where c.departmentId = {departmentId}",
"connectionStringSetting": "CosmosDBConnection"
}
Yapılandırma bölümünde bu özellikler açık bulunmaktadır.
Python kodu şu şekildedir:
import azure.functions as func
def main(queuemsg: func.QueueMessage, documents: func.DocumentList):
for document in documents:
# operate on each document