快速入門:使用 Java SDK 與 Azure Cosmos DB 建置資料表 API 應用程式

適用於: Table

本快速入門說明如何從 .NET 應用程式存取 Azure Cosmos DB 資料表 API。 Azure Cosmos DB 資料表 API 是無架構資料存放區,可讓應用程式將結構化的 NoSQL 資料儲存在雲端中。 由於資料儲存在無架構設計中,當具有新屬性的物件被新增至資料表時,新的屬性 (資料行) 會自動新增至資料表中。

Java 應用程式可以使用 azure-data-tables 用戶端程式庫來存取 Azure Cosmos DB 資料表 API。

必要條件

範例應用程式是以 Spring Boot 2.6.4 撰寫,您可以使用 Visual Studio CodeIntelliJ IDEA 作為 IDE。

如果您沒有 Azure 訂用帳戶,請在開始前建立免費帳戶

範例應用程式

本教學課程的應用程式範例可從存放庫 https://github.com/Azure-Samples/msdocs-azure-data-tables-sdk-java 複製或下載。 入門和已完成的應用程式都包含在樣本存放庫中。

git clone https://github.com/Azure-Samples/msdocs-azure-data-tables-sdk-java

應用程式範例會以氣象資料為例,來示範資料表 API 的功能。 代表氣象觀察的物件會使用資料表 API 來儲存和取出,其中包括儲存具有其他屬性的物件以藉此示範資料表 API 的無架構功能。

A screenshot of the finished application showing data stored in an Azure Cosmos DB table using the Table API.

1 - 建立 Azure Cosmos DB 帳戶

您必須先建立 Azure Cosmos DB 資料表 API 帳戶,其中會包含您應用程式中所使用的資料表。 您可以使用 Azure 入口網站、Azure CLI 或 Azure PowerShell 來完成此操作。

登入 Azure 入口網站,並遵循下列步驟來建立 Azure Cosmos DB 帳戶。

指示 Screenshot
在 Azure 入口網站中:
  1. 在 Azure 入口網站頂端的搜尋列中,輸入「Azure Cosmos DB」。
  2. 在出現在搜尋列下方的功能表上,選取 [服務] 下標示為 [Azure Cosmos DB] 的項目。
A screenshot showing how to use the search box in the top tool bar to find Azure Cosmos DB accounts in Azure.
在 [Azure Cosmos DB] 頁面上,選取 [+ 建立] A screenshot showing the Create button location on the Azure Cosmos DB accounts page in Azure.
在 [選取 API 選項] 頁面上,選擇 [Azure 資料表] 選項。 A screenshot showing the Azure Table option as the correct option to select.
在 [建立 Azure Cosmos DB 帳戶 - Azure 資料表] 頁面上,以如下方式填寫表單。
  1. 選取 [資源群組] 下的 [新建] 連結,以為名為 rg-msdocs-tables-sdk-demo 的儲存體帳戶建立全新資源群組。
  2. 將您的儲存體帳戶取名為 cosmos-msdocs-tables-sdk-demo-XYZ,其中 XYZ 為任意三個隨機字元,藉此建立出唯一的帳戶名稱。 Azure Cosmos DB 帳戶名稱的長度必須介於 3 到 44 個字元之間,且只能包含小寫字母、數字或連字號 (-) 字元。
  3. 選取儲存體帳戶的區域。
  4. 選取 [標準] 效能。
  5. 在 [容量模式] 下,為此範例選取 [已佈建輸送量]
  6. 針對此範例,請選取 [套用免費階層折扣] 下的 [套用]
  7. 選取畫面底部的 [檢閱 + 建立] 按鈕,然後在摘要畫面上選取 [建立] 以建立 Azure Cosmos DB 帳戶。 此程序可能需要幾分鐘的時間。
A screenshot showing how to fill out the fields on the Azure Cosmos DB Account creation page.

2 - 建立資料表

接下來,您必須在 Azure Cosmos DB 帳戶內建立資料表以供應用程式使用。 與傳統資料庫不同的是,您只需要指定資料表的名稱,而無須指定資料表中的屬性 (資料行)。 當資料載入至資料表時,系統會視需要自動建立屬性 (資料行)。

