Azure Cosmos DB Cassandra API 中的次要索引

適用於: Cassandra API

Azure Cosmos DB 中的 Cassandra API 會利用基礎索引結構來公開平台中固有的索引編製強度。 不過,不同於核心 SQL API,Azure Cosmos DB 中的 Cassandra API 不會預設編製所有屬性的索引。 相反地,其支援使用次要索引編制來建立特定屬性的索引,其行為方式與 Apache Cassandra 相同。

一般情況下,不建議您在未分割的資料行上執行篩選查詢。 您必須明確地使用 ALLOW FILTERING 語法,而這可能會導致某個作業無法順利執行。 在 Azure Cosmos DB 中,您可以在低基數屬性上執行這類查詢,因為這些查詢會在資料分割之間展開,以擷取結果。

不建議您在經常更新的資料行上建立索引。 在定義資料表時建立索引是聰明的做法。 這可確保資料和索引處於一致的狀態。 如果您在現有的資料上建立新的索引,則目前無法追蹤資料表的索引進度變更。 如果您需要追蹤此作業的進度,必須透過支援票證要求進度變更。

注意

下列物件不支援次要索引:

  • 凍結的集合類型、十進位和變數類型之類的資料類型。
  • 靜態資料行
  • 群集索引鍵

警告

在 Cassandra API 中,分割區索引鍵依預設不會編制索引。 如果您的資料表中有複合主索引鍵,而且您同時篩選分割區索引鍵和叢集索引鍵,或只篩選分割區索引鍵,這將提供所需的行為。 不過,如果您篩選分割區索引鍵和叢集索引鍵以外的任何其他非索引欄位,這會導致分割區索引鍵展開,即使其他非索引欄位具有次要索引也會導致相同問題。 如果您的資料表中有複合主索引鍵,而您想要同時篩選複合主索引鍵的分割區索引鍵值元素及其他非分割區索引鍵或叢集索引鍵的欄位,請確定您已明確對分割區索引鍵新增次要索引。 此案例中的索引應會大幅改善查詢效能,即使其他非分割區索引鍵和非叢集索引鍵欄位沒有索引也一樣。 如需詳細資訊,請參閱有關資料分割的文章。

索引範例

首先,在 CQL 殼層提示字元中執行下列命令,以建立 keyspace 和資料表範例:

CREATE KEYSPACE sampleks WITH REPLICATION = {'class' : 'SimpleStrategy'};
CREATE TABLE sampleks.t1(user_id int PRIMARY KEY, lastname text) WITH cosmosdb_provisioned_throughput=400;

然後,使用下列命令插入使用者資料範例:

insert into sampleks.t1(user_id,lastname) values (1, 'nishu');
insert into sampleks.t1(user_id,lastname) values (2, 'vinod');
insert into sampleks.t1(user_id,lastname) values (3, 'bat');
insert into sampleks.t1(user_id,lastname) values (5, 'vivek');
insert into sampleks.t1(user_id,lastname) values (6, 'siddhesh');
insert into sampleks.t1(user_id,lastname) values (7, 'akash');
insert into sampleks.t1(user_id,lastname) values (8, 'Theo');
insert into sampleks.t1(user_id,lastname) values (9, 'jagan');

如果您嘗試執行下列陳述式,您將會遇到錯誤,其中要求您使用 ALLOW FILTERING

select user_id, lastname from sampleks.t1 where lastname='nishu';

雖然 Cassandra API 支援 ALLOW FILTERING (如上一節所述),但並不建議這麼做。 您應改為建立索引,如下列範例所示:

CREATE INDEX ON sampleks.t1 (lastname);

在 [lastname] 欄位上建立索引之後,您現在可以成功執行先前的查詢。 使用 Azure Cosmos DB 中的 Cassandra API 時,您不需要提供索引名稱。 您會使用格式為 tablename_columnname_idx 的預設索引。 例如, t1_lastname_idx 是上一個資料表的索引名稱。

卸除索引

若要卸除索引,您必須知道索引的名稱。 執行 desc schema 命令以取得資料表的描述。 此命令的輸出會包含格式為 CREATE INDEX tablename_columnname_idx ON keyspacename.tablename(columnname) 的索引名稱。 然後,您可以使用索引名稱來卸除索引,如下列範例所示:

drop index sampleks.t1_lastname_idx;

後續步驟