调用Azure函数中的cosmos DB存储过程



我在Azure Cosmos DB中有一个存储过程,它将从我的Cosmos DB删除记录。我试图从Azure函数调用该存储过程,但在执行存储过程(client.ExecuteStoredProcedureAsync(时遇到了一个与json解析相关的错误。我已经尝试将分区键更改为";id";但我还是犯了同样的错误。

这是我收到的错误消息:

"未能反序列化存储过程响应或将其转换为类型"System.String":分析值时遇到意外字符:{.Path",第1行,位置1

堆栈跟踪

位于Microsoft.Azure.Documents.Client.StoredProcedureResponse1..ctor(DocumentServiceResponse response, JsonSerializerSettings serializerSettings)rn at Microsoft.Azure.Documents.Client.DocumentClient.ExecuteStoredProcedurePrivateAsync[TValue](String storedProcedureLink, RequestOptions options, IDocumentClientRetryPolicy retryPolicyInstance, CancellationToken cancellationToken, Object[] procedureParams)rn at Microsoft.Azure.Documents.BackoffRetryUtility1.ExecuteRetryAsync(函数1 callbackMethod, Func3 callShouldRetry,函数1 inBackoffAlternateCallbackMethod, TimeSpan minBackoffForInBackoffCallback, CancellationToken cancellationToken, Action1 preRetryCallback(\r\n位于Microsoft.Azure.Documents。Documents.ShouldRetryResult.SthrowIfDoneTrying(ExceptionDispatchInfo capturedException(\r\n位于Microsoft.VisualStudio.Documents.BackoffRetryUtility1.ExecuteRetryAsync(Func1 callbackMethod,Func3 callShouldRetry, Func1 in BackoffAlternateCallbackMethod,TimeSpan minBackoffForInBackoffCallback,CancellationToken CancellationonToken,Action1 preRetryCallback)rn at FunctionApp2.Function1.Run(HttpRequest req, IAsyncCollector1 documentsOut,ILogger log(,位于C:\Users\source\repos\FunctionApp2\FunctionApp2\Function1.cs:line 36";

存储过程deleteStoreSample:

function bulkDeleteProcedure() {
var collection = getContext().getCollection();
var collectionLink = collection.getSelfLink();
var response = getContext().getResponse();
var responseBody = {
deleted: 0,
continuation: true
}; 
query = 'SELECT * FROM c WHERE c.submittedDate > "2002-08-31"';
// Validate input.
if (!query) 
throw new Error("The query is undefined or null.");
tryQueryAndDelete();
// Recursively runs the query w/ support for continuation  tokens.
// Calls tryDelete(documents) as soon as the query returns documents.
function tryQueryAndDelete(continuation) {
var requestOptions = {continuation: continuation};
var isAccepted = collection.queryDocuments(collectionLink, query, requestOptions, function (err, retrievedDocs, responseOptions) {
if (err) 
throw err;
if (retrievedDocs.length > 0) {
// Begin deleting documents as soon as documents are returned form the query results.
// tryDelete() resumes querying after deleting; no need to page through continuation tokens.
//  - this is to prioritize writes over reads given timeout constraints.
tryDelete(retrievedDocs);
} else if (responseOptions.continuation) {
// Else if the query came back empty, but with a continuation token; repeat the query w/ the token.
tryQueryAndDelete(responseOptions.continuation);
} else {
// Else if there are no more documents and no continuation token - we are finished deleting documents.
responseBody.continuation = false;
response.setBody(responseBody);
}
});
// If we hit execution bounds - return continuation: true.
if (!isAccepted) {
response.setBody(responseBody);
}
}
// Recursively deletes documents passed in as an array argument.
// Attempts to query for more on empty array.
function tryDelete(documents) {
if (documents.length > 0) {
// Delete the first document in the array.
var isAccepted = collection.deleteDocument(documents[0]._self, {}, function (err, responseOptions) {
if (err) throw err;
responseBody.deleted++;
documents.shift();
// Delete the next document in the array.
tryDelete(documents);
});
// If we hit execution bounds - return continuation: true.
if (!isAccepted) {
response.setBody(responseBody);
}
} else {
// If the document array is empty, query for more documents.
tryQueryAndDelete();
}
}

Azure功能:

[FunctionName("Function1")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
[CosmosDB(
databaseName: "dbName",
collectionName: "collectionName",
ConnectionStringSetting = "CosmosDbConnectionString")]IAsyncCollector<dynamic> documentsOut,
ILogger log)
{
try
{
log.LogInformation("C# HTTP trigger function processed a request.");
string endpoint = "https://account.documents.azure.com:443/";
string key = "gixxxx==";
var client = new DocumentClient(new Uri(endpoint), key);
Uri uri = UriFactory.CreateStoredProcedureUri("service-order", "ServiceOrder", "deleteStoreSample");
RequestOptions options = new RequestOptions { PartitionKey = new PartitionKey("/id") };
var result = await client.ExecuteStoredProcedureAsync<string>(uri, options);
var response = result.Response;
return new OkObjectResult(response);
}
catch (Exception ex)
{
throw ex;
}
}

我认为问题出在以下代码行:

RequestOptions options = new RequestOptions { PartitionKey = new PartitionKey("/id") };

实际上,您需要在这里指定分区键的值,而不是属性名称。

请尝试将其更改为类似以下内容:

RequestOptions options = new RequestOptions { PartitionKey = new PartitionKey("partition-key-value") };// Replace "partition-key-value" with actual value

最新更新