forked from rxuriguera/plays-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.py
executable file
·87 lines (66 loc) · 2.28 KB
/
db.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# -*- coding: utf-8 -*-
import logging
from flask import Blueprint
from cassandra.cluster import Cluster
from cassandra.cqlengine import connection
from cassandra.cqlengine.management import create_keyspace_simple
logger = logging.getLogger()
db = Blueprint('db', __name__)
db.config = {}
cluster = None
session = None
@db.record
def record_params(setup_state):
app = setup_state.app
db.config = dict([(key,value) for (key,value) in app.config.iteritems()])
def init_db_blueprint():
global cluster
cluster = Cluster(
db.config['CASSANDRA_CONTACT_POINTS']
)
global session
session = cluster.connect(
db.config['CASSANDRA_KEYSPACE']
)
connection.setup(
db.config['CASSANDRA_CONTACT_POINTS'],
db.config['CASSANDRA_KEYSPACE'],
protocol_version=3
)
initialize_keyspace()
def initialize_keyspace():
logger.info("Initializing keyspace")
create_keyspace_simple('plays', 1)
# TODO: Activate automatic creation of udf an uda
logger.info("Creating user-defined functions")
udf = """
-- Create a function that takes in state (any Cassandra type) as the first
-- parameter and any number of additional parameters
CREATE OR REPLACE FUNCTION state_group_and_count( state map<text, int>, type_1 text, type_2 text)
CALLED ON NULL INPUT
RETURNS map<text, int>
LANGUAGE java
AS '
// Clean
type_1 = type_1.replaceAll("\"", "\\\"");
type_2 = type_2.replaceAll("\"", "\\\"");
// Json list
String key = "[\"" + type_1 + "\", \"" + type_2 + "\"]";
Integer count = (Integer) state.get(key);
if (count == null) count = 1;
else count++;
state.put(key, count);
return state;
' ;
"""
#session.execute(udf)
logger.info("Creating user-defined aggregations")
uda = """
-- Create a final function that is called after the state function has been
-- called on every row
CREATE OR REPLACE AGGREGATE group_and_count(text, text)
SFUNC state_group_and_count
STYPE map<text, int>
INITCOND {};
"""
#session.execute(uda)