LoginSignup
0
1

More than 1 year has passed since last update.

Google ColaboratoryでApache Cassandraを使う

Last updated at Posted at 2021-05-18

で使うのだけど、自分のColaboratoryで練習するための設定の防備録

レファレンス

Cassandraのインストール

ipynbの記述ってどうすればいい感じなんだろ :thinking:

!java -versionで確認すると openjdk version "11.0.11" 2021-04-20なので OpenJDK 8のインストールも実施する。

install_colab.ipynb

import os

#apt-getで入れた場合、ディレクトリ作成されない場合があるので、追加
new_dir = '/run/cassandra'
os.makedirs(new_dir, exist_ok=True)


!apt-get install openjdk-8-jdk-headless -qq > /dev/null
!echo "deb http://downloads.apache.org/cassandra/debian 40x main" | sudo tee -a /etc/apt/sources.list.d/cassandra.sources.list

!curl https://downloads.apache.org/cassandra/KEYS | sudo apt-key add -

!sudo apt-get update -qq

!sudo apt-get install -qq cassandra > /dev/null

!pip install -q -U cassandra-driver

import os
os.environ["JAVA_HOME"] = "/usr/lib/jvm/java-8-openjdk-amd64"

#colabratoryだとユーザはrootなのでオプション付きで起動する。
!cassandra -R -p /run/cassandra/cassandra.pid > /dev/null

!nodetool status

結果

result
Datacenter: datacenter1
=======================
Status=Up/Down
|/ State=Normal/Leaving/Joining/Moving
--  Address    Load      Tokens  Owns (effective)  Host ID                               Rack 
UN  127.0.0.1  68.9 KiB  16      100.0%            8d69312c-7b81-4543-a6c6-e8abf3a0a85c  rack1

停止

stop_cassandra.ipynb
!kill `cat /run/cassandra/cassandra.pid`

データベース作成等

creatdb.ipynb
import cassandra

from cassandra.cluster import Cluster
try: 
    cluster = Cluster(['127.0.0.1']) #If you have a locally installed Apache Cassandra instance
    session = cluster.connect()
except Exception as e:
    print(e)

try:
    session.execute("""
    CREATE KEYSPACE IF NOT EXISTS my_db 
    WITH REPLICATION = 
    { 'class' : 'SimpleStrategy', 'replication_factor' : 1 }"""
)

except Exception as e:
    print(e)

try:
    session.set_keyspace('my_db')
except Exception as e:
    print(e)

あとは CREATE TABLE IF NOT EXSTS my_dbと続けて、テーブルを作っていく。

まとめ

cassandraの起動に少し時間がかかるくらいなので、これくらい気楽なのがいいと思う。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1