CQL操作

22193 ワード

http://docs.datastax.com/en/cql/3.1/pdf/cql31.pdf
CQLはCassandra Query Languageの略語で、現在はCassandraデフォルトで主要なインタラクションインターフェースとしています。CQLとSQLは比較的似ています。主な違いは、Cassandraはjoinまたはサブクエリをサポートしていません。Hiveによるバッチ分析をサポートしています。このCassandra以前のインターフェースは主にThrift APIで、これは使ったことがなくて、評価をしません。
CassandraはCQL言語で複数のデータタイプをサポートしています。
CQLタイプ
Javaタイプに対応
説明
ascii
String
ascii文字列
ビギナート
long
64ビットの整数
blob
ByteBuffer/byte[]
バイナリ配列
bollan
bollan
ブール
カウンタ
long
カウンタは、原子的増減をサポートしており、直接割当はサポートされていません。
decimal
Big Decimal
高精度小数
ドビー
ドビー
64ビット浮動小数点
float
float
32ビット浮動小数点
inet
InetAddress
ipv 4またはipv 6プロトコルのipアドレス
要点
要点
32ビットの整数
リスト
List
秩序あるリスト
map
Map
キーペア
セット
セット
集合する
テキスト
String
utf-8符号化文字列
timestamp
Date
日付
uuid
UID
UIDタイプ
timeuuid
UID
時間に関するUUID
varrhar
ストリングス
textの別名
varint
Big Integer
高精度モデル
cqlsh文法
cqlsh [options] [host [port]]
python cqlsh [options] [host [port]] 
Options
-C、--カラー
Always useカラーアウト.
--debug
Show additional debugging information.
--cqlshrc path
Use an alternative cqlshrc file location,path.(Cassandra 2.1.1)
-e cql_statement--execute cql_statement
Accept and execute a CQL command in Cassandra 2.1 and later.Useful for  saving CQL output to a file.
-f file_name,--file=file_name
Execute command from file_name,then exit.
-h,--help
Show the online help about these options and exit.
-k keyspace_name
Use the given keyspace.Equivalent to issung a USE 
keyspace commmand immediately after starting cqlsh.
--no-カラー
Never useカラーアウト.
-p password
Authenticate using password.Default=cassandra.
-t transport_ファクトリーname,--transport=transportファクトリーname
Use the provided Thrift transport factory function.
-u user_name
Authenticate as user.Default=cassandra.
--version
Show the cqlsh version.
 
CQL命令を起動するのはcqlshで、私の下の例はwindowの上のです。cassandraバージョンは2.14です。
例:
#debug
D:\soft\cassandra\apache-cassandra-2.1.14-bin\bin>cqlsh.bat --debug
Using CQL driver: <module 'cassandra' from 'D:\soft\cassandra\apache-cassandra-2.1.14-bin\bin\..\lib\cassandra-driver-in
ternal-only-2.7.2.zip\cassandra-driver-2.7.2\cassandra\__init__.py'>
Using connect timeout: 5 seconds
Connected to Test Cluster at 127.0.0.1:9042.
[cqlsh 5.0.1 | Cassandra 2.1.14 | CQL spec 3.2.1 | Native protocol v3]
Use HELP for help.
WARNING: pyreadline dependency missing.  Install to enable tab completion.

