在sql字符串中使用where条件将python传递到cosmosdb时出现问题

问题描述 投票:0回答:1
def run_query(ENDPOINT,KEY, unix_timestamp,token,container_name):
        client = CosmosClient(url=ENDPOINT, credential=KEY)
        database = client.get_database_client(database_name)
        container = database.get_container_client(container_name)
        general_query = "SELECT * FROM @container_name c WHERE c.RowKey>'@RowKey'"
        parameters = [
            {"name": "@PartitionKey", "value": str(token)},
            {"name": "@RowKey", "value": int(unix_timestamp)},
            {"name": "@database_name", "value": str(database_name)},
            {"name": "@container_name", "value": str(container_name)}
        ]

        for param in parameters:
            general_query = general_query.replace(param['name'], str(param['value']))
        items_tmp = list(container.query_items(query=general_query, 
            partition_key=token  # specifying the partition key
            ))
        return len(items_tmp)>0

以下 python 方法适用于以下情况

general_query = "SELECT * FROM @container_name c"

插入任何像这样的条件的那一刻

general_query = "SELECT * FROM @container_name c WHERE c.RowKey>'@RowKey'"

不起作用。

(我什至尝试过>'0',它涵盖了所有情况,但不起作用)

(我也尝试过 >0,不带引号,但不起作用)

python azure azure-cosmosdb azure-cosmosdb-sqlapi
1个回答
0
投票

感谢您的建议@Barmar。根据他的建议,您无需在

'@RowKey'
条件下添加引号
WHERE
。正如您在下面的输出中看到的那样,它在没有引号的情况下工作正常。

def run_query(ENDPOINT, KEY, unix_timestamp, partition_key_value, container_name):

    print("executing query")
    client = CosmosClient(url=ENDPOINT, credential=KEY)

    database = client.get_database_client(database_name)
    container = database.get_container_client(container_name)

    general_query = "SELECT * FROM c WHERE c.RowKey > @RowKey"

    parameters = [
        {"name": "@RowKey", "value": str(unix_timestamp)}
    ]

    items_tmp = list(container.query_items(
        query=general_query, 
        parameters=parameters,
        partition_key=partition_key_value  
    ))

    return len(items_tmp) > 0

result = run_query(ENDPOINT, KEY, unix_timestamp, partition_key_value, container_name)

print("Items found:", result)

输出:

executing query
Items found: True
© www.soinside.com 2019 - 2024. All rights reserved.