Python.
И СУБД.


Лекция #8

Почему важно отмечаться на лекции?


notebook.ipynb


Рейтинг популярности


Где хранить данные?
- На диске (HDD, SSD)
- В памяти (in-memory)


Модель хранения данных
- Реляционные бд
- Документ-ориентированные
- Key-value хранилища
- Графовые базы данных
- Time series
- Поисковые движки
- Другие

CAP-теорема
- Consistency
- Availability
- Partition tolerance

Определение


Общие понятия
- Язык запросов
- Индексы
- Транзакции
- ACID
- Миграции

Способы масштабирования
- Вертикальное
- Горизонтальное


Репликация


Шардинг


Популярность


Реляционные бд


Таблицы, столбцы, строки


SQL
SELECT * FROM users;
INSERT INTO users (name, address)
VALUES ('Alexander','Stavanger, Norway');
UPDATE users SET address="Moscow, Russia"
WHERE name="Alexander";
DELETE FROM users WHERE name="Alexander";

Первичные ключи
(Primary Key)
CREATE TABLE users (
id int NOT NULL AUTO_INCREMENT,
name varchar(255) NOT NULL,
address varchar(255),
PRIMARY KEY (id)
);
Уникально определяет каждую запись в таблице

Внешние ключи (Foreign Key)
Основной примитив отношений - поле, ссылающееся на первичный ключ другой таблицы
CREATE TABLE City
(
id INTEGER NOT NULL PRIMARY KEY,
name CHAR(40)
)
CREATE TABLE Street
(
id INTEGER NOT NULL PRIMARY KEY,
name CHAR(40),
id_city INTEGER NOT NULL FOREIGN KEY REFERENCES City(id)
)

Отношения (relations)
- Один к одному (One to One)
- Один ко многим/многие к одному (One to Many/Many to One)
- Многие ко многим (Many to Many)

JOINS



user:
course:
https://www.sitepoint.com/understanding-sql-joins-mysql-database/

INNER JOIN (JOIN)
SELECT user.name, course.name
FROM `user`
INNER JOIN `course` on user.course = course.id;



LEFT JOIN
SELECT user.name, course.name
FROM `user`
LEFT JOIN `course` on user.course = course.id;



Python – работа с реляционными бд
- Нативные коннекторы (mysqlclient, sqlite3, psycopg2). DB API 2.0
- ORM (SQLAlchemy, Peewee, Django ORM)


Document-oriented


Преимущества
- Отсутствие схемы (хранение только нужных атрибутов, гибкость)
- Возможность быстрой записи
- Проще шардировать данные
Эти преимущества могут быть и недостатками - "know your business"

PyMongo
from pymongo import MongoClient
client = MongoClient()
db = client.test
result = db.restaurants.insert_one(
{
"address": {
"street": "2 Avenue",
"zipcode": "10075",
"building": "1480",
"coord": [-73.9557413, 40.7720266]
},
"grades": ["A", "B"]
}
)
cursor = db.restaurants.find({"address.zipcode": "10075"})

Поисковые движки


Time-series


Отправка в Graphite
import socket
import time
CARBON_SERVER = '127.0.0.1'
CARBON_PORT = 2003
ts = int(time.time()
message = 'passkeeper.response_time 420 %d\n' % ts)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((CARBON_SERVER, CARBON_PORT))
sock.sendall(message)
sock.close()

Grafana


Column-oriented


Преимущества




cassandra-driver
from cassandra.cluster import Cluster
from cassandra.policies import RoundRobinPolicy
from cassandra.query import SimpleStatement
cluster = Cluster(
['10.1.1.3', '10.1.1.4', '10.1.1.5'],
load_balancing_policy=RoundRobinPolicy(),
port=9042)
session = cluster.connect('mykeyspace')
rows = session.execute('SELECT name, age, email FROM users')
for user_row in rows:
print user_row.name, user_row.age, user_row.email
query = SimpleStatement(
"INSERT INTO users (name, age) VALUES (%s, %s)",
consistency_level=ConsistencyLevel.QUORUM)
session.execute(query, ('John', 42))

Key-value


Другие интересные бд
- RocksDB
- CockroachDB
- Tarantool
- Aerospike

Python – работа с NoSQL бд
Свой коннектор для каждой базы данных, никакой абстракции


Спасибо!
Python_10
By Emelin Alexander
Python_10
- 1,037