Azure 入口網站中完成下列步驟,以在您的 Azure Cosmos DB 帳戶內建立資料表。

指示 Screenshot
在 Azure 入口網站中,瀏覽至 Azure Cosmos DB 帳戶的概觀頁面。 您可以在頂端的搜尋列中鍵入 Azure Cosmos DB 帳戶的名稱 (cosmos-msdocs-tables-sdk-demo-XYZ),並在資源標題下方查看,以巡覽至您 Azure Cosmos DB 帳戶的概觀頁面。選取 Azure Cosmos DB 帳戶的名稱以前往概觀頁面。 A screenshot showing how to use the search box in the top tool bar to find your Azure Cosmos DB account.
在概觀頁面上,選取 [+ 新增資料表]。 [新增資料表] 對話方塊會從頁面右側滑出。 A screenshot showing the location of the Add Table button.
在 [新增資料表] 對話方塊中,以如下方式填寫表單。
  1. 在資料表識別碼中輸入名稱 WeatherData。 這是資料表的名稱。
  2. 在此範例中,選取 [資料表輸送量 (自動調整)] 下的 [手動]
  3. 在預估 RU/秒中使用預設值 400。
  4. 選取 [確定] 按鈕以建立資料表。
A screenshot showing how to New Table dialog box for an Azure Cosmos DB table.

3 - 取得 Azure Cosmos DB 連接字串

您的應用程式需要有 CosmosDB 儲存體帳戶的資料表連接字串,才能存取您在 Azure Cosmos DB 中的資料表。 您可以使用 Azure 入口網站、Azure CLI 或 Azure PowerShell 來擷取連接字串。

指示 Screenshot
在 [Azure Cosmos DB 帳戶] 頁面的左側,在 [設定] 標題下找出名為 [連接字串] 的功能表項目,然後將其選取。 系統會將您帶往一個頁面,您可以在其中擷取儲存體帳戶的連接字串。 A screenshot showing the location of the connection strings link on the Azure Cosmos DB page.
複製要在應用程式中使用的「主要連接字串」值。 A screenshot showing the which connection string to select and use in your application.

您的 Azure Cosmos DB 帳戶連接字串會被視為應用程式祕密,且必須像其他任何應用程式祕密或密碼一樣受到保護。 此範例會使用 POM,以在開發期間儲存連接字串,並將其提供給應用程式使用。

<profiles>
    <profile>
        <id>local</id>
        <properties>
            <azure.tables.connection.string>
                <![CDATA[YOUR-DATA-TABLES-SERVICE-CONNECTION-STRING]]>
            </azure.tables.connection.string>
            <azure.tables.tableName>WeatherData</azure.tables.tableName>
        </properties>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
    </profile>
</profiles>

4 - 包含 azure-data-tables 套件

若要從 Java 應用程式存取 Azure Cosmos DB 資料表 API,請包含 azure-data-tables 套件。

<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-data-tables</artifactId>
    <version>12.2.1</version>
</dependency>

5 - 設定 TableServiceConfig.java 中的資料表用戶端

Azure SDK 會使用用戶端物件來與 Azure 進行通訊,並藉此對 Azure 執行不同的作業。 TableClient 物件是用來與 Azure Cosmos DB 資料表 API 通訊的物件。

應用程式通常會為每個資料表建立單一 TableClient 物件,以便在整個應用程式中使用。 建議您指出方法會產生要由 Spring 容器管理的 TableClient 物件 Bean,並作為單一資料庫完成這項作業。

在應用程式的 TableServiceConfig.java 檔案中,編輯 tableClientConfiguration() 方法以符合下列程式碼片段:

@Configuration
public class TableServiceConfiguration {

    private static String TABLE_NAME;

    private static String CONNECTION_STRING;

    @Value("${azure.tables.connection.string}")
    public void setConnectionStringStatic(String connectionString) {
        TableServiceConfiguration.CONNECTION_STRING = connectionString;
    }

    @Value("${azure.tables.tableName}")
    public void setTableNameStatic(String tableName) {
        TableServiceConfiguration.TABLE_NAME = tableName;
    }

