我对应该是一个简单的任务感到困惑,通过gremlin查询检查文档的存在,如果没有插入文档。
给出以下功能:
public static async Task StoreAuditDetail(AuditDetailResponse auditDetail, string endpointUrl, string authorizationKey)
{
using (var cosmosClient = new DocumentClient(new Uri(endpointUrl), authorizationKey))
{
const string db = "iauditor-database";
const string collection = "audit-details";
Uri databaseUri = UriFactory.CreateDatabaseUri(db);
DocumentCollection graph = cosmosClient.CreateDocumentCollectionIfNotExistsAsync(
databaseUri,
new DocumentCollection { Id = collection },
new RequestOptions { OfferThroughput = 400 }).Result;
List<dynamic> q1 = cosmosClient.CreateGremlinQuery<dynamic>(graph,
$"g.V().hasLabel('audit-details').values('audit_id')"
).ExecuteNextAsync().Result.ToList();
if (!q1.Contains(auditDetail.audit_id))
{
try
{
await cosmosClient.CreateDocumentAsync(graph.DocumentsLink, auditDetail);
}
catch (Exception ex)
{
throw;
}
}
}
}
一切似乎都很好,但不幸的是,如果我尝试重新运行这个功能,我会有一个丑陋的回应:
ids的集合总是空的,我做错了什么?
提前致谢。
答案 0 :(得分:1)
我认为问题是因为异步调用,将 ExecuteGremlinQueryAsync
移到方法中并尝试
private static async Task ExecuteGremlinQueryAsync(DocumentClient client, DocumentCollection graph, string gremlinCommand)
{
IDocumentQuery<dynamic> query = client.CreateGremlinQuery<dynamic>(graph, gremlinCommand);
while (query.HasMoreResults)
{
foreach (dynamic result in await query.ExecuteNextAsync())
{
Console.WriteLine($"\t {JsonConvert.SerializeObject(result)}");
}
}
}
并将其命名为
await ExecuteGremlinQueryAsync(client, graph, gremlinCommand);
答案 1 :(得分:0)
如果您没有提供要查询的密钥,则无法搜索该密钥。
因此,请向您的存储对象提供您要搜索的密钥。
如果您正在寻找具有密钥的Vertice&#39;审核详情&#39;:
$"g.V().hasLabel('audit-details')'
CreateDocumentAsync不能是:
await cosmosClient.CreateDocumentAsync(graph.DocumentsLink, auditDetail);
它应该是这样的:
await cosmosClient.CreateDocumentAsync(graph.DocumentsLink, new { label = "audit-details", detail = auditDetail } );
或更好:
await cosmosClient.CreateDocumentAsync(graph.DocumentsLink, new { label = "audit-details", id = auditDetail.audit_id, detail = auditDetail } );
现在,您可以通过&#39;标签&#39;查询您的文档,也可以直接按&#39;键进行搜索:
public static async Task StoreAuditDetail(AuditDetailResponse auditDetail, string endpointUrl, string authorizationKey)
{
using (var cosmosClient = new DocumentClient(new Uri(endpointUrl), authorizationKey))
{
const string db = "iauditor-database";
const string collection = "audit-details";
Uri databaseUri = UriFactory.CreateDatabaseUri(db);
DocumentCollection graph = cosmosClient.CreateDocumentCollectionIfNotExistsAsync(
databaseUri,
new DocumentCollection { Id = collection },
new RequestOptions { OfferThroughput = 400 }).Result;
List<dynamic> q = cosmosClient.CreateGremlinQuery<dynamic>(graph,
$"g.V().hasLabel('audit-details').values('id')"
).ExecuteNextAsync().Result.ToList();
if (!q.Contains(auditDetail.audit_id))
{
try
{
await cosmosClient.CreateDocumentAsync(graph.DocumentsLink, new { label = "audit-details", id = auditDetail.audit_id, detail = auditDetail } );
}
catch (Exception ex)
{
throw;
}
}
}
}