[DocumentDB .NET SDK]替换时ReadDocumentAsync和CreateDocumentQuery之间的区别是什么

时间:2018-01-26 06:39:28

标签: .net azure azure-cosmosdb

请先查看代码。

在步骤8中,不更新该字段。 在步骤11和12中,字段被更新。

我有两个问题。

替换时ReadDocumentAsync和CreateDocumentQuery之间有什么区别?

使用DocumentQuery获取的值进行替换是否合适?

ConsoleApp

NuGet包(Microsoft.Azure.DocumentDB 1.19.1,Newtonsoft.Json 9.0.1)

using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using Microsoft.Azure.Documents.Linq;
using Newtonsoft.Json;
using System;
using System.Collections.ObjectModel;
using System.Configuration;
using System.Linq;

class Program
{
    static string endpoint = ConfigurationManager.AppSettings["endpoint"];
    static string key = ConfigurationManager.AppSettings["key"];
    static string database = ConfigurationManager.AppSettings["database"];
    static string collection = ConfigurationManager.AppSettings["collection"];
    static void Main(string[] args)
    {
        ConnectionPolicy cp = new ConnectionPolicy()
        {
            ConnectionMode = ConnectionMode.Direct,
            ConnectionProtocol = Protocol.Https,
            RetryOptions = new RetryOptions()
            {
                MaxRetryAttemptsOnThrottledRequests = 5,
                MaxRetryWaitTimeInSeconds = 60,
            }
        };

        var client = new DocumentClient(new Uri(endpoint), key, cp);
        //Step1 Create Database
        client.CreateDatabaseIfNotExistsAsync(new Database { Id = database }).Wait();

        //Step2 Create Collection(400RU)
        client.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri(database),
            new DocumentCollection
            {
                Id = collection,
                PartitionKey = new PartitionKeyDefinition()
                { Paths = new Collection<string>() { "/partitionKey" } }
            }
            , new RequestOptions { OfferThroughput = 400 }).Wait();

        //Step3 Insert TestData
        var id1 = Guid.NewGuid().ToString();
        client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(database, collection)
            , new TestDocument() { TestField = "initialvalue", PartitionKey = "default", Id = id1, }).Wait();
        var id2 = Guid.NewGuid().ToString();
        client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(database, collection)
            , new TestDocument() { TestField = "initialvalue", PartitionKey = "default", Id = id2, }).Wait();

        //Step4 ID1 GetDocument(ReadDocument)
        var readDocument = client.ReadDocumentAsync<TestDocument>(UriFactory.CreateDocumentUri(database, collection, id1),
            new RequestOptions() { PartitionKey = new PartitionKey("default") }).Result.Document;

        //Step5 ID2 GetDocument(DocumentQuery)
        var queryDocument = client.CreateDocumentQuery<TestDocument>(UriFactory.CreateDocumentCollectionUri(database, collection),
            new FeedOptions { MaxItemCount = 1, EnableCrossPartitionQuery = false, })
            .Where(x => x.PartitionKey == "default" && x.Id == id2)
            .AsDocumentQuery().ExecuteNextAsync<TestDocument>().Result.FirstOrDefault();

        //Step6 ChangeValue
        readDocument.TestField = "newvalue";
        queryDocument.TestField = "newvalue";

        //Step7 ID1 Replace
        var updateResult1 = client.ReplaceDocumentAsync(UriFactory.CreateDocumentUri(database, collection, readDocument.Id), readDocument).Result;
        //Step8 ID2 Replace
        var updateResult2 = client.ReplaceDocumentAsync(UriFactory.CreateDocumentUri(database, collection, queryDocument.Id), queryDocument).Result;

        //Step9 ID1 select
        var id1Updated = client.ReadDocumentAsync<TestDocument>(UriFactory.CreateDocumentUri(database, collection, id1),
            new RequestOptions() { PartitionKey = new PartitionKey("default") }).Result.Document;
        //Step10 ID2 select
        var id2Updated = client.ReadDocumentAsync<TestDocument>(UriFactory.CreateDocumentUri(database, collection, id2),
            new RequestOptions() { PartitionKey = new PartitionKey("default") }).Result.Document;

        Console.WriteLine(id1Updated.TestField); //newvalue
        Console.WriteLine(id2Updated.TestField); //initialvalue
        Console.ReadLine();

        //Step11 ID2 SetPropertyValue
        queryDocument.SetPropertyValue("testField", "newvalue2");
        //Step12 ID2 Replace
        var updateResultX = client.ReplaceDocumentAsync(UriFactory.CreateDocumentUri(database, collection, queryDocument.Id), queryDocument).Result;
        //Step13 ID2 select
        var id2UpdatedX = client.ReadDocumentAsync<TestDocument>(UriFactory.CreateDocumentUri(database, collection, id2),
            new RequestOptions() { PartitionKey = new PartitionKey("default") }).Result.Document;
        Console.WriteLine(id2UpdatedX.TestField); //newvalue2
        Console.ReadLine();
    }
}
public class TestDocument : Document
{
    [JsonProperty("partitionKey")]
    public string PartitionKey { get; set; }
    [JsonProperty("testField")]
    public string TestField { get; set; }
}

1 个答案:

答案 0 :(得分:2)

  

ReadDocumentAsync和。之间有什么区别   替换时的CreateDocumentQuery?

您应该在查询中使用ReadDocumentAsync进行简单的ID查找。

在服务器端,ReadDocumentAsync(REST API上的GET)在吞吐量(RU)和延迟方面更轻量级。没有SQL解析/编译/索引扫描,它只是直接查找。

ReadDocumentAsync无法找到提及here的特定文档(在状态代码中返回404)时,

CreateDocumentQuery()将抛出该文档。

要处理此异常,您可以先使用private async Task updateDoc() { string EndpointUri = "xxxxx"; string PrimaryKey = "xxxxx"; DocumentClient client; client = new DocumentClient(new Uri(EndpointUri), PrimaryKey); Document doc = client.CreateDocumentQuery<Document>(UriFactory.CreateDocumentCollectionUri("db", "coll")) .Where(r => r.Id == "**") .AsEnumerable() .SingleOrDefault(); MyMode mode= (dynamic)doc; mode.name = "updated value"; //replace document Document updateddoc = await client.ReplaceDocumentAsync(doc.SelfLink, mode); Console.WriteLine(updateddoc); } public class MyMode { public string id { get; set; } public string name { get; set; } } 进行查询而不是直接阅读。然后,您只需获取结果集。

  

使用DocumentQuery获取的值是否合适   替换?

是的,您可以使用DocumentQuery获取的docuemnt来执行替换操作。请参阅以下代码片段:

  $(function () {
  var $overlay = $('.overlay');
  var $toggle = $('.toggle-menu');
  var toggleOverlay = function (evt) {
    if (!$(evt.target).closest($overlay).length) {
        $overlay.addClass('hidden');
    } else {
        $(document).one('click', toggleOverlay) .fadeIn(1000);
   }
  }
  $toggle.click(function (evt) {
    evt.preventDefault();
    evt.stopPropagation();
    $overlay.toggleClass('hidden');
    $(document).one('click', toggleOverlay) .fadeIn(1000);
  });
});

希望它对你有所帮助。

相关问题