首页 > 解决方案 > 如何使用 SqlQuerySpec 查询 CosmosDb 的多个结果

问题描述

我正在尝试使用数字列表获取多个文档。这是我的查询

var queryString = "Select * from c Where c.id in (@list)";
var queryParam = new Microsoft.Azure.Documents.SqlParameter("@list", string.Join(",", list.Select(x => $"{x.Id}").ToArray()));
var result = repo.Query(
    new SqlQuerySpec()
        {
            QueryText = queryString,
            Parameters = new Microsoft.Azure.Documents.SqlParameterCollection()
            {
                queryParam
            }
        }
    );

我的查询功能:

public IQueryable<TClass> Query(SqlQuerySpec sqlQuerySpec = null, bool allowScan = false, int? maxItems = null)
    {
        var feedOptions = new FeedOptions
        {
            EnableScanInQuery = allowScan,
            MaxItemCount = maxItems,
            EnableCrossPartitionQuery = true
        };
        var querySpec = sqlQuerySpec ?? new SqlQuerySpec();
        return sqlQuerySpec != null
            ? Client.CreateDocumentQuery<TClass>(Collection.DocumentsLink, querySpec, feedOptions) 
            : Client.CreateDocumentQuery<TClass>(Collection.DocumentsLink, feedOptions);
    }

它说有一个错误:one of the specified inputs is invalid

我究竟做错了什么?

标签: sqlazure-cosmosdb

解决方案


id是一个字符串,因此您需要将每个 id 用单引号括起来。

这一行:

var queryParam = new Microsoft.Azure.Documents.SqlParameter("@list", string.Join(",", list.Select(x => $"{x.Id}").ToArray()));

应该:

var queryParam = new Microsoft.Azure.Documents.SqlParameter("@list", string.Join(",", list.Select(x => $"'{x.Id}'").ToArray()));

推荐阅读