    @Bean
    public TableClient tableClientConfiguration() {
        return new TableClientBuilder()
                .connectionString(CONNECTION_STRING)
                .tableName(TABLE_NAME)
                .buildClient();
    }
    
}

您也必須在 TableServiceConfig.java 檔案頂端新增下列 using 陳述式。

import com.azure.data.tables.TableClient;
import com.azure.data.tables.TableClientBuilder;

6 - 實作 Azure Cosmos DB 資料表作業

樣本應用程式的所有 Azure Cosmos DB 資料表作業都會在位於 [服務] 目錄的 TablesServiceImpl 類別中實作。 您必須匯入 com.azure.data.tables SDK 套件。

import com.azure.data.tables.TableClient;
import com.azure.data.tables.models.ListEntitiesOptions;
import com.azure.data.tables.models.TableEntity;
import com.azure.data.tables.models.TableTransactionAction;
import com.azure.data.tables.models.TableTransactionActionType;

TableServiceImpl 類別的開頭,為 TableClient 物件新增成員變數和建構函式,讓 TableClient 物件能夠插入至類別中。

@Autowired
private TableClient tableClient;

從資料表取得資料列

TableClient 類別中包含一個名為 listEntities 的方法,可讓您從資料表中選取資料列。 在此範例中,因為未將任何參數傳遞至方法,所以會從資料表中選取所有資料列。

此方法也採用類型為 TableEntity 的泛型參數,其能夠指定傳回資料的模型類別。 本案例使用了內建類別 TableEntity,這表示 listEntities 方法會傳回 PagedIterable<TableEntity> 集合作為其結果。

public List<WeatherDataModel> retrieveAllEntities() {
    List<WeatherDataModel> modelList = tableClient.listEntities().stream()
        .map(WeatherDataUtils::mapTableEntityToWeatherDataModel)
        .collect(Collectors.toList());
    return Collections.unmodifiableList(WeatherDataUtils.filledValue(modelList));
}

com.azure.data.tables.models 套件中定義的 TableEntity 類別具有資料表中分割區索引鍵和資料列索引鍵值的屬性。 這兩個值合併使用時,便能做為資料表中資料列的唯一索引鍵。 在此範例應用程式中,氣象站 (城市) 名稱會儲存在分割區索引鍵中,而觀察的日期/時間則會儲存在資料列索引鍵中。 所有其他屬性 (溫度、濕度、風速) 都會儲存在 TableEntity 物件的字典中。

常見的做法是將 TableEntity 物件對應至您自己定義的物件上。 範例應用程式定義一個位於「模型」目錄內的 WeatherDataModel 類別來達成此目的。 此類別具有與分割區索引鍵和資料列索引鍵對應的工作站名稱和觀察日期的屬性,為這些值提供更有意義的屬性名稱。 然後其會使用字典來儲存物件上的所有其他屬性。 這是使用資料表儲存體時的常見模式,因為資料列可以有任意數目的任意屬性,而我們希望模型物件能夠擷取到所有屬性。 這個類別也包含了可列出類別上屬性的方法。

public class WeatherDataModel {

    public WeatherDataModel(String stationName, String observationDate, OffsetDateTime timestamp, String etag) {
        this.stationName = stationName;
        this.observationDate = observationDate;
        this.timestamp = timestamp;
        this.etag = etag;
    }

    private String stationName;

    private String observationDate;

    private OffsetDateTime timestamp;

    private String etag;

    private Map<String, Object> propertyMap = new HashMap<String, Object>();

    public String getStationName() {
        return stationName;
    }

    public void setStationName(String stationName) {
        this.stationName = stationName;
    }

    public String getObservationDate() {
        return observationDate;
    }

    public void setObservationDate(String observationDate) {
        this.observationDate = observationDate;
    }

    public OffsetDateTime getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(OffsetDateTime timestamp) {
        this.timestamp = timestamp;
    }

    public String getEtag() {
        return etag;
    }

    public void setEtag(String etag) {
        this.etag = etag;
    }

    public Map<String, Object> getPropertyMap() {
        return propertyMap;
    }

