本部分包含以下示例:This section contains the following examples:
这些示例引用简单的 ToDoItem
类型:The examples refer to a simple ToDoItem
type:
namespace CosmosDBSamplesV2
{
public class ToDoItem
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("partitionKey")]
public string PartitionKey { get; set; }
public string Description { get; set; }
}
}
队列触发器,从 JSON 查找 IDQueue trigger, look up ID from JSON
以下示例演示检索单个文档的 C# 函数。The following example shows a C# function that retrieves a single document. 该函数由包含 JSON 对象的队列消息触发。The function is triggered by a queue message that contains a JSON object. 队列触发器将 JSON 分析为 ToDoItemLookup
类型的对象,其中包含要查找的 ID 和分区键值。The queue trigger parses the JSON into an object of type ToDoItemLookup
, which contains the ID and partition key value to look up. 该 ID 和分区键值用于从指定的数据库和集合中检索 ToDoItem
文档。That ID and partition key value are used to retrieve a ToDoItem
document from the specified database and collection.
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 触发器,从查询字符串查找 IDHTTP trigger, look up ID from query string
以下示例演示检索单个文档的 C# 函数。The following example shows a C# function that retrieves a single document. 此函数由 HTTP 请求触发,该请求使用的查询字符串用于指定要查找的 ID 和分区键值。The function is triggered by an HTTP request that uses a query string to specify the ID and partition key value to look up. 该 ID 和分区键值用于从指定的数据库和集合中检索 ToDoItem
文档。That ID and partition key value are used to retrieve a ToDoItem
document from the specified database and collection.
备注
HTTP 查询字符串参数区分大小写。The HTTP query string parameter is case-sensitive.
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 触发器,从路由数据查找 IDHTTP trigger, look up ID from route data
以下示例演示检索单个文档的 C# 函数。The following example shows a C# function that retrieves a single document. 此函数由 HTTP 请求触发,该请求使用的路由数据用于指定要查找的 ID 和分区键值。The function is triggered by an HTTP request that uses route data to specify the ID and partition key value to look up. 该 ID 和分区键值用于从指定的数据库和集合中检索 ToDoItem
文档。That ID and partition key value are used to retrieve a ToDoItem
document from the specified database and collection.
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 触发器,使用 SqlQuery 从路由数据查找 IDHTTP trigger, look up ID from route data, using SqlQuery
以下示例演示检索单个文档的 C# 函数。The following example shows a C# function that retrieves a single document. 此函数由 HTTP 请求触发,该请求使用的路由数据用于指定要查找的 ID。The function is triggered by an HTTP request that uses route data to specify the ID to look up. 该 ID 用于从指定的数据库和集合检索 ToDoItem
文档。That ID is used to retrieve a ToDoItem
document from the specified database and collection.
以下示例演示如何在 SqlQuery
参数中使用绑定表达式。The example shows how to use a binding expression in the SqlQuery
parameter. 可以将路由数据传递至所示的 SqlQuery
参数,但目前无法传递查询字符串值。You can pass route data to the SqlQuery
parameter as shown, but currently you can't pass query string values.
备注
如果需要只按 ID 进行查询,则建议使用查找(如以前的示例所示),因为该查找消耗较少的请求单位。If you need to query by just the ID, it is recommended to use a look up, like the previous examples, as it will consume less request units. 点读取操作 (GET) 比按 ID 进行的查询更高效。Point read operations (GET) are more efficient than queries by ID.
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 触发器,使用 SqlQuery 获取多个文档HTTP trigger, get multiple docs, using SqlQuery
以下示例演示检索文档列表的 C# 函数。The following example shows a C# function that retrieves a list of documents. 此函数由 HTTP 请求触发。The function is triggered by an HTTP request. 此查询在 SqlQuery
特性属性中指定。The query is specified in the SqlQuery
attribute property.
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 触发器,使用 DocumentClient 获取多个文档HTTP trigger, get multiple docs, using DocumentClient
以下示例演示检索文档列表的 C# 函数。The following example shows a C# function that retrieves a list of documents. 此函数由 HTTP 请求触发。The function is triggered by an HTTP request. 此代码使用 Azure Cosmos DB 绑定提供的 DocumentClient
实例来读取文档列表。The code uses a DocumentClient
instance provided by the Azure Cosmos DB binding to read a list of documents. DocumentClient
实例也可用于写入操作。The DocumentClient
instance could also be used for write operations.
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();
}
}
}
本部分包含以下示例:This section contains the following examples:
HTTP 触发器示例引用简单的 ToDoItem
类型:The HTTP trigger examples refer to a simple ToDoItem
type:
namespace CosmosDBSamplesV2
{
public class ToDoItem
{
public string Id { get; set; }
public string Description { get; set; }
}
}
队列触发器,从字符串查找 IDQueue trigger, look up ID from string
以下示例演示 function.json 文件中的一个 Cosmos DB 输入绑定以及使用该绑定的 C# 脚本函数。The following example shows a Cosmos DB input binding in a function.json file and a C# script function that uses the binding. 该函数读取单个文档,并更新文档的文本值。The function reads a single document and updates the document's text value.
下面是 function.json 文件中的绑定数据:Here's the binding data in the function.json file:
{
"name": "inputDocument",
"type": "cosmosDB",
"databaseName": "MyDatabase",
"collectionName": "MyCollection",
"id" : "{queueTrigger}",
"partitionKey": "{partition key value}",
"connectionStringSetting": "MyAccount_COSMOSDB",
"direction": "in"
}
配置部分解释了这些属性。The configuration section explains these properties.
C# 脚本代码如下所示:Here's the C# script code:
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 获取多个文档Queue trigger, get multiple docs, using SqlQuery
以下示例演示 function.json 文件中的一个 Azure Cosmos DB 输入绑定以及使用该绑定的 C# 脚本函数。The following example shows an Azure Cosmos DB input binding in a function.json file and a C# script function that uses the binding. 该函数使用队列触发器自定义查询参数检索 SQL 查询指定的多个文档。The function retrieves multiple documents specified by a SQL query, using a queue trigger to customize the query parameters.
队列触发器提供参数 departmentId
。The queue trigger provides a parameter departmentId
. { "departmentId" : "Finance" }
的队列消息将返回财务部的所有记录。A queue message of { "departmentId" : "Finance" }
would return all records for the finance department.
下面是 function.json 文件中的绑定数据:Here's the binding data in the function.json file:
{
"name": "documents",
"type": "cosmosDB",
"direction": "in",
"databaseName": "MyDb",
"collectionName": "MyCollection",
"sqlQuery": "SELECT * from c where c.departmentId = {departmentId}",
"connectionStringSetting": "CosmosDBConnection"
}
配置部分解释了这些属性。The configuration section explains these properties.
C# 脚本代码如下所示:Here's the C# script code:
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 触发器,从查询字符串查找 IDHTTP trigger, look up ID from query string
以下示例演示检索单个文档的 C# 脚本函数。The following example shows a C# script function that retrieves a single document. 此函数由 HTTP 请求触发,该请求使用的查询字符串用于指定要查找的 ID 和分区键值。The function is triggered by an HTTP request that uses a query string to specify the ID and partition key value to look up. 该 ID 和分区键值用于从指定的数据库和集合中检索 ToDoItem
文档。That ID and partition key value are used to retrieve a ToDoItem
document from the specified database and collection.
function.json 文件如下所示:Here's the function.json file:
{
"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# 脚本代码如下所示:Here's the C# script code:
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 触发器,从路由数据查找 IDHTTP trigger, look up ID from route data
以下示例演示检索单个文档的 C# 脚本函数。The following example shows a C# script function that retrieves a single document. 此函数由 HTTP 请求触发,该请求使用的路由数据用于指定要查找的 ID 和分区键值。The function is triggered by an HTTP request that uses route data to specify the ID and partition key value to look up. 该 ID 和分区键值用于从指定的数据库和集合中检索 ToDoItem
文档。That ID and partition key value are used to retrieve a ToDoItem
document from the specified database and collection.
function.json 文件如下所示:Here's the function.json file:
{
"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# 脚本代码如下所示:Here's the C# script code:
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 触发器,使用 SqlQuery 获取多个文档HTTP trigger, get multiple docs, using SqlQuery
以下示例演示检索文档列表的 C# 脚本函数。The following example shows a C# script function that retrieves a list of documents. 此函数由 HTTP 请求触发。The function is triggered by an HTTP request. 此查询在 SqlQuery
特性属性中指定。The query is specified in the SqlQuery
attribute property.
function.json 文件如下所示:Here's the function.json file:
{
"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# 脚本代码如下所示:Here's the C# script code:
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 触发器,使用 DocumentClient 获取多个文档HTTP trigger, get multiple docs, using DocumentClient
以下示例演示检索文档列表的 C# 脚本函数。The following example shows a C# script function that retrieves a list of documents. 此函数由 HTTP 请求触发。The function is triggered by an HTTP request. 此代码使用 Azure Cosmos DB 绑定提供的 DocumentClient
实例来读取文档列表。The code uses a DocumentClient
instance provided by the Azure Cosmos DB binding to read a list of documents. DocumentClient
实例也可用于写入操作。The DocumentClient
instance could also be used for write operations.
function.json 文件如下所示:Here's the function.json file:
{
"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# 脚本代码如下所示:Here's the C# script code:
#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);
}
本部分包含以下示例:This section contains the following examples:
这些示例引用简单的 ToDoItem
类型:The examples refer to a simple ToDoItem
type:
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 触发器,从查询字符串查找 ID - 字符串参数HTTP trigger, look up ID from query string - String parameter
以下示例展示了检索单个文档的 Java 函数。The following example shows a Java function that retrieves a single document. 此函数由 HTTP 请求触发,该请求使用的查询字符串用于指定要查找的 ID 和分区键值。The function is triggered by an HTTP request that uses a query string to specify the ID and partition key value to look up. 该 ID 和分区键值用于以字符串形式从指定的数据库和集合中检索文档。That ID and partition key value are used to retrieve a document from the specified database and collection, in String form.
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 函数运行时库中,对其值将来自 Cosmos DB 的函数参数使用 @CosmosDBInput
注释。In the Java functions runtime library, use the @CosmosDBInput
annotation on function parameters whose value would come from Cosmos DB. 可以将此注释与本机 Java 类型、POJO 或使用了 Optional<T>
的可为 null 的值一起使用。This annotation can be used with native Java types, POJOs, or nullable values using Optional<T>
.
HTTP 触发器,从查询字符串查找 ID - POJO 参数HTTP trigger, look up ID from query string - POJO parameter
以下示例展示了检索单个文档的 Java 函数。The following example shows a Java function that retrieves a single document. 此函数由 HTTP 请求触发,该请求使用的查询字符串用于指定要查找的 ID 和分区键值。The function is triggered by an HTTP request that uses a query string to specify the ID and partition key value to look up. 该 ID 和分区键值用于从指定的数据库和集合中检索文档。That ID and partition key value used to retrieve a document from the specified database and collection. 然后将该文档转换为先前创建的 ToDoItem
POJO 实例,并作为参数传递给该函数。The document is then converted to an instance of the ToDoItem
POJO previously created, and passed as an argument to the function.
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 触发器,从路由数据查找 IDHTTP trigger, look up ID from route data
以下示例展示了检索单个文档的 Java 函数。The following example shows a Java function that retrieves a single document. 此函数由 HTTP 请求触发,该请求使用的路由参数用于指定要查找的 ID 和分区键值。The function is triggered by an HTTP request that uses a route parameter to specify the ID and partition key value to look up. 该 ID 和分区键值用于从指定的数据库和集合中检索文档,将它作为 Optional<String>
返回。That ID and partition key value are used to retrieve a document from the specified database and collection, returning it as an 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 触发器,使用 SqlQuery 从路由数据查找 IDHTTP trigger, look up ID from route data, using SqlQuery
以下示例展示了检索单个文档的 Java 函数。The following example shows a Java function that retrieves a single document. 此函数由 HTTP 请求触发,该请求使用路由参数指定要查找的 ID。The function is triggered by an HTTP request that uses a route parameter to specify the ID to look up. 该 ID 用于从指定的数据库和集合中检索文档,将结果集转换为 ToDoItem[]
,因为可能会返回许多文档,具体取决于查询条件。That ID is used to retrieve a document from the specified database and collection, converting the result set to a ToDoItem[]
, since many documents may be returned, depending on the query criteria.
备注
如果需要只按 ID 进行查询,则建议使用查找(如以前的示例所示),因为该查找消耗较少的请求单位。If you need to query by just the ID, it is recommended to use a look up, like the previous examples, as it will consume less request units. 点读取操作 (GET) 比按 ID 进行的查询更高效。Point read operations (GET) are more efficient than queries by ID.
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 触发器,使用 SqlQuery 从路由数据获取多个文档HTTP trigger, get multiple docs from route data, using SqlQuery
以下示例演示了检索多个文档的 Java 函数。The following example shows a Java function that retrieves multiple documents. 该函数由 HTTP 请求触发,该请求使用路由参数 desc
指定要在 description
字段中搜索的字符串。The function is triggered by an HTTP request that uses a route parameter desc
to specify the string to search for in the description
field. 搜索项用于从指定的数据库和集合中检索文档集合,将结果集转换为 ToDoItem[]
并将其作为参数传递给函数。The search term is used to retrieve a collection of documents from the specified database and collection, converting the result set to a ToDoItem[]
and passing it as an argument to the function.
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();
}
}
}
此部分包含的以下示例可以通过指定各种源提供的 ID 值来读取单个文档:This section contains the following examples that read a single document by specifying an ID value from various sources:
队列触发器,从 JSON 查找 IDQueue trigger, look up ID from JSON
以下示例演示 function.json 文件中的一个 Cosmos DB 输入绑定以及使用该绑定的 JavaScript 函数。The following example shows a Cosmos DB input binding in a function.json file and a JavaScript function that uses the binding. 该函数读取单个文档,并更新文档的文本值。The function reads a single document and updates the document's text value.
下面是 function.json 文件中的绑定数据:Here's the binding data in the function.json file:
{
"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"
}
配置部分解释了这些属性。The configuration section explains these properties.
JavaScript 代码如下所示:Here's the JavaScript code:
// 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 触发器,从查询字符串查找 IDHTTP trigger, look up ID from query string
以下示例演示检索单个文档的 JavaScript 函数。The following example shows a JavaScript function that retrieves a single document. 此函数由 HTTP 请求触发,该请求使用的查询字符串用于指定要查找的 ID 和分区键值。The function is triggered by an HTTP request that uses a query string to specify the ID and partition key value to look up. 该 ID 和分区键值用于从指定的数据库和集合中检索 ToDoItem
文档。That ID and partition key value are used to retrieve a ToDoItem
document from the specified database and collection.
function.json 文件如下所示:Here's the function.json file:
{
"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 代码如下所示:Here's the JavaScript code:
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 触发器,从路由数据查找 IDHTTP trigger, look up ID from route data
以下示例演示检索单个文档的 JavaScript 函数。The following example shows a JavaScript function that retrieves a single document. 此函数由 HTTP 请求触发,该请求使用的路由数据用于指定要查找的 ID 和分区键值。The function is triggered by an HTTP request that uses route data to specify the ID and partition key value to look up. 该 ID 和分区键值用于从指定的数据库和集合中检索 ToDoItem
文档。That ID and partition key value are used to retrieve a ToDoItem
document from the specified database and collection.
function.json 文件如下所示:Here's the function.json file:
{
"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 代码如下所示:Here's the JavaScript code:
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();
};
队列触发器,使用 SqlQuery 获取多个文档Queue trigger, get multiple docs, using SqlQuery
以下示例演示 function.json 文件中的一个 Azure Cosmos DB 输入绑定以及使用该绑定的 JavaScript 函数。The following example shows an Azure Cosmos DB input binding in a function.json file and a JavaScript function that uses the binding. 该函数使用队列触发器自定义查询参数检索 SQL 查询指定的多个文档。The function retrieves multiple documents specified by a SQL query, using a queue trigger to customize the query parameters.
队列触发器提供参数 departmentId
。The queue trigger provides a parameter departmentId
. { "departmentId" : "Finance" }
的队列消息将返回财务部的所有记录。A queue message of { "departmentId" : "Finance" }
would return all records for the finance department.
下面是 function.json 文件中的绑定数据:Here's the binding data in the function.json file:
{
"name": "documents",
"type": "cosmosDB",
"direction": "in",
"databaseName": "MyDb",
"collectionName": "MyCollection",
"sqlQuery": "SELECT * from c where c.departmentId = {departmentId}",
"connectionStringSetting": "CosmosDBConnection"
}
配置部分解释了这些属性。The configuration section explains these properties.
JavaScript 代码如下所示:Here's the JavaScript code:
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();
};
队列触发器,从 JSON 查找 IDQueue trigger, look up ID from JSON
下面的示例演示如何读取和更新单个 Cosmos DB 文档。The following example demonstrates how to read and update a single Cosmos DB document. 文档的唯一标识符通过队列消息中的 JSON 值提供。The document's unique identifier is provided through JSON value in a queue message.
Cosmos DB 输入绑定在函数配置文件 (function.json) 中提供的绑定列表中首先列出。The Cosmos DB input binding is listed first in the list of bindings found in the function's configuration file (function.json).
{
"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 文件包含 PowerShell 代码,该代码读取传入的文档并输出更改。The run.ps1 file has the PowerShell code which reads the incoming document and outputs changes.
param($QueueItem, $InputDocumentIn, $TriggerMetadata)
$Document = $InputDocumentIn
$Document.text = 'This was updated!'
Push-OutputBinding -Name InputDocumentOut -Value $Document
HTTP 触发器,从查询字符串查找 IDHTTP trigger, look up ID from query string
下面的示例演示如何通过 Web API 读取和更新单个 Cosmos DB 文档。The following example demonstrates how to read and update a single Cosmos DB document from a web API. 文档的唯一标识符通过 HTTP 请求中的 querystring 参数提供,如绑定的 "Id": "{Query.Id}"
属性所定义。The document's unique identifier is provided through a querystring parameter from the HTTP request, as defined in the binding's "Id": "{Query.Id}"
property.
Cosmos DB 输入绑定在函数配置文件 (function.json) 中提供的绑定列表中首先列出。The Cosmos DB input binding is listed first in the list of bindings found in the function's configuration file (function.json).
{
"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 文件包含 PowerShell 代码,该代码读取传入的文档并输出更改。The the run.ps1 file has the PowerShell code which reads the incoming document and outputs changes.
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 触发器,从路由数据查找 IDHTTP trigger, look up ID from route data
下面的示例演示如何通过 Web API 读取和更新单个 Cosmos DB 文档。The following example demonstrates how to read and update a single Cosmos DB document from a web API. 文档的唯一标识符通过 route 参数提供。The document's unique identifier is provided through a route parameter. route 参数在 HTTP 请求绑定的 route
属性中定义,并在 Cosmos DB "Id": "{Id}"
绑定属性中引用。The route parameter is defined in the HTTP request binding's route
property and referenced in the Cosmos DB "Id": "{Id}"
binding property.
Cosmos DB 输入绑定在函数配置文件 (function.json) 中提供的绑定列表中首先列出。The Cosmos DB input binding is listed first in the list of bindings found in the function's configuration file (function.json).
{
"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 文件包含 PowerShell 代码,该代码读取传入的文档并输出更改。The the run.ps1 file has the PowerShell code which reads the incoming document and outputs changes.
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
})
}
队列触发器,使用 SqlQuery 获取多个文档Queue trigger, get multiple docs, using SqlQuery
下面的示例演示如何读取多个 Cosmos DB 文档。The following example demonstrates how to read multiple Cosmos DB documents. 函数的配置文件 (function.json) 定义了包含 sqlQuery
的绑定属性。The function's configuration file (function.json) defines the binding properties, which includes the sqlQuery
. 提供给 sqlQuery
属性的 SQL 语句选择提供给函数的文档集。The SQL statement provided to the sqlQuery
property selects the set of documents provided to the function.
{
"name": "Documents",
"type": "cosmosDB",
"direction": "in",
"databaseName": "MyDb",
"collectionName": "MyCollection",
"sqlQuery": "SELECT * from c where c.departmentId = {departmentId}",
"connectionStringSetting": "CosmosDBConnection"
}
run1.ps 文件包含 PowerShell 代码,该代码读取传入的文档。The the run1.ps file has the PowerShell code which reads the incoming documents.
param($QueueItem, $Documents, $TriggerMetadata)
foreach ($Document in $Documents) {
# operate on each document
}