在本文中,我们将讨论如何基于特定问题创建物化视图,并涵盖相同的示例。让我们一一讨论。
先决条件——物化视图
在此,您将看到如何基于表定义创建物化视图。让我们通过使用下面给出的以下步骤来理解这一点。
创建表定义:
现在,要理解这些场景,请考虑一个示例,其中 cricket_team 是表名,team_name、team_match_wins、team_match_losses 和 team_match_ties 是字段。
CREATE TABLE cricket_team
(
team_name text primary key,
team_match_wins int,
team_match_losses int,
team_match_ties int
);
向表中插入数据:
现在,您将看到 CQL 查询为上面创建的表插入一些行。
Insert into cricket_team( team_name, team_match_wins, team_match_losses, team_match_ties)
values ('IN' , 100, 5, 5);
Insert into cricket_team( team_name, team_match_wins, team_match_losses, team_match_ties)
values ('NZ' , 80, 5, 2);
Insert into cricket_team( team_name, team_match_wins, team_match_losses, team_match_ties)
values ('AUS' , 80, 4, 5);
Insert into cricket_team( team_name, team_match_wins, team_match_losses, team_match_ties)
values ('PAK' , 70, 8, 5);
Insert into cricket_team( team_name, team_match_wins, team_match_losses, team_match_ties)
values ('ENG' , 60, 9, 5);
验证数据:
现在,要验证上面插入的数据,您可以使用以下 CQL 查询。
select * from cricket_team;
输出 :
team_name | team_match_losses | team_match_ties | team_match_wins |
---|---|---|---|
PAK | 8 | 5 | 70 |
IN | 5 | 5 | 100 |
AUS | 4 | 5 | 80 |
NZ | 5 | 2 | 80 |
ENG | 9 | 5 | 60 |
例子 –
现在,如果你想查询如下。
select * cricket_team_by_team_match_wins where team_match_wins = 100;
笔记 –
主键字段不能为 NULL WHERE 子句必须包括一个 NULL 检查。由于 SELECT 中的 WHERE 子句基于 team_match_wins,因此 team_match_wins 必须是分区键。
创建物化视图:
现在,如果您要执行此查询,您将收到错误消息,因为没有名为cricket_team _by_ team_match_wins 的表。因此,首先,您可以使用以下 CQL 查询创建物化视图。
create materialized view if not exists
cricket_team_by_team_match_wins As
select * from cricket_team
where team_match_wins IS NOT NULL AND team_name IS NOT NULL
primary key((team_match_wins),team_name);
执行查询:
现在,如果您将执行以下给定的查询,那么它将成功执行。
select * cricket_team_by_team_match_wins where team_match_wins = 100;
输出 :
team_match_wins | team_name | team_match_losses | team_match_ties |
---|---|---|---|
100 | IN | 5 | 5 |