Home > Backend Development > Python Tutorial > How to use Python to complete a NoSQL database sample code sharing

How to use Python to complete a NoSQL database sample code sharing

黄舟
Release: 2017-07-18 11:12:57
Original
1902 people have browsed it

The term NoSQL is becoming ubiquitous in recent years. But what exactly does "NoSQL" refer to? How and why is it so useful? In this article, we will use pure Python (as I prefer to call it, "Lightly structured pseudocode") Write a NoSQL database to answer these questions.

OldSQL

In many cases, SQL has become a synonym for "database". In fact, SQL has become a synonym for "database". , SQL is an acronym for Strctured Query Language, and does not refer to the database technology itself. Rather, it refers to the database technology from RDBMS (Relationship A language for retrieving data in a type database management system, Relational Database Management System ). MySQL, MS SQL Server and Oracle are all members of RDBMS.

R in RDBMS, That is, "Relational" (relationship, associated), is the richest part. The data is organized through table(table), and each table is composed of type(type) Composed of associated columns. The types of all tables, columns and their classes are called the schema (schema or schema) of the database. The schema is passed through each table's The description information completely describes the structure of the database. For example, a table called Car may have the following columns:

  • ##Make: a string

  • Model: a string

  • Year: a four-digit number; alternatively, a date

  • Color: a string

  • VIN (Vehicle Identification Number): a string

In a table, each single entry is called a

row ( row), or a record(record). In order to distinguish each record, a primary key is usually defined. The primary key## in the table # is one of the columns that uniquely identifies each row. In the table Car, VIN is a natural primary key choice because it ensures that each car has a unique identifier. Two different rows may There are the same values ​​in the Make, Model, Year and Color columns, but for different cars, there will definitely be different VINs. On the contrary, as long as two rows have the same VIN, we do not have to check other columns to consider this The two rows refer to the same car.Querying

SQL allows us to obtain useful information by

query

on the database. Query Simply put, a query is to ask a question to the RDBMS using a structured language and interpret the rows returned as the answer to the question. Assume that the database represents all registered vehicles in the United States. In order to obtain all Records, we can roughly translate SQL into Chinese by performing the following SQL query on the database:

SELECT Make, Model FROM Car;
Copy after login
:

    "SELECT" : "Show me"
  • "Make, Model" : "The values ​​of Make and Model"
  • "FROM Car" : "Yes Each row in table Car"
  • That is, "Show me the values ​​of Make and Model in each row of table Car". After executing the query, we will get some query results , each of which is Make and Model. If we only care about the color of the car registered in 1994, then we can:
SELECT Color FROM Car WHERE Year = 1994;
Copy after login

At this point, we will get a list similar to the following:

Black
Red
Red
White
Blue
Black
White
Yellow
Copy after login

Finally, we can specify a vehicle by using the table's

(primary key) primary key

, here is VIN:

SELECT * FROM Car WHERE VIN = '2134AFGER245267'
Copy after login
The above query statement will return the specified vehicle Attribute information.

The primary key is defined to be unique and non-repeatable. That is, a vehicle with a certain VIN can only appear at most once in the table. This is very important, why? Let’s look at an example. :

Relations

Suppose we are running a car repair business. Among other necessary things, we also need to track the service history of a car, that is, all the services on the car. Trim records. Then we might create a

ServiceHistory

table containing the following columns:

VIN

In this way, every time a vehicle is repaired, we add a new row to the table and write what we did during the service, which repairman it was, how much it cost and the service time, etc.

But wait, we all know that for the same vehicle, all columns related to the vehicle's own information are unchanged. In other words, if I renovate my Black 2014 Lexus RX 350 10 times, even though the information Make, Model, Year and Color will not change, the information will still be recorded repeatedly every time. Compared with the invalid repeated records , a more reasonable approach is to store such information only once and query it when needed.

So what to do? We can create a second table: Vehicle , which has the following columns:

MakeModelYearColorService PerformedMechanicPriceDate
##VINMakeModelYearColor
In this way, for the

ServiceHistory table, we can simplify it as follows Some columns:

VINService PerformedMechanicPriceDate

你可能会问,为什么 VIN 会在两张表中同时出现? 因为我们需要有一个方式来确认在 ServiceHistory 表的 辆车指的就是 Vehicle 表中的 辆车, 也就是需要确认两张表中的两条记录所表示的是同一辆车。 这样的话,我们仅需要为每辆车的自身信息存储一次即可. 每次当车辆过来维修的时候, 我们就在 ServiceHistory 表中创建新的一行, 而不必在 Vehicle表中添加新的记录。 毕竟, 它们指的是同一辆车。

我们可以通过 SQL 查询语句来展开 VehicleServiceHistory 两张表中包含的隐式关系:

SELECT Vehicle.Model, Vehicle.Year FROM Vehicle, ServiceHistory WHERE Vehicle.VIN = ServiceHistory.VIN AND ServiceHistory.Price > 75.00;
Copy after login

该查询旨在查找维修费用大于 $75.00 的所有车辆的 Model 和 Year. 注意到我们是通过匹配 VehicleServiceHistory 表中的 VIN 值来筛选满足条件的记录. 返回的将是两张表中符合条件的一些记录, 而 “Vehicle.Model” 与 “Vehicle.Year” , 表示我们只想要 Vehicle 表中的这两列.

如果我们的数据库没有 索引 (indexes) (正确的应该是 indices), 上面的查询就需要执行 表扫描 (table scan) 来定位匹配查询要求的行。 table scan 是按照顺序对表中的每一行进行依次检查, 而这通常会非常的慢。 实际上, table scan 实际上是所有查询中最慢的。

可以通过对列加索引来避免扫描表。 我们可以把索引看做一种数据结构, 它能够通过预排序让我们在被索引的列上快速地找到一个指定的值 (或指定范围内的一些值). 也就是说, 如果我们在 Price 列上有一个索引, 那么就不需要一行一行地对整个表进行扫描来判断其价格是否大于 75.00, 而是只需要使用包含在索引中的信息 “跳” 到第一个价格高于 75.00 的那一行, 并返回随后的每一行(由于索引是有序的, 因此这些行的价格至少是 75.00)。

当应对大量的数据时, 索引是提高查询速度不可或缺的一个工具。当然, 跟所有的事情一样,有得必有失, 使用索引会导致一些额外的消耗: 索引的数据结构会消耗内存,而这些内存本可用于数据库中存储数据。这就需要我们权衡其利弊,寻求一个折中的办法, 但是为经常查询的列加索引是 非常 常见的做法。

The Clear Box

得益于数据库能够检查一张表的 schema (描述了每列包含了什么类型的数据), 像索引这样的高级特性才能够实现, 并且能够基于数据做出一个合理的决策。 也就是说, 对于一个数据库而言, 一张表其实是一个 “黑盒” (或者说透明的盒子) 的反义词?

当我们谈到 NoSQL 数据库的时候要牢牢记住这一点。 当涉及 query 不同类型数据库引擎的能力时, 这也是其中非常重要的一部分。

Schemas

我们已经知道, 一张表的 schema , 描述了列的名字及其所包含数据的类型。它还包括了其他一些信息, 比如哪些列可以为空, 哪些列不允许有重复值, 以及其他对表中列的所有限制信息。 在任意时刻一张表只能有一个 schema, 并且 表中的所有行必须遵守 schema 的规定

这是一个非常重要的约束条件。 假设你有一张数据库的表, 里面有数以百万计的消费者信息。 你的销售团队想要添加额外的一些信息 (比如, 用户的年龄), 以期提高他们邮件营销算法的准确度。 这就需要来 alter (更改) 现有的表 – 添加新的一列。 我们还需要决定是否表中的每一行都要求该列必须有一个值。 通常情况下, 让一个列有值是十分有道理的, 但是这么做的话可能会需要一些我们无法轻易获得的信息(比如数据库中每个用户的年龄)。因此在这个层面上,也需要有些权衡之策。

此外,对一个大型数据库做一些改变通常并不是一件小事。为了以防出现错误,有一个回滚方案非常重要。但即使是如此,一旦当 schema 做出改变后,我们也并不总是能够撤销这些变动。 schema 的维护可能是 DBA 工作中最困难的部分之一。

Key/Value Stores

在 “NoSQL” 这个词存在前, 像 memcached 这样的 键/值 数据存储 (Key/Value Data Stores) 无须 table schema 也可提供数据存储的功能。 实际上, 在 K/V 存储时, 根本没有 “表 (table)” 的概念。 只有 键 (keys)值 (values) . 如果键值存储听起来比较熟悉的话, 那可能是因为这个概念的构建原则与 Python 的 dictset 相一致: 使用 hash table (哈希表) 来提供基于键的快速数据查询。 一个基于 Python 的最原始的 NoSQL 数据库, 简单来说就是一个大的字典 (dictionary) .

为了理解它的工作原理,亲自动手写一个吧! 首先来看一下一些简单的设计想法:

  • 一个 Python 的 dict 作为主要的数据存储

  • 仅支持 string 类型作为键 (key)

  • 支持存储 integer, string 和 list

  • 一个使用 ASCLL string 的简单 TCP/IP 服务器用来传递消息

  • 一些像 INCREMENT, DELETE , APPENDSTATS 这样的高级命令 (command)

有一个基于 ASCII 的 TCP/IP 接口的数据存储有一个好处, 那就是我们使用简单的 telnet 程序即可与服务器进行交互, 并不需要特殊的客户端 (尽管这是一个非常好的练习并且只需要 15 行代码即可完成)。

对于我们发送到服务器及其它的返回信息,我们需要一个 “有线格式”。下面是一个简单的说明:

Commands Supported

  • PUT

    • 参数: Key, Value

    • 目的: 向数据库中插入一条新的条目 (entry)

  • GET

    • 参数: Key

    • 目的: 从数据库中检索一个已存储的值

  • PUTLIST

    • 参数: Key, Value

    • 目的: 向数据库中插入一个新的列表条目

  • APPEND

    • 参数: Key, Value

    • 目的: 向数据库中一个已有的列表添加一个新的元素

  • INCREMENT

    • 参数: key

    • 目的: 增长数据库的中一个整型值

  • DELETE

    • 参数: Key

    • 目的: 从数据库中删除一个条目

  • STATS

    • 参数: 无 (N/A)

    • 目的: 请求每个执行命令的 成功/失败 的统计信息

现在我们来定义消息的自身结构。

Message Structure

Request Messages

一条 请求消息 (Request Message) 包含了一个命令(command),一个键 (key), 一个值 (value), 一个值的类型(type). 后三个取决于消息类型,是可选项, 非必须。; 被用作是分隔符。即使并没有包含上述可选项, 但是在消息中仍然必须有三个 ; 字符。

COMMAND; [KEY]; [VALUE]; [VALUE TYPE]
Copy after login
  • COMMAND 是上面列表中的命令之一

  • KEY 是一个可以用作数据库 key 的 string (可选)

  • VALUE 是数据库中的一个 integer, list 或 string (可选)

    • list 可以被表示为一个用逗号分隔的一串 string, 比如说, “red, green, blue”

  • VALUE TYPE 描述了 VALUE 应该被解释为什么类型

    • 可能的类型值有:INT, STRING, LIST

Examples

  • "PUT; foo; 1; INT"

  • "GET; foo;;"

  • "PUTLIST; bar; a,b,c ; LIST"

  • "APPEND; bar; d; STRING"

  • "GETLIST; bar; ;"

  • STATS; ;;

  • INCREMENT; foo;;

  • DELETE; foo;;

Reponse Messages

一个 响应消息 (Reponse Message) 包含了两个部分, 通过 ; 进行分隔。第一个部分总是 True|False , 它取决于所执行的命令是否成功。 第二个部分是命令消息 (command message), 当出现错误时,便会显示错误信息。对于那些执行成功的命令,如果我们不想要默认的返回值(比如 PUT), 就会出现成功的信息。 如果我们返回成功命令的值 (比如 GET), 那么第二个部分就会是自身值。

Examples

  • True; Key [foo] set to [1]

  • True; 1

  • True; Key [bar] set to [['a', 'b', 'c']]

  • True; Key [bar] had value [d] appended

  • True; ['a', 'b', 'c', 'd']

  • True; {'PUTLIST': {'success': 1, 'error': 0}, 'STATS': {'success': 0, 'error': 0}, 'INCREMENT': {'success': 0, 'error': 0}, 'GET': {'success': 0, 'error': 0}, 'PUT': {'success': 0, 'error': 0}, 'GETLIST': {'success': 1, 'error': 0}, 'APPEND': {'success': 1, 'error': 0}, 'DELETE': {'success': 0, 'error': 0}}

Show Me The Code!

我将会以块状摘要的形式来展示全部代码。 整个代码不过 180 行,读起来也不会花费很长时间。

Set Up

下面是我们服务器所需的一些样板代码:

"""NoSQL database written in Python"""

# Standard library imports
import socket

HOST = 'localhost'
PORT = 50505
SOCKET = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
STATS = {
    'PUT': {'success': 0, 'error': 0},
    'GET': {'success': 0, 'error': 0},
    'GETLIST': {'success': 0, 'error': 0},
    'PUTLIST': {'success': 0, 'error': 0},
    'INCREMENT': {'success': 0, 'error': 0},
    'APPEND': {'success': 0, 'error': 0},
    'DELETE': {'success': 0, 'error': 0},
    'STATS': {'success': 0, 'error': 0},
    }
Copy after login

很容易看到, 上面的只是一个包的导入和一些数据的初始化。

Set up(Cont’d)