    public void setPropertyMap(Map<String, Object> propertyMap) {
        this.propertyMap = propertyMap;
    }
}

mapTableEntityToWeatherDataModel 方法能用來將 TableEntity 物件對應至 WeatherDataModel 物件。 mapTableEntityToWeatherDataModel 方法會直接對應 PartitionKeyRowKeyTimestampEtag 屬性,然後使用 properties.keySet 來反覆查看 TableEntity 物件中的其他屬性,並將這些屬性對應至 WeatherDataModel 物件,減去已經直接對應的屬性。

編輯 mapTableEntityToWeatherDataModel 方法中的程式碼以符合下列程式碼區塊。

public static WeatherDataModel mapTableEntityToWeatherDataModel(TableEntity entity) {
    WeatherDataModel observation = new WeatherDataModel(
        entity.getPartitionKey(), entity.getRowKey(),
        entity.getTimestamp(), entity.getETag());
    rearrangeEntityProperties(observation.getPropertyMap(), entity.getProperties());
    return observation;
}

private static void rearrangeEntityProperties(Map<String, Object> target, Map<String, Object> source) {
    Constants.DEFAULT_LIST_OF_KEYS.forEach(key -> {
        if (source.containsKey(key)) {
            target.put(key, source.get(key));
        }
    });
    source.keySet().forEach(key -> {
        if (Constants.DEFAULT_LIST_OF_KEYS.parallelStream().noneMatch(defaultKey -> defaultKey.equals(key))
        && Constants.EXCLUDE_TABLE_ENTITY_KEYS.parallelStream().noneMatch(defaultKey -> defaultKey.equals(key))) {
            target.put(key, source.get(key));
        }
    });
}

篩選從資料表傳回的資料列

若要篩選從資料表傳回的資料列,您可以將 OData 樣式篩選字串傳遞至 listEntities 方法。 例如,如果您想要取得在 2021 年 7 月 1 日午夜與 2021 年 7 月 2 日午夜 (含) 之間芝加哥的所有氣象讀數,您會傳入下列篩選字串。

PartitionKey eq 'Chicago' and RowKey ge '2021-07-01 12:00 AM' and RowKey le '2021-07-02 12:00 AM'

您可以在 OData 網站的 [篩選系統查詢選項] 區段中,檢視所有 OData 篩選運算子。

在範例應用程式中,FilterResultsInputModel 物件的目的是擷取使用者所提供的任何篩選準則。

public class FilterResultsInputModel implements Serializable {

    private String partitionKey;

    private String rowKeyDateStart;

    private String rowKeyTimeStart;

    private String rowKeyDateEnd;

    private String rowKeyTimeEnd;

    private Double minTemperature;

    private Double maxTemperature;

    private Double minPrecipitation;

    private Double maxPrecipitation;

    public String getPartitionKey() {
        return partitionKey;
    }

    public void setPartitionKey(String partitionKey) {
        this.partitionKey = partitionKey;
    }

    public String getRowKeyDateStart() {
        return rowKeyDateStart;
    }

    public void setRowKeyDateStart(String rowKeyDateStart) {
        this.rowKeyDateStart = rowKeyDateStart;
    }

    public String getRowKeyTimeStart() {
        return rowKeyTimeStart;
    }

    public void setRowKeyTimeStart(String rowKeyTimeStart) {
        this.rowKeyTimeStart = rowKeyTimeStart;
    }

    public String getRowKeyDateEnd() {
        return rowKeyDateEnd;
    }

    public void setRowKeyDateEnd(String rowKeyDateEnd) {
        this.rowKeyDateEnd = rowKeyDateEnd;
    }

    public String getRowKeyTimeEnd() {
        return rowKeyTimeEnd;
    }

    public void setRowKeyTimeEnd(String rowKeyTimeEnd) {
        this.rowKeyTimeEnd = rowKeyTimeEnd;
    }

    public Double getMinTemperature() {
        return minTemperature;
    }

    public void setMinTemperature(Double minTemperature) {
        this.minTemperature = minTemperature;
    }

    public Double getMaxTemperature() {
        return maxTemperature;
    }

