COM6002 Big Data Management · Week 7
NoSQL Databases: Graph, Column, Wide-column, In-memory, Search & Vector
COM6002 · Week 7 · Source: 7-NoSQL.pptx (62 slides)
Contents · 15 sections
🎯 本講重點 (Learning outcomes)
- NoSQL 嘅定義同點解流行(flexible schema、agile development);document store(MongoDB)留待下一章。
- Graph database:Index-Free Adjacency、graph analytics 同 fraud detection、Knowledge Graph、RDF。
- Column-oriented database:row vs column storage、disk I/O 計算、compression、read-optimized vs write-optimized。
- Wide-column database:Bigtable data model、append-only logs、LSM tree、優缺點。
- In-memory key-value database:Redis、persistence options、indexing、use cases。
- Search engine:inverted index、analysis pipeline、TF-IDF 計算、BM25 嘅改良、fuzzy search。
- Vector database:embedding、semantic search、cosine similarity、brute force vs IVF vs HNSW。
⭐ 考試必溫 Top-5
- Row vs column storage 嘅 disk I/O:sum 一個 column(3 vs 1)、insert 一個 record(2 vs 4);RDBMS write-optimized、column-oriented read-optimized。
- Bigtable:
(row, column, time) → value;LSM tree 三步;wide-column 嘅優點(scalability、fast write、no null overhead)同缺點(join、read latency、eventual consistency)。 - TF-IDF 手計:textbook vs scikit-learn 版本、slides 47–49 例題、L2 normalization。
- Analysis pipeline 次序同 inverted index;TF-IDF 三個問題同 BM25 點樣改良(BM25 formula 本身 slide 列明唔使考)。
- Cosine similarity / distance;kNN 三種方法:Brute force 、IVF 、HNSW ,同 IVF vs HNSW 嘅優點。
1. NoSQL 概覽(slides 2–3)
NoSQL stands for Not Only SQL,係 a broad class of non-relational DBMS。Slide 特別 note:有啲 NoSQL database 都係用 table structure,所以唔好將 NoSQL 等同「冇 table」。
ExamNoSQL 通常支援 flexible schema,過去十年喺新 applications / companies 好流行,原因係 agile development:requirements change rapidly,而 database schema 一改,就要 migrate 現有 data 去新結構。
| 類型 | 例子 | 專長 |
|---|---|---|
| Graph database | Neo4j | 搵 nodes 之間嘅關係 |
| Column-oriented database | KDB | Column-based process,例如計一個 attribute 嘅 mean / mode |
| Wide column store | Cassandra | Distributed environment,處理 extremely large amount of data |
| In-memory database | Redis | 速度 |
| Search engine | Elasticsearch | 全文搜尋 |
| Vector database | Pinecone、Qdrant、Chroma、FAISS | Semantic search |
| Document store | MongoDB | 下一章(Next chapter) |
Week 1 已經介紹過 NoSQL,而且提醒 RDBMS 仍然最多人用。呢一講就係逐種 NoSQL 深入講佢解決 RDBMS 嘅咩問題、又犧牲咗啲咩。
2. Graph database(slides 4–5)
Graph 其實可以用 table 表示(slide 4 嘅 edge table,共 4 個 nodes):
| From | To | Weight |
|---|---|---|
| 1 | 2 | 3 |
| 2 | 3 | 4 |
| 3 | 1 | 5 |
| 3 | 4 | 5 |
既然 table 都存到,點解仲要 graph database?
| Problems with RDBMS | Graph database solution |
|---|---|
| Joins are expensive:要搵 nodes 之間嘅關係,需要大量 joins | Native support for graph operations;Index-Free Adjacency:直接儲存相連 nodes 之間嘅 pointers,達到 constant traversal time |
Graph query language:Neo4j 用 Cypher。
喺 edge table 搵「朋友嘅朋友嘅朋友」,每行多一層就多一個 self-join。Graph database 就好似每個 node 手上已經有齊鄰居地址,順住 pointer 行就得,每一步都唔使再查 index。
3. Graph analytics(slides 6–10)
| Method | 做咩 | Example application |
|---|---|---|
| Breadth-first search | 先探索 depth 1 嘅所有 direct neighbours,再去 depth 2,如此類推 | 判斷 social network 上一個 user 同另一個 user 係咪喺某個距離內 |
| PageRank | 量度 nodes 嘅相對 importance / influence;最初由 Google 開發 | 搵 influential users / key opinion leaders |
| Weakly connected components | 搵 subgraphs,入面每對 nodes 互相 reachable;數目 = Number of Islands | Fraud Detection & Identity Resolution |
| Community detection(label propagation) | 每個 node 由 unique label 開始,反覆更新做鄰居入面嘅 majority label,直至 convergence | Marketing Segmentation、Content Targeting |
| Local clustering coefficient | 量度一個 node 嘅 immediate neighbours 幾接近形成 complete graph | Spam and fake account detection |
| Single source shortest paths | 由一個 source 計去其他 nodes 嘅最短路徑(Dijkstra 1959) | Route optimization |
- Slide 7:「weakly」嘅意思係 reachable 時唔理 edge 方向。Directed graph 入面要順住方向都 reachable,一般叫 strongly connected。Slide 7 嘅圖有 3 個獨立 groups(Alex/Bob/Justin、Chase/Damon/Eddie、George/Fiona/Howard/Ivy),所以係 3 個 components。
- Slide 9:文字話每個 node 由 unique label 開始,但圖只係部分 nodes 有 label(兩種顏色),Pass 1、Pass 2 逐步擴散。圖同文字係唔同嘅起始設定,答題時跟文字嘅定義就得。
Fraud detection 例子(slide 8)
ExamTarget scenario:有人操作幾百個 fake accounts。Observation:佢哋無可避免會共用 subtle resources,例如同一個 IP address、credit card、Wi-Fi network 或 delivery address。
Graph construction:Node = Account;兩個 accounts 有一個或以上 features 相同就連 edge。Fake accounts 就會形成一個大嘅 weakly connected component。
| Handling false positives | 做法 |
|---|---|
| Filtering supernodes | 排除例如 public computers,因為好多無關嘅人都會共用 |
| Weights and thresholds | 同 IP = low weight;同 credit card = high weight;common features 越多 weight 越高;再設 strict connectivity threshold,例如要有一條 high-weight path,或多條 medium-weight paths |
| Temporal relationship | 只考慮 tight time window(例如 30 mins)內嘅 activities |
4. Knowledge Graph 同 RDF(slides 11–12)
Knowledge Graph 曾經係 AI 嘅 leading techniques 之一:IBM Watson 喺 2011 年嘅問答節目 Jeopardy 贏咗兩位 human experts。Slide 11 嘅圖用 nodes 同 edges 表達知識,例如 Da Vinci painted Mona Lisa、Mona Lisa is in Louvre。
ExamRDF (Resource Description Framework) 技術上係一個 graph,每個 RDF record 有 3 個 components:Subject、Predicate、Object。命名用 URI-based vocabularies(同 linked data 一樣),query language 係 SPARQL(the query language of the Semantic Web)。
| Subject | Predicate | Object |
|---|---|---|
| Da Vinci | painted | Mona Lisa |
5. Column-oriented database(slides 13–19)
Exam核心分別:Standard RDBMS stores data by rows;column-oriented database stores data by columns(C-Store,Stonebraker et al., VLDB 2005)。例子 KDB 喺 financial industry 幾流行,支援 time-series data,query language 係 Q,不過 difficult to learn。Slide 13 附咗一張香港 Citibank KDB Engineer 招聘截圖,顯示業界需求。
Sample data(slide 14):
| x1 | x2 | x3 | x4 |
| x5 | x6 | x7 | x8 |
| x9 | x10 | x11 | x12 |
| Storage | Data on disk |
|---|---|
| RDBMS(by rows) | x1, x2, x3, x4, …, x11, x12 |
| Column-oriented(by columns) | x1, x5, x9 | x2, x6, x10 | x3, x7, x11 | x4, x8, x12 |
| Task | RDBMS | Column-oriented | 原因 |
|---|---|---|---|
| Sum 第一個 column(x1, x5, x9) | 3 disk I/O | 1 disk I/O | Row storage 入面 x1、x5、x9 分散喺三個 blocks:(x1–x3)、(x4–x6)、(x7–x9);column storage 就連續擺埋一齊 |
| Adding a new record(4 values) | may need 2 disk I/O | 4 disk I/O | Row storage 將 4 個 values 連續寫,最多跨 2 個 blocks;column storage 要每個 column 寫一次 |
結論(slide 18,出自 C-Store paper abstract 第一句):RDBMS is write-optimized,column-oriented database is read-optimized。
Compression(slide 17)
ExamColumn-based compression 可以有較高 compression rate,因為 data within the same column are of very similar nature,帶來 lower storage cost 同 faster processing speed。
| 方法 | 例子 column | Data | Compressed |
|---|---|---|---|
| Run-Length Encoding | sex / gender | F, F, F, M, M, F, F | F3M2F2 |
| Dictionary Encoding | district | Sha Tin, Central, Sha Tin, Tai Po | 1, 2, 1, 3(Dictionary:Sha Tin → 1,Central → 2,Tai Po → 3) |
Sample use case(slide 19)
好適合 data analytics in finance:有好多 columns(MACD、RSI、Bollinger Bands 等 technical analysis),但 quantitative analysis 通常只用少數 columns,例如計一個 feature 嘅 mean、standard deviation、confidence intervals,或者兩個 features 嘅 correlation。
COM6001 嘅 df['col'].mean()、df[['a','b']].corr(),同 COM6005 嘅 Confidence Interval,都係呢類「只掂少數 columns」嘅運算。
6. Wide-column database(slides 20–29)
ExamPurpose:make the database highly scalable by horizontal scaling。例子:Cassandra、HBase。源頭係 Google Bigtable(OSDI 2006)。
Column-oriented(KDB)同 wide-column(Cassandra)名似但目的唔同:前者將同一 column 擺埋一齊,提升 analytics 讀取;後者重點係 horizontal scaling 同高 write throughput。
6.1 由 RDBMS 到 Bigtable(slides 21–22)
將多個 tables join 成一張 single big table,呢張 table 有咩特性?Big 同 Sparse,好多格都係空嘅。
Bigtable 係一個 map:
(row:string, column:string, time:int64) → string
提供 row ID、column ID 同 timestamp,就得到 data contents。有 timestamp,所以可以取得唔同時間嘅 versions(recall MVCC)。呢個諗法最初嚟自儲存 Internet data:Row 係 website,column 係 property 嘅名。
Sample data(slide 23):
| ID | Name | Association | Hobby |
|---|---|---|---|
| 1 | Amy | Red Cross | |
| 2 | Bob | Badminton |
對應嘅 Bigtable data:
| Row ID | Column | Time | Value |
|---|---|---|---|
| 1 | Name | 1 Jan 2020 | Diana |
| 1 | Name | 1 Jan 2023 | Amy |
| 1 | Association | 1 Jan 2020 | Red Cross |
| 2 | Name | 1 Jan 2020 | Bob |
| 2 | Hobby | 1 Jan 2020 | Badminton |
留意三件事:Row 1 嘅 Name 有兩個 versions,最新係 Amy;空格(Amy 冇 Hobby)根本唔使儲,就係 no null overhead;要還原返關係型嗰張 table,就要 self-join(slide 24)。
Slides 23–24 嘅 Bigtable table 將 column 寫成 “Hobbit”,對照上面應該係 Hobby。上表已更正。
6.2 Query(slide 25)
Wide-column database 一般唔用 SQL。Cassandra 用類似 SQL 嘅 Cassandra Query Language (CQL),但 CQL 冇 JOIN operator。
6.3 Append-only logs 同 LSM tree(slide 26)
有新 update 時,只係 insert 一個新 version,updates are processed sequentially。
專為 append-only write operations 優化嘅 data structure:
- Buffer incoming writes in memory。
- 間中 flush 去 disk,變成 immutable, sorted records。
- 喺背景持續 merge and compact,清走 deleted / outdated records。
6.4 優缺點(slides 27–28)
| Advantages | Problems |
|---|---|
| Massive (horizontal) scalability:大家用同一個 underlying schema,專為 distributed environment 設計 | Poor support of complex queries that require “join”:例如 enrollment 只記 student ID 同 module code,要搵 Amy 讀咩 module 嘅名就要 join |
| Fast write throughput:append-only 令 write 容易處理(例如 no locking) | Higher read latency(相對 RDBMS):要花多啲功夫喺 LSM trees 搵最新 data |
| No Null overhead | Only provide eventual consistency:喺原本 Google search engine 嘅應用唔係大問題,用戶未攞到網站最新內容都可以接受 |
Example applications(slide 29):IoT & sensor data logging(大量 devices 持續發 data);Discord 用 ScyllaDB,因為 chat applications 有 heavy write volume,而且可以按 channels 自然 partition。
Week 6 嘅 horizontal fragmentation、MVCC、CAP 同 BASE 喺度全部用得著:eventual consistency 就係 BASE 嘅 “E”,代表為咗 availability 同 scalability 而放寬 consistency。
7. In-memory key-value database:Redis(slides 30–37)
7.1 點解 in-memory?(slides 30、33)
| Storage | Benchmark read/write speed |
|---|---|
| Magnetic harddisk | 80 MB/s – 160 MB/s |
| SSD harddisk | 200 MB/s – 550 MB/s |
| RAM (Memory) | 2 GB/s – 20 GB/s |
ExamRAM 最快,但 volatile:一斷電 data 就冇晒。Redis 嘅做法係 data 主要放 RAM,permanent storage(例如 harddisk)作 backup。
另一個問題:RAM is expensive and limited,所以 compression is critical。Slide 33 嘅價錢截圖:8TB HDD 賣 $2699,16GB RAM 賣 $1499,以每 GB 計 RAM 貴接近 280 倍。Trade-off:compression / decompression 有 computational cost,最終 performance 視乎 data 嘅性質。
7.2 Redis 特性(slide 31)
- Key-value store,例如 key
"session:auth:98342"對應{"user_id": "usr_01H7X", "status": "authenticated"}。 - Index on key only,唔支援其他 fields 嘅 secondary index,所以 querying power 有限。
- Simple sharding:hashed sharding,without strong consistency check。
- Optimized for speed but sacrifice consistency。
7.3 Persistence options(slide 32)
| Option | 做法 |
|---|---|
| Snapshot | 按指定 intervals 做 point-in-time snapshots |
| AOF (Append Only File) | Log 每個 write operation,server 啟動時 replay 去重建 dataset;用同 Redis protocol 一樣嘅格式 |
| No persistence | 斷電 data 就冇 |
| Snapshot + AOF | 兩者一齊用 |
AOF 同 Week 3 嘅 log-based recovery 諗法相近;Snapshot 就有啲似 checkpoint。兩者都係靠額外記錄,喺故障後還原 data。
7.4 Indexing(slide 34)
Exam傳統 indexing(例如 B-tree)唔適合 in-memory database:佢哋係為 I/O optimal 而設計,放喺 memory 就 suboptimal。Preferred 方法係 Hash table: time access,但 no range queries。
B-tree 每個 node 擺好多 keys,目的係減少讀 disk 嘅次數;喺 RAM 冇 disk I/O 成本,呢個設計就失去優勢。Hash table 打散 keys,所以搵單一 key 快,但做唔到「搵 A 至 B 之間」。
7.5 NVRAM(slide 35)
Non-volatile RAM:比 volatile RAM 慢,但 power off 都保留 data。現時 Redis 冇用 NVRAM 做 primary memory,不過可以作較快嘅 backup and recovery layer。
7.6 Use cases 同其他系統(slides 36–37)
| Use case | 原因 |
|---|---|
| User session management | 暫存 visit 期間嘅 user data(例如 shopping cart),冇 activity 一段時間就 expire |
| Leaderboards in gaming | 大量 players 要 fast update |
| High-Frequency Trading | 需要 low latency |
| Other in-memory databases | 特點 |
|---|---|
| VoltDB | For relational data;NewSQL |
| SAP HANA | Column-oriented storage |
| Memcached | Key-value store,even simpler than Redis |
8. Search engine:Elasticsearch(slides 38–41)
Data 係 JSON 格式嘅 documents,Exam核心係 inverted index:mapping words to document IDs。
| ID | Term | Document |
|---|---|---|
| 1 | butterfly | 1 |
| 2 | blue | 1, 2 |
| 3 | bright | 1, 2 |
上表節錄自 slide 38 嘅圖(Document 1 “The bright blue butterfly hangs on the breeze”;Document 2 “Under blue sky, in bright sunlight, one need no search around”)。圖入面仲有 retire、wind 指向 Document 2,但呢兩個字唔喺 Document 2 嘅句子,應該係圖本身嘅問題,所以冇抄入表。
正常係「document → 入面有咩字」;inverted 就倒轉,變成「字 → 喺邊啲 documents」,搜尋時就唔使逐份 document 掃。
Elastic Stack (ELK)(slide 39):
| Component | 角色 |
|---|---|
| Logstash | Data pipeline tool,由多個 sources ingest data |
| Elasticsearch | The core engine |
| Kibana | Frontend interface |
Analysis pipeline:由 text 到 terms(slides 40–41)
| Step | 做咩 | 結果 |
|---|---|---|
| 原文 | <p> The quick brown Fox's Tail, is nice.</p> | |
| 1. Character filter | 抽取 text contents,例如移除 HTML tags | The quick brown Fox's Tail, is nice. |
| 2. Tokenizer | 將字元流拆成 tokens | [The, quick, brown, Fox's, Tail, is, nice] |
| 3. Normalization | 統一同一個字嘅 tokens,例如 Apple → apple | [the, quick, brown, fox's, tail, is, nice] |
| 4. Stopword filter | 移除 high-frequency non meaningful words(the、a、is) | [quick, brown, fox's, tail, nice] |
| 5. Stemming filter | 轉成 root form,例如 ran → run | [quick, brown, fox, tail, nice] |
Slide 41 另外列出 Synonym filter:按 defined list 取代或者加 tokens,例如 automobile → car。Slide 40 嘅例子冇用到呢一步。
9. Relevance score 同 TF-IDF(slides 42–49)
點解要 rank?簡單 term matching 通常返回大量 documents,但唔知邊份較 relevant。Relevance score 就係代表 document 同 search query 相關程度嘅數值。流行演算法係 BM25(Best Matching),由 TF-IDF 改良而成。
9.1 Formula(slides 43–45)
係 term 喺 document 嘅 term frequency; 係 inverse document frequency,對所有 documents 都一樣。
| Textbook version | Scikit-learn version | |
|---|---|---|
| count of in | ||
:total number of documents;:number of documents containing 。
TF:呢份 document 提得越多,越可能同呢個字有關。IDF:越多 documents 都有嘅字越冇鑑別力。“cat” 三份都有,IDF 最低;“chased” 只得一份有,IDF 較高。
9.2 例題(slides 43、46–49)
Corpus:
- :The cat sat on the mat.
- :The cat chased the cat.
- :The mouse ran from the cat.
移除 stop words(the、on、from)後,Vocabulary = [cat, chased, mat, mouse, ran, sat]。
Step 1:TF(scikit-learn 版本,即 count)
| cat | chased | mat | mouse | ran | sat | |
|---|---|---|---|---|---|---|
| 1 | 0 | 1 | 0 | 0 | 1 | |
| 2 | 1 | 0 | 0 | 0 | 0 | |
| 1 | 0 | 0 | 1 | 1 | 0 |
Step 2:IDF()
mat、mouse、ran、sat 都只喺一份 document 出現,所以 IDF 同 chased 一樣,都係 。
Step 3:TF × IDF(normalization 之前),例如 :
| cat | chased | mat | mouse | ran | sat | |
|---|---|---|---|---|---|---|
| 1 | 0 | 0 | 0 | |||
| 2 | 0 | 0 | 0 | 0 | ||
| 1 | 0 | 0 | 0 |
Step 4:L2 norms
Step 5:每行除以該行嘅 norm(final result,slide 49)
| cat | chased | mat | mouse | ran | sat | |
|---|---|---|---|---|---|---|
| 0.3854 | 0 | 0.6525 | 0 | 0 | 0.6525 | |
| 0.7632 | 0.6461 | 0 | 0 | 0 | 0 | |
| 0.3854 | 0 | 0 | 0.6525 | 0.6525 | 0 |
手計方法:;;;。
from sklearn.feature_extraction.text import TfidfVectorizer
corpus = ["The cat sat on the mat.",
"The cat chased the cat.",
"The mouse ran from the cat."]
vectorizer = TfidfVectorizer(stop_words=['the', 'on', 'from'])
X = vectorizer.fit_transform(corpus).toarray()
print(vectorizer.get_feature_names_out()) # ['cat' 'chased' 'mat' 'mouse' 'ran' 'sat']
print(vectorizer.idf_) # [1. 1.6931 1.6931 1.6931 1.6931 1.6931]
print(X.round(4)) # 同 slide 49 一樣
Textbook version 比較(自編,唔係 slide 內容):,所以 cat 嘅 TF-IDF 喺每份 document 都係 0。假設 total terms 以移除 stop words 後計( 有 3 個),。
- Textbook 用 ,scikit-learn 用 ;scikit-learn 嘅 “+1” 有兩個位置(分數上下各一,加上 log 之外再加一)。
- Scikit-learn 版本嘅 IDF 最少係 1,唔會變 0;textbook 版本出現喺所有 documents 嘅字 IDF 就係 0。
- Normalization 係每份 document(每個 row)獨立除以自己嘅 norm,唔係全表一個 norm。
10. TF-IDF 嘅問題同 BM25(slides 50–51)
| TF-IDF 嘅問題 | 解釋 | BM25 嘅做法 |
|---|---|---|
| Linear TF Increase(Saturation Issue) | 出現 50 次得到 10 次嘅 5 倍 weight,但 relevance 唔係線性上升 | Term Frequency Saturation:modified TF function,限制 term frequency 令 score 上升嘅速度 |
| Bias to Long Documents(Normalization Issue) | 雖然有 normalization,但唔足夠,較長 documents 仍然著數 | Improved Length Normalization:用 tuneable parameters 控制 document length 嘅影響 |
| Lack of Tuning | No hyperparameter tuning | 有 tuneable parameters |
只作理解用: 控制 saturation, 控制 length normalization 嘅強度。
11. Elasticsearch 嘅其他功能同應用(slides 52–53)
Fuzzy search:連相似嘅字都會返回,similarity 用 edit distance 量度。Use case:user 打錯字,想搵 “fox” 但打咗 “box”;兩個字只差一個字母,edit distance 係 1。
| Application | 做咩 |
|---|---|
| Website search | 搵個 phrase 喺網站邊度出現 |
| Enterprise search | 搵企業入面邊份 document 有呢個 phrase |
| Data analytics | 統計唔同 search phrases 嘅出現次數再分析,例如喺 treemap 顯示 incident documents 最常見嘅原因 |
12. Vector database(slides 54–58)
Vector data 例子:User-Product ratings(YouTube、Netflix)、item features(例如 TF-IDF 產生嘅 feature vector)、text / image / 任何 data type 嘅 embedding(Generative AI / LLM,呢度嘅重點)。
Pure vector databases:Pinecone、Qdrant、Chroma、FAISS。隨住 vector database 流行,PostgreSQL、MongoDB、Oracle 等都開始實作 vector functions。
ExamEmbedding model(slide 55):neural network model,將 data 映射成 dense vector。兩個 inputs semantically similar,佢哋嘅 vectors 就會 close to each other。例子:nomic-embed-text-v2-moe(text,multilingual)、CLIP(image)、Gemini Embedding 2(multimodal)。
- 將 text data chunk 成小塊。
- 每個 text chunk embed 成 vector。
- 將 query text 轉成 query vector。
- 用 query vector 搵最接近嘅 data vectors(k Nearest Neighbor search)。
- 結果 text chunks 就會同 query semantically similar。
Why not a keyword search? 有 keyword 唔代表 relevant;冇 keyword 亦唔代表唔 relevant。
係 vector 嘅 magnitude, 係 同 之間嘅角度。Embedding model 通常 output unit vector(magnitude = 1),所以 cosine similarity 就等於 dot product。
自編例子:,。,,,similarity ,distance 。
Slide 58 列出 MongoDB 嘅 options:$similarityCosine、$similarityDotProduct、$similarityEuclidean。
Cosine similarity 同 COM6004 Chapter 2 係同一條式;kNN 嘅諗法同 Chapter 4A 嘅 KNN classifier 一樣都係搵最近鄰居。
13. kNN 計算:Brute force、IVF、HNSW(slides 59–62)
| Brute force | IVF(Inverted File Index) | HNSW(Hierarchical Navigable Small World) | |
|---|---|---|---|
| Idea | 同每個 vector 比較 | 先用 K-means 將 data 分 cluster,只搜尋 candidate clusters | 多層 graph,由 sparse 層逐步落到 dense 層 |
| Complexity (average) | |||
| Worst case | |||
| Results | Exact | Approximate only | Approximate only |
| Used by | FAISS | Pinecone、Qdrant、Chroma、PostgreSQL(more popular) | |
| Advantages | Use less memory (RAM) | Faster search time;No re-training(IVF 需要 K-means clustering) |
HNSW 結構(slide 60):
- A higher layer is a sparser subset of the lower layer。
- 最底嘅 ground layer 包含所有 vectors。
- 每一層,每個 node 都記住 neighbours 嘅 edges。
- 由 top layer 開始。
- Loop:greedily hop 去最近嘅 neighbours,然後落去較 dense 嘅一層,發掘更近嘅 neighbours。
- 到 ground layer,refine closest neighbours 嘅 list,返回 top K。
好似搭交通工具:先搭飛機(top layer,站少跳得遠)飛到附近城市,再轉火車,最後行路(ground layer)去到目的地。
IVF 用嘅 K-means 就係 COM6004 Chapter 5 嘅 K-means。Data 變動時 clusters 可能要重新計,所以 slide 62 話 HNSW 嘅優點係 no re-training。
自我測驗 Self-test
Q1. NoSQL 代表咩?點解 agile development 會令 NoSQL 流行?
Not Only SQL。Requirements 轉得快,而 RDBMS schema 一改就要 migrate 現有 data;NoSQL 通常支援 flexible schema,唔使咁麻煩。
Q2. 點解 graph database 比 RDBMS 更適合搵關係?
RDBMS 要大量 expensive joins。Graph database 用 Index-Free Adjacency,直接儲存相連 nodes 嘅 pointers,traversal time 係 constant。
Q3. 12 rows × 4 columns 嘅 table,每次 disk I/O 讀 3 個 values。Sum 一個 column,row storage 同 column storage 各要幾多次 I/O?
Column storage:12 個 values 連續擺放,12/3 = 4 次。Row storage(以第一個 column 為例):佢哋喺第 1、5、9、…、45 個位置,每個都落喺唔同 block,所以 12 次。
Q4. 將 A, A, B, B, B, A 用 Run-Length Encoding 壓縮;將 Red, Blue, Red, Green 用 Dictionary Encoding 壓縮。
A2B3A1。1, 2, 1, 3,Dictionary:Red → 1,Blue → 2,Green → 3。
Q5. Bigtable 嘅 data model 係咩?Timestamp 有咩用?
(row:string, column:string, time:int64) → string。Timestamp 令系統可以保存同取得同一格喺唔同時間嘅 versions。
Q6. 解釋 LSM tree;點解 wide-column database write 快但 read 慢?
Writes 先 buffer 喺 memory,間中 flush 成 immutable sorted records,背景 merge and compact。Update 只係 append 新 version,所以 write 快(例如 no locking);read 就要喺 LSM trees 花功夫搵最新 data,所以 latency 較高。
Q7. 點解 B-tree 唔適合 in-memory database?Hash table 嘅代價係咩?
B-tree 為 I/O optimal 而設計,喺 memory 入面 suboptimal。Hash table 有 access,但做唔到 range queries。
Q8. 寫出 Redis 嘅 persistence options。AOF 點樣還原 data?
Snapshot、AOF、No persistence、Snapshot + AOF。AOF 記錄每個 write operation,server 啟動時 replay 去重建 dataset。
Q9. 排列 analysis pipeline,並處理 “<b>The Apples ran</b>”。
Character filter → Tokenizer → Normalization → Stopword filter → Stemming filter。結果:The Apples ran → [The, Apples, ran] → [the, apples, ran] → [apples, ran] → [apple, run]。
Q10. 用 scikit-learn 版本:,term 喺 1 份 document 出現,喺 出現 3 次。求 TF-IDF(未 normalize)。
,TF = 3,所以 TF-IDF 。
Q11. 同上,改用 textbook 版本,假設 共有 10 個 terms。
TF = 3/10 = 0.3;;TF-IDF 。
Q12. BM25 解決咗 TF-IDF 嘅咩問題?
Term frequency saturation(TF 唔再線性上升)、improved length normalization(減少偏向長 documents),而且有 tuneable parameters。
Q13. 比較 IVF 同 HNSW。如果 RAM 好緊張,揀邊個?
IVF:、用較少 RAM、需要 K-means。HNSW:、較快、唔使 re-training、較流行。兩者都只係 approximate。RAM 緊張就揀 IVF。
Q14. 以下情況用邊種 database?(a) 記錄大量 IoT sensor readings;(b) 搵 fake account 集團;(c) 遊戲 leaderboard;(d) 計幾百個 columns 入面某一個 column 嘅 mean;(e) 用意思而唔係關鍵字搜尋文件。
(a) Wide-column;(b) Graph;(c) In-memory(Redis);(d) Column-oriented;(e) Vector database。
一頁總結 Cheat sheet
- NoSQL = Not Only SQL;flexible schema;agile development。MongoDB 留待下一章。
- Graph:Joins expensive → Index-Free Adjacency(pointers,constant traversal);Cypher。BFS、PageRank、Weakly connected components(fraud)、label propagation(segmentation)、local clustering coefficient(spam)、shortest paths(route)。RDF = Subject + Predicate + Object;SPARQL。
- Column-oriented:讀 3 → 1 I/O;insert 2 → 4 I/O;read-optimized vs RDBMS write-optimized。RLE:F3M2F2;Dictionary:1,2,1,3。KDB + Q,finance。
- Wide-column:
(row, column, time) → value;Big + Sparse;CQL 冇 JOIN。LSM:buffer → flush → merge & compact。優:scalability、fast write、no null overhead。缺:join、read latency、eventual consistency。 - Redis:RAM 快但 volatile;key-only index;Snapshot / AOF / None / Snapshot + AOF;hash table 、no range queries,B-tree 唔適合。Session、leaderboard、HFT。
- Elasticsearch:inverted index(word → document IDs);ELK;Character → Tokenizer → Normalization → Stopword → Stemming(另有 Synonym)。Fuzzy search = edit distance。
- TF-IDF:textbook TF = count/total,IDF = ;sklearn TF = count,IDF = ,再 L2 normalize 每個 document。
- BM25:saturation、length normalization、tuneable;formula 唔使考。
- Vector:chunk → embed → query vector → kNN。Cosine = ,distance = 1 − similarity;unit vector 時 = dot product。
- kNN:Brute ;IVF (K-means、省 RAM、FAISS);HNSW (多層、no re-training、更流行)。後兩者 worst case ,只係 approximate。