Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

CosmosDB Python get multiple items

I’m using the CosmosDB noSQL API and I feel like I’m not doing it right. The methods in the container class all return these iterator objects, which only have one method: next().

I need to get a list of records out of my container, and my only thought is to do this:

def to_list(iterator):
    list = []
    for i in range(0, 99):
        try:
            list.append(iterator.next())
        except:
            break
    return list

This works, but it feels bad. Is this going to be a performance problem? Does the Iterator class actually have all of my data in it? Like if I do the above with an iterator I get back, am I making 1 query to cosmos or 100?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I found this article which is using the methods in azure.cosmos.cosmos_client instead, but you still end up looping over everything. Is this normal, should I be using sqlalchemy or something instead?

What’s best practice for how to talk to CosmosDB using python?

>Solution :

If you’re trying to read all items in a container you can use this method.

item_list = list(container.read_all_items(max_item_count=10))

and this for a query.

items = list(container.query_items(
        query="SELECT * FROM r WHERE r.name=@name",
        parameters=[
            { "name":"@name", "value": "Mark" }
        ],
        enable_cross_partition_query=True
    ))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading