This document provides a detailed guide on how to create items within a Cosmos DB container using the Java SDK.
Prerequisites
Before you begin, ensure you have:
- Java Development Kit (JDK) installed.
- Maven or Gradle configured for your project.
- An Azure Cosmos DB account and a container created within it.
Creating an Item
The following code example demonstrates how to create a new item in a Cosmos DB container.
import com.azure.cosmos.cosmosclient.CosmosClient;
import com.azure.cosmos.models.Item;
public class CreateItemExample {
public static void main(String[] args) {
CosmosClient client = new CosmosClient("YOUR_ACCOUNT_ENDPOINT", "YOUR_ACCOUNT_KEY");
String databaseId = "YOUR_DATABASE_ID";
String containerId = "YOUR_CONTAINER_ID";
Item item = new Item("id", "name", "value");
client.readItem(databaseId, containerId, item.id);
}
}
Replace `YOUR_ACCOUNT_ENDPOINT`, `YOUR_ACCOUNT_KEY`, `YOUR_DATABASE_ID`, and `YOUR_CONTAINER_ID` with your actual values.
Understanding the Code
This code snippet demonstrates the core logic for creating an item. It initializes a CosmosClient instance with your account endpoint and key. It then constructs an Item object with an ID and relevant data fields. The `client.readItem` method is used to persist the item into the container.
Next Steps
Explore the following resources for more in-depth knowledge: