How to union all two tables in CosmosDB?

Xu, Kyson K 151 Reputation points
2024-03-26T08:25:33.9066667+00:00

How to union all two tables in Cosmos DB? Thanks

Azure Cosmos DB
Azure Cosmos DB
An Azure NoSQL database service for app development.
1,440 questions
{count} votes

Accepted answer
  1. Dillon Silzer 54,466 Reputation points
    2024-03-27T01:14:34.1833333+00:00

    Hello,

    I am just checking to clarify if you are actually speaking about Cosmos DB or not. Cosmos DB isn't typically utilized for traditional structured table-to-table calls. Instead, it usually should be handling semi-structured or unstructured data.

    However, if you're looking to merge data from different collections within Cosmos DB, you can certainly achieve that with your preferred programming language. Here's a Python script demonstrating how to do it:

    Code generated by ChatGPT:

    from azure.cosmos import CosmosClient
    
    # Initialize Cosmos DB client
    endpoint = "your_cosmosdb_endpoint_uri"
    key = "your_cosmosdb_primary_key"
    client = CosmosClient(endpoint, key)
    
    # Get database and containers
    database_id = 'your_database_id'
    container1_id = 'collection1_id'
    container2_id = 'collection2_id'
    database = client.get_database_client(database_id)
    container1 = database.get_container_client(container1_id)
    container2 = database.get_container_client(container2_id)
    
    # Define SQL queries
    query1 = 'SELECT * FROM c'
    query2 = 'SELECT * FROM c'
    
    # Query data from containers
    items1 = list(container1.query_items(query1, enable_cross_partition_query=True))
    items2 = list(container2.query_items(query2, enable_cross_partition_query=True))
    
    # Merge results
    merged_items = items1 + items2
    
    # Display merged items
    for item in merged_items:
        print(item)
    

    If this is helpful please accept answer.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful