8 Aralık 2020 Salı

Apache Cassandra Query Language - CQL

Giriş
Açıklaması şöyle.
Some NoSQL databases added their own “SQL-like” query languages, like Cassandra’s CQL. 
Açıklaması şöyle.
Cassandra exposes a SQL dialect called CQL for its DDL (data definition language) and DML (data manipulation language). While similar to SQL, there is one notable omission: Apache Cassandra does not support join operations.

Finally, as Cassandra is a distributed database, you can configure things like replication factor and consistency level to determine where the data gets replicated and how often. Almost every distributed database honors the CAP theorem nowadays: the oft-repeated notion that a distributed data store must honor the tradeoff between data consistency, availability, and partition tolerance.
JOIN İşlemleri
Açıklaması şöyle. Join desteklenmez, dolayısıyla denormalization yapmak gerekir. Yani veri çoklanır
Unlike a relational database model in which queries make use of table joins to get data from multiple tables, joins are not supported in Cassandra so all required fields (columns) must be grouped together in a single table.
QUORUM
Açıklaması şöyle
Eventually consistent implies the read-after-write of a value may not yield the latest value written. But, we can achieve strong consistency in Cassandra by specifying the consistency level for the query as QUORUM. This quorum means that a write transaction would succeed only after writing it to a majority of servers. 
Sütun Tipi
- bigint
- decimal
- double
- int
- text
- timestamp

BEGIN TRANSACTION
Bir örnek burada

CREATE KEYSPACE
Örnek
Şöyle yaparız. 3 tane replica yaratır.
CREATE KEYSPACE personalization WITH replication = {‘class’: ‘NetworkTopologyStrategy’,
‘batch’: ‘3’, ‘live’: ‘3’, ‘offline’: ‘3’} AND durable_writes = true;
CREATE TABLE
Örnek
Şöyle yaparız
CREATE TABLE lockrequests( resource id TEXT, lock_status TEXT, created_on TIMESTAMP,
PRIMARY KEY(resource_id)) WITH GC_GRACE_SECONDS=86400 AND DEFAULT_TIME_TO_LIVE=600;
DEFAULT_TIME_TO_LIVE için açıklama şöyle
The next problem is what happens if the service that acquired the lock has not released it. The server might have crashed, or the code might have thrown an exception. The lock will never get released. For such cases, we can define time-to-live (TTL) for the row. This means the lock row will automatically expire after the prescribed number of seconds. Here is how we can achieve it by defining TTL for every record of the row
Now the lock will automatically expire in 10 mins. This setting can be overridden for every row by defining TTL for all the columns. TTL might not help if we don’t have a rough estimate of how much time a computation (that is surrounded by the lock) can take.
Örnek - WITH CLUSTERING ORDER BY
Şöyle yaparız
CREATE TABLE messages ( 
  channel_id bigint, 
  bucket int, 
  message_id bigint, 
  author_id bigint, 
  content text, 
  PRIMARY KEY ((channel_id, bucket), message_id)) 
WITH CLUSTERING ORDER BY (message_id DESC);
Örnek - WITH CLUSTERING ORDER BY + AND
Şöyle yaparız
CREATE KEYSPACE retail WITH REPLICATION = {
  'class' : 'NetworkTopologyStrategy', 
  'datacenter1' : 1
};

CREATE TABLE retail.orders_by_customer (
  order_id int, 
  customer_id int, 
  purchase_amount int, 
  city text, 
  purchase_time timestamp, 
  PRIMARY KEY (customer_id, purchase_time)) 
  WITH CLUSTERING ORDER BY 
    (purchase_time DESC) AND 
    cosmosdb_cell_level_timestamp=true AND 
    cosmosdb_cell_level_timestamp_tombstones=true AND 
    cosmosdb_cell_level_timetolive=true;

CREATE TABLE retail.orders_by_city (
  order_id int, 
  customer_id int, 
  purchase_amount int, 
  city text, 
  purchase_time timestamp, 
  PRIMARY KEY (city,order_id)) 
  WITH 
    cosmosdb_cell_level_timestamp=true AND 
    cosmosdb_cell_level_timestamp_tombstones=true AND 
    cosmosdb_cell_level_timetolive=true;
CREATE TYPE
Örnek
Şöyle yaparız
CREATE TYPE commerce.money (currency text,amount decimal);
Örnek
Şöyle yaparız
CREATE TYPE IF NOT EXISTS developers.money (currency text, amount decimal);

CREATE TYPE IF NOT EXISTS developers.headquarter (city text, country text);

