问题
I'm attempting to get all distinct category values used in a container, where categories is an array of strings.
Looking at the Cosmos DB SQL docs, I've constructed the following query which works in the Emulator when I execute the SQL and returns an array of distinct categories as expected.
SELECT DISTINCT * FROM c IN s.categories
Results in
[
"Running",
"Rugby",
"Icon"
]
However, if I use the same query via the Cosmos .NET SDK I get an error
"Identifier 'session' could not be resolved."
Why would this query work in the Emulator but not via the SDK? Am I doing something wrong or this is an issue with the SDK?
Sample data:
{
"name": "Sample Entity",
"description": "<p></p>",
"startDateUtc": "2020-07-13T19:10:00Z",
"endDateUtc": "2020-07-13T20:00:00Z",
"categories": [
"Running",
"Icon"
],
"id": "h3foyhfk0a3betj1",
"dateCreated": "2020-07-15T06:33:57.9406583Z",
"lastUpdated": "2020-08-13T17:04:18.6182079Z" }
The SDK Code:
var query = new QueryDefinition("SELECT DISTINCT * FROM c IN s.categories");
var results = new List<TEntity>();
var resultSetIterator = _container.GetItemQueryIterator<TEntity>(query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey(partitionKey) });
while (resultSetIterator.HasMoreResults)
{
var response = await resultSetIterator.ReadNextAsync();
results.AddRange(response);
if (response.Diagnostics != null)
{
_logger.LogTrace($"\nQueryWithSqlParameters Diagnostics: {response.Diagnostics}");
}
}
return results;
回答1:
Remove , requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey(partitionKey)
.
Then you will get result. There maybe wrong in requestOptions
when you use.
var query = new QueryDefinition("SELECT DISTINCT * FROM c IN s.categories");
var results = new List<dynamic>();
var resultSetIterator = container.GetItemQueryIterator<dynamic>(query);
while (resultSetIterator.HasMoreResults)
{
var response = await resultSetIterator.ReadNextAsync();
results.AddRange(response);
if (response.Diagnostics != null)
{
Console.WriteLine($"\nQueryWithSqlParameters Diagnostics: {response.Diagnostics}");
}
}
来源:https://stackoverflow.com/questions/63402515/cosmos-db-array-query-doesnt-work-in-net-sdk