#version
D:\soft\cassandra\apache-cassandra-2.1.14-bin\bin>cqlsh.bat --version
cqlsh 5.0.1
#Saving CQL output in a file  
D:\soft\cassandra\apache-cassandra-2.1.14-bin\bin>cqlsh.bat -e "select * from duansf.users">myoutput.txt
エクスポートしたファイルは以下の通りです。
D:\soft\cassandra\apache-cassandra-21.14-bin\bin>cqlsh.bat
結果:cqlsh Can't detect Python version!
pythonをインストールして、私は64ビットの2.7バージョンをインストールして、環境変数のpathの中でpythonのインストールルートのパスを増加するように配置します。インストールしてcqlsh.batを実行します。
D:\soft\cassandra\apache-cassandra-21.14-bin\bin>cqlsh.bat
D:\soft\cassandra\apache-cassandra-2.1.14-bin\bin>cqlsh.bat
Connected to Test Cluster at 127.0.0.1:9042.
[cqlsh 5.0.1 | Cassandra 2.1.14 | CQL spec 3.2.1 | Native protocol v3]
Use HELP for help.
WARNING: pyreadline dependency missing.  Install to enable tab completion.
一、keyspaceを作成する
対照として、あなたはkeyspaceをSQLデータベースの例として理解することができます。もちろんそれらは違います。Cassandraのkeyspaceはデータがノード間でどのようにコピーされているかを定義するために用いられます。通常は、アプリケーションのためのkeyspaceを確立する必要があります。
CREATE KEYSPACE IF NOT EXISTS pimin_net
WITH REPLICATION = {'class': 'SimpleStrategy','replication_factor':1};
上の文の意味は、keyspaceが存在するかどうかを判断し、存在しない場合はkeyspaceを確立するということです。使用したレプリカ戦略は単純戦略であり、レプリカ係数は1である。とりあえず中の深いところはともかく、簡単な原則で実現します。
二、表を作成する
Cassandraは列に面した分散型データベースというが、表の概念もある。作成前にまずuse pimin_ネット
USE pimin_net;
 
CREATE TABLE users (
id int,
user_name varchar,
PRIMARY KEY (id) );
 
このようにユーザーテーブルを作りました。簡単のために、二つのフィールドしかないです。oracleやmysqlなどと似ていますか?
三、時計のCRUD
もう一つのユーザーテーブルがあります。中にいくつかのデータを挿入して、それを調べたり、更新したり、削除したりします。
INSERT INTO users (id,user_name) VALUES (1,'china');
INSERT INTO users (id,user_name) VALUES (2,'taiwan');
SELECT * FROM users;
結果:
cqlsh:pimin_net> SELECT * FROM users;

 id | user_name
----+-----------

(0 rows)
cqlsh:pimin_net> INSERT INTO users (id,user_name) VALUES (1,'china');
cqlsh:pimin_net> INSERT INTO users (id,user_name) VALUES (2,'taiwan');
cqlsh:pimin_net> SELECT * FROM users;

 id | user_name
----+-----------
  1 |     china
  2 |    taiwan

(2 rows)
cqlsh:pimin_net>
 
UPDATE users SET user_name = 'china2014' WHERE id = 1;
SELECT * FROM users;
DELETE FROM users WHERE id = 1;
SELECT * FROM users;
結果:
cqlsh:pimin_net> UPDATE users SET user_name = 'china2014' WHERE id = 1;
cqlsh:pimin_net> SELECT * FROM users;

 id | user_name
----+-----------
  1 | china2014
  2 |    taiwan

(2 rows)
cqlsh:pimin_net> DELETE FROM users WHERE id = 1;
cqlsh:pimin_net> SELECT * FROM users;

 id | user_name
----+-----------
  2 |    taiwan

(1 rows)
cqlsh:pimin_net>
 重要:従来のRDBMSと違って、CassandraはDELETE FROM usersを使用できません。このような表現には、WHERE条件が必要です。
 重要:従来のRDBMSと違って、CassandraはDELETE FROM usersを使用できません。このような表現には、WHERE条件が必要です。
例2:
cqlsh:usermanager;use duansf
1.keyspaceを作成する 
cqlsh:usermanager> create keyspace duansf WITH REPLICATION = {'class': 'SimpleStrategy','replication_factor':1};
duansfというkeyspaceを作成します。コピーポリシーSimpleStrategyは複製因子が1です。 
2.Columnを作成する family 
cqlsh>use duansf;
cqlsh:duansf> create columnfamily users(
           key varchar primary key,
           password varchar,
           gender varchar,
           session_token varchar,
           state varchar,
           birth_year bigint);
usersという名前のcolumnを作成します。 family 
 ...  KEY varrhar PRIMARY KEY、このcolumnfamilyの下にKeyがあります。
