更新时间:2023-01-28 gmt 08:00

如何使用物化视图-凯发k8国际娱乐官网入口

什么是物化视图

物化视图本质上是由数据库自动维护的标准cql表,自动维护符合条件的数据与源表数据的一致性。

使用限制

  • 物化视图的primary key必须包含源表的所有primary key,不允许使用静态列。
  • 视图中primary key的所有列必须是“is not null”。
  • 任何物化视图中,必须将一个cql行从源表映射到物化视图的另一行,即视图和源表之间的行是逐一对应的。
  • 创建物化视图的select语句的where条件中,不能对视图的非primary key列进行限制,“is not null”除外。
    图1 示例
  • 不支持使用静态列、counter、supercolumn、duration类型。

如何使用物化视图

  1. 在源表中插入一条记录,并查询结果。

    源表示例:

    create table person (
       id int,
       name text,
       addr text,
       age int,
       email text,
       primary key (id, name));

    插入一条记录:

    insert into person(id, name, age, addr, email) values (0, 'ruby', 26, 'beijing', 'ruby@email.com');

    查看数据插入结果:

    图2 查询结果
  2. 创建物化视图。

    create materialized view person_addr as

    select * from person where id is not null and addr is not null and name is not null

    primary key (addr, id, name);

    “system_schema.views”记录了视图和源表的关联关系:

    图3 视图与源表的关联关系

    不符合该条件的查询不显示,示例:is not null。

  3. 插入“addr”为“null”的记录。

    insert into person(id, name, age, addr, email) values (1, 'mike', 30, null, 'mike@email.com');

    查看源表数据和物化视图数据:

    图4 查询结果
  4. 删除物化视图。
    drop materialized view person_adder;
    图5 删除视图
分享:
网站地图