CREATE COLUMNFAMILY IF NOT EXISTS developers.Company (name text PRIMARY KEY,
cost FROZEN<money>,
languages set<text>,
contacts map<text, text>,
headquarters set<FROZEN<headquarter>>);
INSERT
Örnek
Şöyle yaparız
INSERT INTO lock_requests(resource_id,lock_status,created_on) VALUES('ABC','Locked',
toTimestamp(now()) IF NOT EXISTS;
Açıklaması şöyle
If the lock exists, the above write fails, and hence the lock is not acquired. 
Örnek - TTL
Şöyle yaparız
INSERT INTO sensor_events (account_name,
                               device_id,
                               event_id,
                               event_date,
                               closest_devices_ip,
                               tempratures,
                               tags,
                               latitude,
                               longitude,
                               humidity,
                               pressure, 
                               event_time) 
VALUES ('Account#1',
        89a35059-b6c1-4d28-9fae-d8a7abd896f5, 
        uuid(),
        '2022-10-25',
        {'29.208.191.134','29.208.191.135'},
        [19,20,20,21],
        {'type':'whether_sensor','brand':'some_brand' },
        48.955624, 
        30.025853,
        62, 
        36,
        '07:36:07') USING TTL 20;
UPDATE

Örnek - Tek Alan
Şöyle yaparız
UPDATE sensor_events SET pressure = 82
       WHERE account_name = 'Account#1' AND 
             device_id = 89a35059-b6c1-4d28-9fae-d8a7abd896f5 AND
             event_id = 06b1cc9d-d891-4969-acb3-c9b958bd21f5 AND
             event_date = '2022-10-25';
Örnek - Set
Ekleme ve çıkarma için şöyle yaparız
UPDATE sensor_events SET closest_devices_ip = 
                         closest_devices_ip + {'29.208.191.136'}
       WHERE account_name = 'Account#1' AND 
             device_id = 89a35059-b6c1-4d28-9fae-d8a7abd896f5 AND
             event_id = 06b1cc9d-d891-4969-acb3-c9b958bd21f5 AND
             event_date = '2022-10-25';

UPDATE sensor_events SET closest_devices_ip = 
                         closest_devices_ip -{'29.208.191.134'}
       WHERE account_name = 'Account#1' AND 
             device_id = 89a35059-b6c1-4d28-9fae-d8a7abd896f5 AND
             event_id = 06b1cc9d-d891-4969-acb3-c9b958bd21f5 AND
             event_date = '2022-10-25';
Örnek - List
Ekleme, çıkarma ve değiştirme için şöyle yaparız
UPDATE sensor_events SET tempratures = tempratures + [19] 
       WHERE account_name = 'Account#1' AND 
             device_id = 89a35059-b6c1-4d28-9fae-d8a7abd896f5 AND
             event_id = 06b1cc9d-d891-4969-acb3-c9b958bd21f5 AND
             event_date = '2022-10-25';

UPDATE sensor_events SET tempratures = tempratures - [22] 
       WHERE account_name = 'Account#1' AND 
             device_id = 89a35059-b6c1-4d28-9fae-d8a7abd896f5 AND
             event_id = 06b1cc9d-d891-4969-acb3-c9b958bd21f5 AND
             event_date = '2022-10-25';

UPDATE sensor_events SET tempratures[0] = 19
       WHERE account_name = 'Account#1' AND 
             device_id = 89a35059-b6c1-4d28-9fae-d8a7abd896f5 AND
             event_id = 06b1cc9d-d891-4969-acb3-c9b958bd21f5 AND
             event_date = '2022-10-25';
Örnek - Map
Ekleme, değiştirme ve silme için şöyle yaparız
UPDATE sensor_events SET tags = tags + {'owner':'team#1'}
       WHERE account_name = 'Account#1' AND 
             device_id = 89a35059-b6c1-4d28-9fae-d8a7abd896f5 AND
             event_id = 06b1cc9d-d891-4969-acb3-c9b958bd21f5 AND
             event_date = '2022-10-25';


UPDATE sensor_events SET tags['type'] = 'weather_sensor'
       WHERE account_name = 'Account#1' AND 
             device_id = 89a35059-b6c1-4d28-9fae-d8a7abd896f5 AND
             event_id = 06b1cc9d-d891-4969-acb3-c9b958bd21f5 AND
             event_date = '2022-10-25';

DELETE tags['brand'] FROM sensor_events WHERE account_name = 'Account#1' AND 
             device_id = 89a35059-b6c1-4d28-9fae-d8a7abd896f5 AND
             event_id = 06b1cc9d-d891-4969-acb3-c9b958bd21f5 AND
             event_date = '2022-10-25';
DELETE
Örnek 
Tüm satırı silmek için şöyle yaparız
DELETE FROM sensor_events  WHERE account_name = 'Account#1' AND
        device_id = 89a35059-b6c1-4d28-9fae-d8a7abd896f5 AND
        event_id = 06b1cc9d-d891-4969-acb3-c9b958bd21f5 AND
        event_date = '2022-10-25';
COPY
Örnek 
CSV dosyasını kopyalamak için şöyle yaparız
COPY sensor_events (account_name,
                    device_id,
                    event_id,
                    event_date,
                    closest_devices_ip,
                    tempratures,
                    tags,
                    latitude,
                    longitude,
                    humidity,
                    pressure, 
                    event_time) FROM  './tmp/data/data-for-input.csv'
                                 WITH HEADER=true and DELIMITER='|';
SELECT
Örnek 
Şöyle yaparız
// Çalışmaz
SELECT * FROM sensor_events WHERE account_name='Account#1';

// Çalışır
SELECT * FROM sensor_events WHERE 
                            account_name='Account#1' AND 
                            device_id=89a35059-b6c1-4d28-9fae-d8a7abd896f5;
INDEX
Elimizde şöyle bir tablo olsun.
user_id | user_name | user_phone
---------+-----------+-------------
      23 |     user, | 12345678910
...      
 Şöyle yaparız.
CREATE CUSTOM INDEX user_name_idx ON user ("user_name")
  USING 'org.apache.cassandra.index.sasi.SASIIndex'
  WITH OPTIONS = {'mode': 'CONTAINS',
    'analyzer_class': 'org.apache.cassandra.index.sasi.analyzer.StandardAnalyzer',
    'case_sensitive': 'false'};
 Şöyle yaparız.
SELECT * FROM user WHERE "user_name" LIKE '%u%'
Materialized View
Bir örnek burada

Hiç yorum yok:

Yorum Gönder