と5列 
 ...  password varrhar、 
…  gende rvarrhar 
 ...  session_token varhar 
…  state varrhar 
 ...  バーツ.year bigint); 
3.Columnsの挿入と検索 
cqlsh:duansf>insert into users(key,password)values('jsmith'、'chadsfl')using ttl 86400;
passwodの列にデータを挿入します。
cqlsh:duansf> select * from users where key='jsmith';

 key    | birth_year | gender | password | session_token | state
--------+------------+--------+----------+---------------+-------
 jsmith |       null |   null |  chadsfl |          null |  null

(1 rows)
cqlsh:duansf>
session_へtokenこの列にデータを挿入します。
cqlsh:duansf> insert into users(key,session_token) values('jsmith','test') using ttl 86400;
cqlsh:duansf> select * from users where key='jsmith';

 key    | birth_year | gender | password | session_token | state
--------+------------+--------+----------+---------------+-------
 jsmith |       null |   null |  chadsfl |          test |  null
3.Columnへ familyにColumnを追加します。 
cqlsh:duansf> alter table user add coupon_code varchar;
注意:他に既に存在している列は更新されません。
4. Columnのメタデータを変更します。
cqlsh:duansf> alter table users alter coupon_code type int;
ConfigurationException: <ErrorMessage code=2300 [Query invalid because of configuration issue] message="Cannot change co
upon_code from type text to type int: types are incompatible.">
既存のデータはこのタイプには変わりません。新たに挿入されたデータがこのタイプです。
5.TTL属性で列の満期時間を設定する 
cqlsh:duansf> update users using ttl 432000 set password='asldkjsfsdf' where key = 'jsmith';
パスワードの更新は5日間の有効期限です。
6.列メタデータを削除する 
cqlsh:duansf> alter table users drop coupon_code;
7.索引Column 
cqlsh:duansf> create index state_key on users(state);
cqlsh:duansf> create index birth_year_key on users(birth_year);
8.列または行を削除する 
cqlsh:duansf> delete session_token from users where key='jsmith';  //  session_token 
cqlsh:duansf> select * from users;

 key    | birth_year | gender | password    | session_token | state
--------+------------+--------+-------------+---------------+-------
 jsmith |       null |   null | asldkjsfsdf |          null |  null

(1 rows)
cqlsh:duansf> delete from users where key='jsmith';  //  key=jsmith  
cqlsh:duansf> select * from users;

 key | birth_year | gender | password | session_token | state
-----+------------+--------+----------+---------------+-------

(0 rows)
cqlsh:duansf>
9. columnfamilyとkeyspaceを削除します。 
cqlsh:duansf> drop columnfamily users;
cqlsh:duansf> insert into users(key,password) values('jsmith','chadsfl') using ttl 86400;
InvalidRequest: code=2200 [Invalid query] message="unconfigured columnfamily users"
cqlsh:duansf>
keyspaceを削除します
cqlsh:duansf> drop keyspace duansf;
cqlsh:duansf> use duansf;
InvalidRequest: code=2200 [Invalid query] message="Keyspace 'duansf' does not exist"
cqlsh:duansf>
 
10.構造情報を表示する
cqlsh:usermanager> desc users;

CREATE TABLE usermanager.users (
    key blob PRIMARY KEY,
    age text,
    name text
) WITH bloom_filter_fp_chance = 0.01
    AND caching = '{"keys":"ALL", "rows_per_partition":"NONE"}'
    AND comment = ''
    AND compaction = {'class': 'org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy'}
    AND compression = {'sstable_compression': 'org.apache.cassandra.io.compress.LZ4Compressor'}
    AND dclocal_read_repair_chance = 0.1
    AND default_time_to_live = 0
    AND gc_grace_seconds = 864000
    AND max_index_interval = 2048
    AND memtable_flush_period_in_ms = 0
    AND min_index_interval = 128
    AND read_repair_chance = 0.0
    AND speculative_retry = '99.0PERCENTILE';