Home > Software engineering >  How to query partitionkey in Cosmos DB?
How to query partitionkey in Cosmos DB?

Time:11-09

I'm using Azure Cosmos DB for NoSQL. I made a container with a partitionkey called 'pricedate' but not really. It's really called '/pricedate' because it's required to have the slash. How do I query it in python with azure.cosmos version 4.3.0 library?

I've tried:

x=container.query_items("select * from container c where c.pricedate='2018-04-01'", enable_cross_partition_query=True)
x.next()

Got a StopIteration error

x=container.query_items("select * from container c where c./pricedate='2018-04-01'", enable_cross_partition_query=True)
x.next()

Got a CosmosHttpResponseError for incorrect syntax around the /

x=container.query_items("select * from container c where c.\"/pricedate\"='2018-04-01'", enable_cross_partition_query=True)
x.next()

Got a CosmosHttpResponseError for incorrect syntax again.

For extra info...

x=container.read_all_items()
x.next()

returns:

{'id': '2018-04-01T04:00:00 00:00',
'da': 'full',
'rt': 'full',
'/pricedate': '2018-04-01',
'_rid': 'mu0HAOqArvIBAAAAAAAAAA==',
'_self': 'dbs/mu0HAA==/colls/mu0HAOqArvI=/docs/mu0HAOqArvIBAAAAAAAAAA==/',
'_etag': '"0600755a-0000-0100-0000-63692d300000"',
'_attachments': 'attachments/',
'_ts': 1667837232}

so there is definitely data that matches the query and it is all lower case.

CodePudding user response:

The problem is that when you define a partitionKey it forces it to begin a slash leading, at least me, to think that when inserting actual data that the slash continues to need to be used. That turns out not to be the case.

CodePudding user response:

StopIteration is a documented signal of Azure SDKs for Python: Screenshot of documentation explaining that StopIteration is raised when no more results

This means the query is not finding any results.

Based on your comments, you are not finding results on the Portal either, which means the Python SDK is behaving as expected (not finding results).

Based on the updated question with the document, the problem is the property name in your document. You are using "/pricedate" as the property name, which ideally should be "pricedate" (this matches your query).

Either change how you are writing your documents to use "pricedate" or if you can't, then change the query to:

select * from container c where c["/pricedate"]='2018-04-01'
  • Related