【翻譯】SQLite 不只是玩具數據庫而已


來源:https://antonz.org/sqlite-is-not-a-toy-database/

無論你是研發、數據分析師、QA 工程師、DevOps 負責人,或是產品經理,SQLite 都是完美的工具。理由如下。

從一些基礎的事實說起:

  • SQLite 是世界上最常用的 DBMS(數據庫管理系統),所有的主流系統都帶有它
  • SQLite 是 serverless 的
  • 對於開發者來說,SQLite 直接嵌入到 app 之中
  • 對於其他人來說,SQLite 有便利的數據庫控制台(REPL 命令行),以單文件的形式被提供。(Windows的sqlite3.exe,  Linux / macOS上的sqlite3)

控制台,導入與導出

控制台是SQLite為數據分析提供的殺手應用:比 Excel 強大,比 pandas 簡單。一行命令就可以導入 csv 數據,表會被自動建好:

> .import --csv city.csv city
> select count(*) from city;
1117

控制台支持基礎的 SQL 功能,並且會以友善的 ASCII 表格繪制查詢結果。同時支持高級的SQL功能,之后詳述。

select
  century || ' century' as dates,
  count(*) as city_count
from history
group by century
order by century desc;
┌────────────┬────────────┐
│   dates    │ city_count │
├────────────┼────────────┤
│ 21 century │ 1          │
│ 20 century │ 263        │
│ 19 century │ 189        │
│ 18 century │ 191        │
│ 17 century │ 137        │
│ ...        │ ...        │
└────────────┴────────────┘

可以導入的數據包括 SQL、CSV、JSON,甚至 markdown 和 HTML。只需要幾行命令:

.mode json
.output city.json
select city, foundation_year, timezone from city limit 10;
.shell cat city.json
[
    { "city": "Amsterdam", "foundation_year": 1300, "timezone": "UTC+1" },
    { "city": "Berlin", "foundation_year": 1237, "timezone": "UTC+1" },
    { "city": "Helsinki", "foundation_year": 1548, "timezone": "UTC+2" },
    { "city": "Monaco", "foundation_year": 1215, "timezone": "UTC+1" },
    { "city": "Moscow", "foundation_year": 1147, "timezone": "UTC+3" },
    { "city": "Reykjavik", "foundation_year": 874, "timezone": "UTC" },
    { "city": "Sarajevo", "foundation_year": 1461, "timezone": "UTC+1" },
    { "city": "Stockholm", "foundation_year": 1252, "timezone": "UTC+1" },
    { "city": "Tallinn", "foundation_year": 1219, "timezone": "UTC+2" },
    { "city": "Zagreb", "foundation_year": 1094, "timezone": "UTC+1" }
]

如果相比於控制台愛好者你更傾向於BI,流行的數據分析工具如MetabaseRedash, 和 Superset 都支持 SQLite。

原生JSON

分析和轉換 JSON 領域,沒有什么比 SQLite 更方便的了。你可以從文件中直接選取數據,就如同對一張普通的表進行操作。或者將數據導入到表,並且從表中查詢。

select
  json_extract(value, '$.iso.code') as code,
  json_extract(value, '$.iso.number') as num,
  json_extract(value, '$.name') as name,
  json_extract(value, '$.units.major.name') as unit
from
  json_each(readfile('currency.sample.json'))
;
┌──────┬─────┬─────────────────┬──────────┐
│ code │ num │      name       │   unit   │
├──────┼─────┼─────────────────┼──────────┤
│ ARS  │ 032 │ Argentine peso  | peso     │
│ CHF  │ 756 │ Swiss Franc     │ franc    │
│ EUR  │ 978 │ Euro            │ euro     │
│ GBP  │ 826 │ British Pound   │ pound    │
│ INR  │ 356 │ Indian Rupee    │ rupee    │
│ JPY  │ 392 │ Japanese yen    │ yen      │
│ MAD  │ 504 │ Moroccan Dirham │ dirham   │
│ RUR  │ 643 │ Russian Rouble  │ rouble   │
│ SOS  │ 706 │ Somali Shilling │ shilling │
│ USD  │ 840 │ US Dollar       │ dollar   │
└──────┴─────┴─────────────────┴──────────┘

不管 JSON 深度有多深,你可以提取任何深層的對象:

select
  json_extract(value, '$.id') as id,
  json_extract(value, '$.name') as name
from
  json_tree(readfile('industry.sample.json'))
