如何为文档生成序列号? [英] How to generate a sequence number for documents?

查看:83
本文介绍了如何为文档生成序列号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好, 

我需要为插入一个集合中的每个文档分配序列号(在事件处理解决方案中使用)。 

我发现以下建议暗示这个功能是由函数DocumentId(集合)实现的:

I have the need to assign an sequence number for each document inserted in one collection (used in an eventsourcing solution). 
I found the following suggestion which hints that such feature is implemented by the function DocumentId(collection):

https://feedback.azure.com/forums/263030 -azure-cosmos-db / suggestions / 6408183-i-want-atomic-counter

https://feedback.azure.com/forums/263030-azure-cosmos-db/suggestions/6408183-i-want-atomic-counter

直接从.NET代码插入文档时:

When inserting documents directly from .NET code as:

var _cosmosClient = new CosmosClient(new CosmosConfiguration(endpoint, accountKey));
var _container = _cosmosClient.Databases[DatabaseId].Containers[ContainerId];

for (int i = 0; i < 15; i++) {
    await _container.Items.CreateItemAsync("event", new { aggregateId = "event", id = Guid.NewGuid().ToString() });
}

将为每个文档生成递增序列号:

Will generate an incrementing sequencenumber for each document:

SELECT f.id, DocumentId(f) FROM Events f 
-->

[

    {
        "id": "2215dc32-89c1-464c-a559-0269be3068f4",
        "$1": 9
    },
    {
        "id": "ca6fac1c-59e1-42e2-858c-9646d6800a7e",
        "$1": 10
    },
    {
        "id": "54891f66-26de-461a-8ee7-2b23eb2d7c18",
        "$1": 11
    },
    {
        "id": "d8324e70-482c-448a-a117-5eb7e5ce56be",
        "$1": 12
    },
    {
        "id": "a57db830-0919-4f54-b9f7-9b74431a9f76",
        "$1": 13
    },
    {
        "id": "3597643c-957e-4284-a953-b7f0c7b74092",
        "$1": 14
    },
]




当通过存储过程插入多个文档时,我得到了DocumentId函数的不同行为,现在函数是ju st返回一个大整数,对于存储过程插入的每个文档都是相同的:

When inserting multiple documents via an stored procedure i get a different behavior of the DocumentId function, the function now just return a big integer number which is the same for each document that was inserted by the stored procedure:

    {
        "id": "046f1a2b-7e6c-488b-af4c-bb06762dae9d",
        "$1": 576460752303423500
    },
    {
        "id": "d4f5a8d3-3e5a-456c-8ec9-3967a4250a08",
        "$1": 576460752303423500
    },
    {
        "id": "HEAD",
        "$1": 576460752303423500
    }

有谁知道如何为同一个插入的文档生成一个序列号集合,与SQL服务器中的标识列非常相似。

Does anyone know how I can generate a sequence number for each inserted document in one and the same collection, very much the same as an Identity column in SQL server.

最好的问候

Nicals

存储过程如下所示:

function appendEvents(header, docs, etag) {

    var collection = getContext().getCollection();
    var collectionLink = collection.getSelfLink();

    // The count of imported docs, also used as current doc index.
    var count = 0;

    // Validate input.
    if (!docs) throw new Error("The array is undefined or null.");

    var docsLength = docs.length;
    if (docsLength === 0) {
        getContext().getResponse().setBody(0);
    }

    var options = { disableAutomaticIdGeneration: true };

    // Call the CRUD API to create a document.
    tryCreateEvent(docs[count], callback);

    // Insert or update the header:
    upsertStreamHeader(
        header,
        null,
        function (err, doc, options) {
            if (err) throw err;
        }
    );

    function tryCreateEvent(doc, callback) {

        // Assign the offset value relative from the header.offset:
        //doc.offset = header.offset + count + 1;

        var isAccepted = collection.createDocument(
            collectionLink,
            doc,
            options,
            callback
        );

        if (!isAccepted) getContext().getResponse().setBody(count);
    }

    // This is called when collection.createDocument is done and the document has been persisted.
    function callback(err, doc, options) {
        if (err) throw err;

        // One more document has been inserted, increment the count.
        count++;

        if (count >= docsLength) {
            // If we have created all documents, we are done. Just set the response.
            getContext().getResponse().setBody(count);
        } else {
            // Create next document.
            tryCreateEvent(docs[count], callback);
        }
    }

    function upsertStreamHeader(doc, continuation, callback) {

        var query = { query: "SELECT * FROM root r WHERE r.id = @id", parameters: [{ name: "@id", value: doc.id }] };
        var requestOptions = { continuation: continuation };

        var isAccepted = collection.queryDocuments(collectionLink, query, requestOptions, function (err, retrievedDocs, responseOptions) {
            if (err)
            {
                throw err;
            }

            if (retrievedDocs.length > 0)
            {
                tryReplaceStreamHeader(retrievedDocs[0], doc, callback);
            }
            else
            {
                tryCreateStreamHeader(doc, callback);
            }
        });

        if (!isAccepted) {
            throw new Error("Unable to query documents");
        }
    }

    function tryCreateStreamHeader(doc, callback) {
        var isAccepted = collection.createDocument(collectionLink, doc, callback);
        if (!isAccepted) {
            throw new Error("Unable to schedule create document");
        }
    }

    function tryReplaceStreamHeader(docToReplace, docContent, callback) {

        var isAccepted = collection.replaceDocument(
            docToReplace._self,
            docContent,
            { etag: etag },
            callback);

        if (!isAccepted) {
            throw new Error("Unable to schedule replace document");
        }
    }
}

推荐答案

感谢您详细解释这个问题。通过.Net客户端与存储过程的JavaScript创建文档对象时,序列号生成来自不同的运行时环境。

Thank you for detailing this question so well. When creating document objects via .Net client versus the JavaScript of a stored procedure, the sequence number generation is from different runtime environments.

如果查看
项目的属性
,那里已经为`_id`生成了唯一的系统生成值,但是没有为每个API公开。 

If you look at properties of an item, there is already unique system generated values being generated for `_id` but this is not exposed for every API. 

第二个选项是`id`字段,这是你正在工作的在您的解决方案中。

The second option is the `id` field, which is what you are working with in your solution.

关于此值的要求,我有一个问题。你问这个属性是否可以这种方式使用?是的,`id`字段可以用作SQL数据库中将使用的Identity列。此外,您需要在
中插入逻辑来控制在SP和.NET客户端中生成的序列值。

I have a question for you with regard to the requirements for this value. Are you asking if this property can be used in this manner? Yes, the `id` field can be used as Identity column would be used in SQL Database. Also, you will need to insert logic to control the sequence value being generated in both the SP and the .NET client.

如何在javascript中生成数字/字符序列?


这篇关于如何为文档生成序列号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