如何在Azure Cosmos DB SQL API中使用SQL参数进行CONTAINS查询?

时间:2019-03-18 02:51:40

标签: azure-cosmosdb azure-cosmosdb-sqlapi

我有以下sql变量:

SELECT * FROM x WHERE  x.Description CONTAINS(@p1)

我已经使用名称@ p1和有效字符串(即“ foo”)配置了一个SQL参数,并使用以下命令将其添加到SqlParameterCollection集合变量中:

var sqlQuery = new SqlQuerySpec(sql, collection);

然后我调用以下查询。

var query = _documentClient.CreateDocumentQuery<T>(GetDocumentCollectionUri<T>(graphRequestContext), sqlQuery, options).AsDocumentQuery();

我遇到以下错误:

消息:Microsoft.Azure.Documents.DocumentClientException:消息:{“错误”:[{“严重性”:“错误”,“位置”:{“开始”:37,“结束”:45},“代码“:” SC1001“,”消息“:”语法错误,'CONTAINS'附近的语法不正确。“}]} ActivityId:<< strong>出于隐私原因而删除,Microsoft.Azure.Documents.Common / 2.2.0.0,Windows / 10.0.17763 documentdb-netcore-sdk / 2.2.2

每个文档(https://docs.microsoft.com/en-us/azure/cosmos-db/sql-api-query-reference)似乎都在寻找字符串表达式。因此,如果确实如此,我正在寻求确认。

1 个答案:

答案 0 :(得分:1)

似乎您使用了错误的语法CONTAINS。请了解correct syntax

enter image description here

请参考下面的代码,它对我有用。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using System;

namespace DocumentDB.TestClass
{
    class CreateBySqlParam
    {
        private static readonly string endpointUrl = "https://***.documents.azure.com:443/";
        private static readonly string authorizationKey = "***";
        private static readonly string databaseId = "db";
        private static readonly string collectionId = "***";

        private static DocumentClient client;

        public static async void QueryTest()

        {
            client = new DocumentClient(new Uri(endpointUrl), authorizationKey);
            var uri = UriFactory.CreateDocumentCollectionUri(databaseId, collectionId);

            IQueryable<Pojo> queryable = client.CreateDocumentQuery<Pojo>(
                                                uri,
                                                new SqlQuerySpec
                                                {
                                                    QueryText = "SELECT c.id,c.name FROM c WHERE contains(c.name,@param)",
                                                    Parameters = new SqlParameterCollection()
                                                    {
                                                        new SqlParameter("@param", "n")
                                                    }

                                                }
            );

            foreach (Pojo p in queryable)
            {
                Console.WriteLine("\nRead {0}", p);
            }
        }
    }

    class Pojo : Document
    {
        public string id { get; set; }
        public string name { get; set; }
    }

}

输出:

enter image description here