    public void setMaxTemperature(Double maxTemperature) {
        this.maxTemperature = maxTemperature;
    }

    public Double getMinPrecipitation() {
        return minPrecipitation;
    }

    public void setMinPrecipitation(Double minPrecipitation) {
        this.minPrecipitation = minPrecipitation;
    }

    public Double getMaxPrecipitation() {
        return maxPrecipitation;
    }

    public void setMaxPrecipitation(Double maxPrecipitation) {
        this.maxPrecipitation = maxPrecipitation;
    }
}

將這個物件傳遞至 TableServiceImpl 類別中的 retrieveEntitiesByFilter 方法時,其會為每個非 null 的屬性值建立一個篩選字串。 然後其會將所有值與「and」子句聯結在一起,以建立出合併的篩選字串。 這個合併的篩選字串會傳遞至 TableClient 物件上的 listEntities 方法,且僅會傳回符合篩選字串的資料列。 您可以在程式碼中使用類似的方法,藉此視您應用程式的需要來建構適當的篩選字串。

public List<WeatherDataModel> retrieveEntitiesByFilter(FilterResultsInputModel model) {

    List<String> filters = new ArrayList<>();

    if (!StringUtils.isEmptyOrWhitespace(model.getPartitionKey())) {
        filters.add(String.format("PartitionKey eq '%s'", model.getPartitionKey()));
    }
    if (!StringUtils.isEmptyOrWhitespace(model.getRowKeyDateStart())
            && !StringUtils.isEmptyOrWhitespace(model.getRowKeyTimeStart())) {
        filters.add(String.format("RowKey ge '%s %s'", model.getRowKeyDateStart(), model.getRowKeyTimeStart()));
    }
    if (!StringUtils.isEmptyOrWhitespace(model.getRowKeyDateEnd())
            && !StringUtils.isEmptyOrWhitespace(model.getRowKeyTimeEnd())) {
        filters.add(String.format("RowKey le '%s %s'", model.getRowKeyDateEnd(), model.getRowKeyTimeEnd()));
    }
    if (model.getMinTemperature() != null) {
        filters.add(String.format("Temperature ge %f", model.getMinTemperature()));
    }
    if (model.getMaxTemperature() != null) {
        filters.add(String.format("Temperature le %f", model.getMaxTemperature()));
    }
    if (model.getMinPrecipitation() != null) {
        filters.add(String.format("Precipitation ge %f", model.getMinPrecipitation()));
    }
    if (model.getMaxPrecipitation() != null) {
        filters.add(String.format("Precipitation le %f", model.getMaxPrecipitation()));
    }

    List<WeatherDataModel> modelList = tableClient.listEntities(new ListEntitiesOptions()
        .setFilter(String.join(" and ", filters)), null, null).stream()
        .map(WeatherDataUtils::mapTableEntityToWeatherDataModel)
        .collect(Collectors.toList());
    return Collections.unmodifiableList(WeatherDataUtils.filledValue(modelList));
}

使用 TableEntity 物件插入資料

將資料新增至資料表的最簡單方法為使用 TableEntity 物件。 在此範例中,資料會從輸入模型物件對應至 TableEntity 物件。 輸入物件上代表氣象站名稱和觀察日期/時間的屬性會分別對應至 PartitionKeyRowKey 屬性,以形成資料表中該資料列的唯一索引鍵。 然後,輸入模型物件上的其他屬性會對應到 TableClient 物件上的字典屬性。 最後,使用 TableClient 物件上的 createEntity 方法來將資料插入至資料表中。

修改範例應用程式中的 insertEntity 類別以包含下列程式碼。

public void insertEntity(WeatherInputModel model) {
    tableClient.createEntity(WeatherDataUtils.createTableEntity(model));
}

使用 TableEntity 物件來 upsert 資料

如果您嘗試使用已經存在於該資料表中的分割區索引鍵/資料列索引鍵組合,來將資料列插入資料表中,您將會收到錯誤訊息。 基於這個理由,在將資料列新增至資料表時,通常最好使用 upsertEntity 來取代 insertEntity 方法。 如果指定的分割區索引鍵/資料列索引鍵組合已經存在於資料表中,upsertEntity 方法便會更新現有的資料列。 否則,便會將資料列新增至資料表中。