where
  path like '$[%].industries'
;
┌────────┬──────────────────────┐
│   id   │         name         │
├────────┼──────────────────────┤
│ 7.538  │ Internet provider    │
│ 7.539  │ IT consulting        │
│ 7.540  │ Software development │
│ 9.399  │ Mobile communication │
│ 9.400  │ Fixed communication  │
│ 9.401  │ Fiber-optics         │
│ 43.641 │ Audit                │
│ 43.646 │ Insurance            │
│ 43.647 │ Bank                 │
└────────┴──────────────────────┘

常見表單表達式和集合操作

當然了,SQLite 支持常見表單表達式(如 WITH 語句)和 JOIN 等,我甚至沒有必要在這里舉例。如果數據是分層級的(表引用自身,比如通過 parent_id)- WITH RECURSIVE 就變得很實用。無論多深的層級,都可以通過一句查詢輕松展開。

with recursive tmp(id, name, level) as (
  select id, name, 1 as level
  from area
  where parent_id is null

  union all

  select
    area.id,
    tmp.name || ', ' || area.name as name,
    tmp.level + 1 as level
  from area
    join tmp on area.parent_id = tmp.id
)

select * from tmp;
┌──────┬──────────────────────────┬───────┐
│  id  │           name           │ level │
├──────┼──────────────────────────┼───────┤
│ 93   │ US                       │ 1     │
│ 768  │ US, Washington DC        │ 2     │
│ 1833 │ US, Washington           │ 2     │
│ 2987 │ US, Washington, Bellevue │ 3     │
│ 3021 │ US, Washington, Everett  │ 3     │
│ 3039 │ US, Washington, Kent     │ 3     │
│ ...  │ ...                      │ ...   │
└──────┴──────────────────────────┴───────┘

集合運算?沒有問題:UNION,INTERSECT,EXCEPT 全部可以使用。

select employer_id
from employer_area
where area_id = 1

except

select employer_id
from employer_area
where area_id = 2;

通過其他表格的數據計算某列的值?輸入被創建的列即可:

alter table vacancy
add column salary_net integer as (
  case when salary_gross = true then
    round(salary_from/1.04)
  else
    salary_from
  end
);

被創建的列可以像普通列一樣被查詢:

select
  substr(name, 1, 40) as name,
  salary_net
from vacancy
where
  salary_currency = 'JPY'
  and salary_net is not null
limit 10;

數學統計

描述性統計?簡單:均值、中位數、百分位數、標准差,你想到的基本都有。需要讀一個插件,不過也只一行命令而已:

.load sqlite3-stats

select
  count(*) as book_count,
  cast(avg(num_pages) as integer) as mean,
  cast(median(num_pages) as integer) as median,
  mode(num_pages) as mode,
  percentile_90(num_pages) as p90,
  percentile_95(num_pages) as p95,
  percentile_99(num_pages) as p99
from books;
┌────────────┬──────┬────────┬──────┬─────┬─────┬──────┐
│ book_count │ mean │ median │ mode │ p90 │ p95 │ p99  │
├────────────┼──────┼────────┼──────┼─────┼─────┼──────┤
│ 14833492952566408171199 │
└────────────┴──────┴────────┴──────┴─────┴─────┴──────┘

關於插件的備注:與其他DBMS比如PostgreSQL相比,SQLite缺失了很多功能。但是這些功能都很好添加,大家一般也都會來添加插件,因此往往造成一些混亂。

因此,我決定制作一些穩定的插件,按照領域分類,並為主流的操作系統編譯。目前已經完成了一些,更多的還在制作中。sqlean @ GitHub

來看些更有趣的。你可以將數據分布直接在控制台中作圖。多可愛啊。

with slots as (
  select
    num_pages/100 as slot,
    count(*) as book_count
  from books
  group by slot
),
max as (
  select max(book_count) as value
  from slots
)
select
  slot,
  book_count,
  printf('%.' || (book_count * 30 / max.value) || 'c', '*') as bar
from slots, max
order by slot;
┌──────┬────────────┬────────────────────────────────┐
│ slot │ book_count │              bar               │
├──────┼────────────┼────────────────────────────────┤
│ 0116        │ *********                      │
│ 1254        │ ********************           │
│ 2376        │ ****************************** │
│ 3285        │ **********************         │
│ 4184        │ **************                 │
│ 590         │ *******                        │
│ 654         │ ****                           │
│ 741         │ ***                            │
│ 831         │ **                             │
│ 915         │ *                              │
│ 1011         │ *                              │
│ 1112         │ *                              │
│ 122          │ *                              │
└──────┴────────────┴────────────────────────────────┘