接下来我会跳过一些代码, 以便能够继续展示上面准备部分剩余的代码。 注意它涉及到了一些尚不存在的一些函数, 不过没关系, 我们会在后面涉及。 在完整版(将会呈现在最后)中, 所有内容都会被有序编排。 这里是剩余的安装代码:

COMMAND_HANDERS = {
    'PUT': handle_put,
    'GET': handle_get,
    'GETLIST': handle_getlist,
    'PUTLIST': handle_putlist,
    'INCREMENT': handle_increment,
    'APPEND': handle_append,
    'DELETE': handle_delete,
    'STATS': handle_stats,
}

DATA = {}

def main():
    """Main entry point for script"""
    SOCKET.bind(HOST, PORT)
    SOCKET.listen(1)
    while 1:
        connection, address = SOCKET.accept()
        print('New connection from [{}]'.format(address))
        data = connection.recv(4096).decode()
        command, key, value = parse_message(data)
        if command == 'STATS':
            response = handle_stats()
        elif command in ('GET', 'GETLIST', 'INCREMENT', 'DELETE'):
            response = COMMAND_HANDERS[command](key)
        elif command in (
                'PUT',
                'PUTLIST',
                'APPEND', ):
            response = COMMAND_HANDERS[command](key, value)
        else:
            response = (False, 'Unknown command type {}'.format(command))
        update_stats(command, response[0])
        connection.sandall('{};{}'.format(response[0], response[1]))
        connection.close()

if __name__ == '__main__':
    main()
Copy after login

我们创建了 COMMAND_HANDLERS, 它常被称为是一个 查找表 (look-up table) . COMMAND_HANDLERS 的工作是将命令与用于处理该命令的函数进行关联起来。 比如说, 如果我们收到一个 GET 命令, COMMAND_HANDLERS[command](key) 就等同于说 handle_get(key) . 记住,在 Python 中, 函数可以被认为是一个值,并且可以像其他任何值一样被存储在一个 dict中。

在上面的代码中, 虽然有些命令请求的参数相同,但是我仍决定分开处理每个命令。 尽管可以简单粗暴地强制所有的 handle_ 函数接受一个 key 和一个 value , 但是我希望这些处理函数条理能够更加有条理, 更加容易测试,同时减少出现错误的可能性。

注意 socket 相关的代码已是十分极简。 虽然整个服务器基于 TCP/IP 通信, 但是并没有太多底层的网络交互代码。

最后还须需要注意的一小点: DATA 字典, 因为这个点并不十分重要, 因而你很可能会遗漏它。 DATA 就是实际用来存储的 key-value pair, 正是它们实际构成了我们的数据库。

Command Parser

下面来看一些 命令解析器 (command parser) , 它负责解释接收到的消息:

def parse_message(data):
    """Return a tuple containing the command, the key, and (optionally) the
    value cast to the appropriate type."""
    command, key, value, value_type = data.strip().split(';')
    if value_type:
        if value_type == 'LIST':
            value = value.split(',')
        elif value_type == 'INT':
            value = int(value)
        else:
            value = str(value)
    else:
        value = None
    return command, key, value
Copy after login

这里我们可以看到发生了类型转换 (type conversion). 如果希望值是一个 list, 我们可以通过对 string 调用 str.split(',') 来得到我们想要的值。 对于 int, 我们可以简单地使用参数为 string 的 int() 即可。 对于字符串与 str() 也是同样的道理。

Command Handlers

下面是命令处理器 (command handler) 的代码. 它们都十分直观,易于理解。 注意到虽然有很多的错误检查, 但是也并不是面面俱到, 十分庞杂。 在你阅读的过程中,如果发现有任何错误请移步 这里 进行讨论.

def update_stats(command, success):
    """Update the STATS dict with info about if executing *command* was a
    *success*"""
    if success:
        STATS[command]['success'] += 1
    else:
        STATS[command]['error'] += 1

def handle_put(key, value):
    """Return a tuple containing True and the message to send back to the
    client."""
    DATA[key] = value
    return (True, 'key [{}] set to [{}]'.format(key, value))

def handle_get(key):
    """Return a tuple containing True if the key exists and the message to send
    back to the client"""
    if key not in DATA:
        return (False, 'Error: Key [{}] not found'.format(key))
    else:
        return (True, DATA[key])

def handle_putlist(key, value):
    """Return a tuple containing True if the command succeeded and the message
    to send back to the client."""
    return handle_put(key, value)

def handle_putlist(key, value):
    """Return a tuple containing True if the command succeeded and the message
    to send back to the client"""
    return handle_put(key, value)