public void upsertEntity(WeatherInputModel model) {
    tableClient.upsertEntity(WeatherDataUtils.createTableEntity(model));
}

使用變數屬性插入或 upsert 資料

使用 Azure Cosmos DB Tables API 的其中一項優點,就是如果載入資料表的物件包含任何新屬性,則這些屬性會自動新增至資料表,而值則會儲存在 Azure Cosmos DB 中。 您不需像在傳統資料庫中一樣,執行 ALTER TABLE 等 DDL 陳述式來新增資料行。

若之後因資料來源而需要新增或修改所需擷取的資料,或是當不同的輸入端為應用程式提供不同的資料時,這種模型可讓您的應用程式更有彈性。 在範例應用程式中,我們所模擬的氣象站不只能傳送基本的氣象資料,還有一些額外的值。 當具有這些新屬性的物件第一次儲存到資料表中時,對應的屬性 (資料行) 也會自動新增至資料表中。

在範例應用程式中,ExpandableWeatherObject 類別是根據內部字典所建立,以支援物件上的任何屬性集。 此類別代表著當物件需要包含任意一組屬性時的一般模式。

public class ExpandableWeatherObject {

    private String stationName;

    private String observationDate;

    private Map<String, Object> propertyMap = new HashMap<String, Object>();

    public String getStationName() {
        return stationName;
    }

    public void setStationName(String stationName) {
        this.stationName = stationName;
    }

    public String getObservationDate() {
        return observationDate;
    }

    public void setObservationDate(String observationDate) {
        this.observationDate = observationDate;
    }

    public Map<String, Object> getPropertyMap() {
        return propertyMap;
    }

    public void setPropertyMap(Map<String, Object> propertyMap) {
        this.propertyMap = propertyMap;
    }

    public boolean containsProperty(String key) {
        return this.propertyMap.containsKey(key);
    }

    public Object getPropertyValue(String key) {
        return containsProperty(key) ? this.propertyMap.get(key) : null;
    }

    public void putProperty(String key, Object value) {
        this.propertyMap.put(key, value);
    }

    public List<String> getPropertyKeys() {
        List<String> list = Collections.synchronizedList(new ArrayList<String>());
        Iterator<String> iterators = this.propertyMap.keySet().iterator();
        while (iterators.hasNext()) {
            list.add(iterators.next());
        }
        return Collections.unmodifiableList(list);
    }

    public Integer getPropertyCount() {
        return this.propertyMap.size();
    }
}

若要使用資料表 API 插入或 upsert 這類物件,請將可展開物件的屬性對應至 TableEntity 物件,並適當地在 TableClient 物件上使用 createEntityupsertEntity 方法。

public void insertExpandableEntity(ExpandableWeatherObject model) {
    tableClient.createEntity(WeatherDataUtils.createTableEntity(model));
}

public void upsertExpandableEntity(ExpandableWeatherObject model) {
    tableClient.upsertEntity(WeatherDataUtils.createTableEntity(model));
}

更新實體

您可以藉由在 TableClient 物件上呼叫 updateEntity 方法來更新實體。 因為使用資料表 API 所儲存的實體 (資料列) 可能包含任意一組屬性,因此利用與先前討論過的 ExpandableWeatherObject 相似的字典物件來建立更新物件通常會相當有幫助。 在本案例中,唯一的差異是要在更新時新增用於並行控制的 etag 屬性。

public class UpdateWeatherObject {

    private String stationName;

    private String observationDate;

    private String etag;

    private Map<String, Object> propertyMap = new HashMap<String, Object>();

    public String getStationName() {
        return stationName;
    }

    public void setStationName(String stationName) {
        this.stationName = stationName;
    }

    public String getObservationDate() {
        return observationDate;
    }

    public void setObservationDate(String observationDate) {
        this.observationDate = observationDate;
    }

    public String getEtag() {
        return etag;
    }

    public void setEtag(String etag) {
        this.etag = etag;
    }

