Cosmos DB - 문서 삭제
코스모스 DB에서 개별 레코드를 삭제하려면 어떻게 해야 합니까?
SQL 구문을 사용하여 선택할 수 있습니다.
SELECT *
FROM collection1
WHERE (collection1._ts > 0)
그리고 확실히 모든 문서(행과 유사)가 반환됩니다.
하지만 삭제하려고 하면 작동하지 않습니다.
DELETE
FROM collection1
WHERE (collection1._ts > 0)
어떻게 하면 그것을 달성할 수 있을까요?
문서DB API의 SQL은 특히 쿼리를 위한 것입니다.즉, 다음과 같은 기능만 제공합니다.SELECT,것은 아니다.UPDATE또는DELETE.
이러한 작업은 완전히 지원되지만 REST(또는 SDK) 호출이 필요합니다.예를 들어 .net을 사용하면DeleteDocumentAsync()또는ReplaceDocumentAsync()그리고 node.js에서, 이것은 다음과 같은 전화일 것입니다.deleteDocument()또는replaceDocument().
특정 시나리오에서 다음을 실행할 수 있습니다.SELECT삭제할 문서를 식별한 다음 문서당 하나씩 "삭제" 호출을 수행합니다(또는 효율성 및 트랜잭션 기능을 위해 삭제할 문서 배열을 저장 프로시저로 전달).
가장 쉬운 방법은 Azure Storage Explorer를 사용하는 것입니다.연결 후 선택한 컨테이너로 드릴다운하여 문서를 선택한 후 삭제할 수 있습니다.Cosmos DB용 추가 도구는 https://gotcosmos.com/tools 에서 확인할 수 있습니다.
고려해야 할 또 다른 옵션은 TTL(Time to Live)입니다.수집에 대해 이 옵션을 설정한 다음 문서의 만료 기간을 설정할 수 있습니다.문서가 만료되면 자동으로 정리됩니다.
다음 코드를 사용하여 저장 프로시저를 만듭니다.
/**
* A Cosmos DB stored procedure that bulk deletes documents for a given query.
* Note: You may need to execute this stored procedure multiple times (depending whether the stored procedure is able to delete every document within the execution timeout limit).
*
* @function
* @param {string} query - A query that provides the documents to be deleted (e.g. "SELECT c._self FROM c WHERE c.founded_year = 2008"). Note: For best performance, reduce the # of properties returned per document in the query to only what's required (e.g. prefer SELECT c._self over SELECT * )
* @returns {Object.<number, boolean>} Returns an object with the two properties:
* deleted - contains a count of documents deleted
* continuation - a boolean whether you should execute the stored procedure again (true if there are more documents to delete; false otherwise).
*/
function bulkDeleteStoredProcedure(query) {
var collection = getContext().getCollection();
var collectionLink = collection.getSelfLink();
var response = getContext().getResponse();
var responseBody = {
deleted: 0,
continuation: true
};
// 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();
}
}
}
그리고 파티션 키(예: null)와 쿼리를 사용하여 문서를 선택합니다(예: SELECT c._self FROM c를 사용하여 모두 삭제).
Query Explorer를 통한 조건에 따라 CosmosDB에서 문서 삭제 기준
다음은 .net Cosmos SDK V3를 사용하여 bulkDeleteStoredProcedure를 사용하는 방법의 예입니다.
실행 범위 때문에 ContinuationFlag를 사용해야 합니다.
private async Task<int> ExecuteSpBulkDelete(string query, string partitionKey)
{
var continuationFlag = true;
var totalDeleted = 0;
while (continuationFlag)
{
StoredProcedureExecuteResponse<BulkDeleteResponse> result = await _container.Scripts.ExecuteStoredProcedureAsync<BulkDeleteResponse>(
"spBulkDelete", // your sproc name
new PartitionKey(partitionKey), // pk value
new[] { sql });
var response = result.Resource;
continuationFlag = response.Continuation;
var deleted = response.Deleted;
totalDeleted += deleted;
Console.WriteLine($"Deleted {deleted} documents ({totalDeleted} total, more: {continuationFlag}, used {result.RequestCharge}RUs)");
}
return totalDeleted;
}
및 반응 모델:
public class BulkDeleteResponse
{
[JsonProperty("deleted")]
public int Deleted { get; set; }
[JsonProperty("continuation")]
public bool Continuation { get; set; }
}
아래 방법으로 c#을 사용하여 cosmosdb에서 단일 문서를 삭제할 수 있습니다 - 아래 방법을 cosmosdb 컨테이너 인스턴스와 함께 사용할 수 있습니다.
고객 컨테이너.항목 비동기 삭제(id, 새 파티션 키("파티션 키의 모든 값")
T -> 컨테이너에 있는 항목의 유형입니다.
id -> 삭제할 항목의 guid입니다.(이를 위해 먼저 select query를 사용하여 cosmosdb에서 항목을 가져올 수 있습니다.
Any Value of PartitionKey - 대부분의 경우 코스모스 db 컨테이너로 파티션 키를 생성하므로, 여기서는 해당 키에 대한 값을 ex에 제공해야 합니다. - 제 키는 customerCity이므로 "Goa"를 제공했습니다.
언급URL : https://stackoverflow.com/questions/46871925/cosmos-db-deleting-a-document
'programing' 카테고리의 다른 글
| Azure App Service 인스턴스를 다시 시작하는 방법 (0) | 2023.05.05 |
|---|---|
| WPF에서 스택 패널과 독 패널의 차이점은 무엇입니까? (0) | 2023.05.05 |
| pyenv를 사용하여 virtualenv를 활성화하지 못했습니다. (0) | 2023.05.05 |
| "git fetch --tags"에 "git fetch"가 포함되어 있습니까? (0) | 2023.05.05 |
| 액세스 97에서 전체 경로의 디렉터리 부분(파일 이름 제외) 찾기 (0) | 2023.05.05 |