def handle_getlist(key):
    """Return a tuple containing True if the key contained a list and the
    message to send back to the client."""
    return_value = exists, value = handle_get(key)
    if not exists:
        return return_value
    elif not isinstance(value, list):
        return (False, 'ERROR: Key [{}] contains non-list value ([{}])'.format(
            key, value))
    else:
        return return_value

def handle_increment(key):
    """Return a tuple containing True if the key's value could be incremented
    and the message to send back to the client."""
    return_value = exists, value = handle_get(key)
    if not exists:
        return return_value
    elif not isinstance(list_value, list):
        return (False, 'ERROR: Key [{}] contains non-list value ([{}])'.format(
            key, value))
    else:
        DATA[key].append(value)
        return (True, 'Key [{}] had value [{}] appended'.format(key, value))

def handle_delete(key):
    """Return a tuple containing True if the key could be deleted and the
    message to send back to the client."""
    if key not in DATA:
        return (
            False,
            'ERROR: Key [{}] not found and could not be deleted.'.format(key))
    else:
        del DATA[key]

def handle_stats():
    """Return a tuple containing True and the contents of the STATS dict."""
    return (True, str(STATS))
Copy after login

有两点需要注意: 多重赋值 (multiple assignment) 和代码重用. 有些函数仅仅是为了更加有逻辑性而对已有函数的简单包装而已, 比如 handle_get 和 handle_getlist . 由于我们有时仅仅是需要一个已有函数的返回值,而其他时候却需要检查该函数到底返回了什么内容, 这时候就会使用 多重赋值 。

Let’s take a look at handle_append. If we try to call handle_get but the key does not exist, then we simply return the content returned by handle_get. In addition, we also want to be able to reference the tuple returned by handle_get as a separate return value. Then when the key does not exist, we can simply use return return_value .

If it does exist, then we need to check the return value. Moreover, we also hope to be able to reference the return value of handle_get as a separate variable. In order to be able to handle the above two situations, and also consider the situation where the results need to be processed separately, we use multiple assignment. This eliminates the need to write multiple lines of code while keeping the code clear. return_value = exists, list_value = handle_get(key) can explicitly indicate that we are going to reference the return value of handle_get in at least two different ways.

How Is This a Database?

The above program is obviously not an RDBMS, but it can definitely be called a NoSQL database. The reason it's so easy to create is that we don't have any actual interaction with the data. We just do minimal type checking and store whatever the user sends. If we need to store more structured data, we may need to create a schema for the database to store and retrieve the data. Since NoSQL databases are easier to write, easier to maintain, and easier to implement, why don't we just use mongoDB? Of course there is a reason. As the saying goes, there are gains and losses. We need to weigh the searchability of the database based on the data flexibility provided by the NoSQL database.

Querying Data

Suppose we use the NoSQL database above to store the previous Car data. Then we may use VIN as the key and a list as the value of each column, that is,

2134AFGER245267 = ['Lexus', 'RX350', 2013, Black]

. Of course, we have lost The meaning of each index in the list. We only need to know that somewhere index 1 stores the model of the car, and index 2 stores the Year.The bad thing is Now, what happens when we want to execute the previous query statement? Finding the colors of all the 1994 cars is going to be a nightmare. We must traverse

each value

in DATA to confirm whether this value stores car data or simply other irrelevant data, for example, check index 2 and see index 2 Is the value equal to 1994, and then continues to get the value of index 3. This is worse than table scan, because it not only scans every row of data, but also needs to apply some complex rules to answer the query. The authors of NoSQL databases are certainly aware of these problems, and (given that querying is a very useful feature) they have also figured out some ways to make querying less "out of reach". One approach is to structure the data used, such as JSON, allowing references to other rows to represent relationships. At the same time, most NoSQL databases have the concept of namespace. A single type of data can be stored in a "section" unique to that type in the database, which allows the query engine to take advantage of the "shape" of the data to be queried. information.

Of course, although some more sophisticated methods have existed (and been implemented) to enhance queryability, the compromise between storing a smaller amount of schema and enhancing queryability is always an unavoidable one. The problem of escaping. In this example, our database only supports querying by key. If we need to support richer queries, then things become much more complicated.

Summary

At this point, I hope the concept of “NoSQL” is very clear. We learned a little bit about SQL and saw how an RDBMS works. We saw how to retrieve data from an RDBMS (using SQL

query

). By building a toy-level NoSQL database, we learned about some of the issues faced between queryability and simplicity. , also discusses some of the approaches that some database authors have taken to deal with these problems.

The above is the detailed content of How to use Python to complete a NoSQL database sample code sharing. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template