    public Map<String, Object> getPropertyMap() {
        return propertyMap;
    }

    public void setPropertyMap(Map<String, Object> propertyMap) {
        this.propertyMap = propertyMap;
    }
}

在樣本應用程式中,這個物件會傳遞至 TableServiceImpl 類別中的 updateEntity 方法。 此方法會先使用 TableClient 上的 getEntity 方法,來從資料表 API 載入現有的實體。 其接著會更新該實體物件,並使用 updateEntity 方法來將更新儲存至資料庫。 請留意 updateEntity 方法是如何接受該物件目前的 Etag,以藉此確保物件在剛開始載入之後沒有受到變更。 如果您想要更新實體,您可以將 etag 的值傳遞給 updateEntity 方法。

public void updateEntity(UpdateWeatherObject model) {
    TableEntity tableEntity = tableClient.getEntity(model.getStationName(), model.getObservationDate());
    Map<String, Object> propertiesMap = model.getPropertyMap();
    propertiesMap.keySet().forEach(key -> tableEntity.getProperties().put(key, propertiesMap.get(key)));
    tableClient.updateEntity(tableEntity);
}

移除實體

若要從資料表中移除實體,請使用物件的分割區索引鍵和資料列索引鍵在 TableClient 物件上呼叫 deleteEntity 方法。

public void deleteEntity(WeatherInputModel model) {
    tableClient.deleteEntity(model.getStationName(),
            WeatherDataUtils.formatRowKey(model.getObservationDate(), model.getObservationTime()));
}

7 - 執行程式碼

執行應用程式範例來與 Azure Cosmos DB 資料表 API 互動。 您第一次執行應用程式時不會看到任何資料,因為資料表是空的。 使用應用程式頂端的任意按鈕來將資料新增至資料表。

A screenshot of the application showing the location of the buttons used to insert data into Azure Cosmos DB using the Table API.

選取 [使用資料表實體插入] 按鈕後會開啟一個對話方塊,可讓您使用 TableEntity 物件來插入或 upsert 新的資料列。

A screenshot of the application showing the dialog box used to insert data using a TableEntity object.

選取 [使用可展開的資料插入] 按鈕後會顯示一個對話方塊,讓您使用自訂屬性插入物件,示範 Azure Cosmos DB 的資料表 API 如何在需要時自動將屬性 (資料行) 新增至資料表。 使用 [新增自訂欄位] 按鈕來新增一個或多個新的屬性,並示範這項功能。

A screenshot of the application showing the dialog box used to insert data using an object with custom fields.

使用 [插入範例資料] 按鈕,將部分範例資料載入您的 Azure Cosmos DB 資料表中。

A screenshot of the application showing the location of the sample data insert button.

選取頂端功能表中的 [篩選結果] 項目以移至 [篩選結果] 頁面。 在此頁面上,填寫篩選準則以示範如何建立篩選子句並將其傳遞至 Azure Cosmos DB 資料表 API。

A screenshot of the application showing filter results page and highlighting the menu item used to navigate to the page.

清除資源

在您完成應用程式範例後,您應該從 Azure 帳戶中移除與此文章相關的所有 Azure 資源。 您可以藉由刪除資源群組來完成這項作業。

您可以執行下列動作來使用 Azure 入口網站刪除資源群組。

指示 Screenshot
若要移至資源群組,請在搜尋列中輸入該資源群組的名稱。 然後,在 [資源群組] 索引標籤上,選取該資源群組的名稱。 A screenshot showing how to search for a resource group.
從資源群組頁面頂端的工具列中,選取 [刪除資源群組] A screenshot showing the location of the Delete resource group button.
畫面右側會出現一個對話方塊,要求您確認是否要刪除資源群組。
  1. 依指示在文字輸入框中輸入資源群組的完整名稱以確認刪除。
  2. 選取頁面底部的 [刪除] 按鈕。
A screenshot showing the confirmation dialog for deleting a resource group.

下一步

在本快速入門中,您已了解如何建立 Azure Cosmos DB 帳戶、如何使用資料總管來建立資料表,以及如何執行應用程式。 現在,您可以使用資料表 API 來查詢您的資料。