【发布时间】:2015-08-12 22:36:39
【问题描述】:
考虑以下“文档”,这两个文档将如何存储在集合中。
// collection posts:
{
id: 1,
name: "kingsbounty",
fields: {
"title": {
"title": "Game Title",
"value": "Kings Bounty"
}
},
{
"body": {
"title": "Game Description",
"value": "Kings Bounty is a turn-based fantasy..."
}
}
}
// collection posts:
{
id: 2,
name: "outrun",
fields: {
"vehicle": {
"title": "Vehicle",
"value": "Ferrari Testarossa"
},
"color": {
"title": "Vehicle Color",
"value": "Red"
},
"driver": {
"title": "Driver",
"value": "David Hasselhoff"
}
}
}
注意字段是如何变化大小的地图。
因为 cassandra 不允许定义这种类型 fields <map <map, text>>
我想学习“cassandra”的方法,即非规范化的方法。 这种方式不会被非规范化,但可以存储和检索任意长度的嵌套数据。
CREATE TABLE posts (
id uuid,
name text,
fields list<text>
PRIMARY KEY (id)
);
CREATE INDEX post_name_key ON posts (name);
CREATE TABLE post_fields (
post_name text,
field_name text,
title text,
value text,
PRIMARY KEY (post_name, field_name)
);
INSERT INTO posts (id, name, fields) VALUES ( uuid(), 'kingsbounty', [ 'title', 'body' ] );
INSERT INTO posts (id, name, fields) VALUES ( uuid(), 'outrun', [ 'vehicle', 'color', 'driver' ] );
INSERT INTO post_fields (post_name, field_name, title, value) VALUES ( 'kingsbounty', 'title', 'Game Title', 'Kings Bounty');
INSERT INTO post_fields (post_name, field_name, title, value) VALUES ( 'kingsbounty', 'body', 'Game Description', 'Kings Bounty is a turn-based fantasy...');
INSERT INTO post_fields (post_name, field_name, title, value) VALUES ( 'outrun', 'vehicle', 'Vehicle', 'Ferrari Testarossa');
INSERT INTO post_fields (post_name, field_name, title, value) VALUES ( 'outrun', 'color', 'Vehicle Color', 'Red');
INSERT INTO post_fields (post_name, field_name, title, value) VALUES ( 'outrun', 'driver', 'Driver', 'David Hasselhoff');
SELECT fields FROM posts WHERE name = 'kingsbounty';
fields
-------------------
['title', 'body']
SELECT * FROM post_fields WHERE post_name = 'kingsbounty';
post_name | field_name | title | value
-------------+------------+------------------+-----------------------------------------
kingsbounty | body | Game Description | Kings Bounty is a turn-based fantasy...
kingsbounty | title | Game Title | Kings Bounty
SELECT fields FROM posts WHERE name = 'outrun';
fields
--------------------------------
['vehicle', 'color', 'driver']
SELECT * FROM post_fields WHERE post_name = 'outrun';
post_name | field_name | title | value
-----------+------------+---------------+--------------------
outrun | color | Vehicle Color | Red
outrun | driver | Driver | David Hasselhoff
outrun | vehicle | Vehicle | Ferrari Testarossa
有什么更好的非规范化方式来存储此类数据?
【问题讨论】:
标签: database cassandra denormalization