性能

SQLite 可以順利處理億級數據量的數據。通常的 INSERT 操作在我的筆記本上每秒可以跑 24 萬條。另外,如果你是做CSV文件關聯到虛擬表(通過插件)的話,INSERT 操作還可以再快 2 倍。

.load sqlite3-vsv

create virtual table temp.blocks_csv using vsv(
    filename="ipblocks.csv",
    schema="create table x(network text, geoname_id integer, registered_country_geoname_id integer, represented_country_geoname_id integer, is_anonymous_proxy integer, is_satellite_provider integer, postal_code text, latitude real, longitude real, accuracy_radius integer)",
    columns=10,
    header=on,
    nulls=on
);
.timer on
insert into blocks
select * from blocks_csv;

Run Time: real 5.176 user 4.716420 sys 0.403866
select count(*) from blocks;
3386629

Run Time: real 0.095 user 0.021972 sys 0.063716

開發者間流行的觀點是 SQLite 不適用於互聯網,因為它不支持並行查詢。這是錯覺。在很早就支持的 write-ahead log 模式下,想要多少並發讀取就可以有多少。只能有一個並發寫入,不過通常一個就夠了。

SQLite 完美適用於小型網站和應用。sqlite.org 使用 SQLite 作為數據庫,在不優化的情況下(大概每頁200個請求)。它每個月可以處理70萬的訪問並且比我見過的95%的網站都更快。

文檔,圖,搜索

SQLite 支持部分索引以及索引到表達式,就像那些“大型” DBMS 一樣。你可以索引創建的列,甚至可以把 SQLite 轉換為一個文檔數據庫。只需要存入原始 JSON,並且在 json_extract() 得到的列上建立索引:

create table currency(
  body text,
  code text as (json_extract(body, '$.code')),
  name text as (json_extract(body, '$.name'))
);

create index currency_code_idx on currency(code);

insert into currency
select value
from json_each(readfile('currency.sample.json'));
explain query plan
select name from currency where code = 'EUR';

QUERY PLAN
`--SEARCH TABLE currency USING INDEX currency_code_idx (code=?)

你也可以像用圖數據庫一樣來用 SQLite。可以通過一系列復雜的 WITH RECURSIVE 來實現,你比較傾向加點 Python 也行:

simple-graph @ GitHub

全文搜索開箱即用:

create virtual table books_fts
using fts5(title, author, publisher);

insert into books_fts
select title, author, publisher from books;

select
  author,
  substr(title, 1, 30) as title,
  substr(publisher, 1, 10) as publisher
from books_fts
where books_fts match 'ann'
limit 5;
┌─────────────────────┬────────────────────────────────┬────────────┐
│       author        │             title              │ publisher  │
├─────────────────────┼────────────────────────────────┼────────────┤
│ Ruby Ann Boxcar     │ Ruby Ann's Down Home Trailer P │ Citadel    │
│ Ruby Ann Boxcar     │ Ruby Ann's Down Home Trailer P │ Citadel    │
│ Lynne Ann DeSpelder │ The Last Dance: Encountering D │ McGraw-Hil │
│ Daniel Defoe        │ Robinson Crusoe                │ Ann Arbor  │
│ Ann Thwaite         │ Waiting for the Party: The Lif │ David R. G │
└─────────────────────┴────────────────────────────────┴────────────┘

或者你需要一個內存數據庫來進行一些即時的運算?一行 Python 搞定:

db = sqlite3.connect(":memory:")

你甚至可以通過多個連接請求它:

db = sqlite3.connect("file::memory:?cache=shared")

還有更多...

有炫酷的窗函數(window functions),就像 PostgreSQL。還有 UPSERT,UPDATE FROM,以及 generate_series() 。R樹索引。正則表達式,模糊搜索,以及地理數據(geo)。

在功能層面,SQLite 可以與任何“大型” DBMS 競爭。

SQLite 周邊有一批很棒的工具。我尤其喜歡 Datasette —— 一個探索、發布 SQLite 數據集的開源工具。 DBeaver 是另一個優秀的開源數據庫 IDE,並且支持最新版本的 SQLite。

我希望這篇文章能夠促使你嘗試下 SQLite。感謝閱讀!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM