All Revision Notes

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

  1. Row vs column storage 嘅 disk I/O:sum 一個 column(3 vs 1)、insert 一個 record(2 vs 4);RDBMS write-optimized、column-oriented read-optimized。
  2. Bigtable:(row, column, time) → value;LSM tree 三步;wide-column 嘅優點(scalability、fast write、no null overhead)同缺點(join、read latency、eventual consistency)。
  3. TF-IDF 手計:textbook vs scikit-learn 版本、slides 47–49 例題、L2 normalization。
  4. Analysis pipeline 次序同 inverted index;TF-IDF 三個問題同 BM25 點樣改良(BM25 formula 本身 slide 列明唔使考)。
  5. Cosine similarity / distance;kNN 三種方法:Brute force O(n)O(n)、IVF O(n)O(\sqrt{n})、HNSW O(lg⁡n)O(\lg n),同 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 去新結構。

⭐ NoSQL 種類一覽(slides 3、54)
類型例子專長
Graph databaseNeo4j搵 nodes 之間嘅關係
Column-oriented databaseKDBColumn-based process,例如計一個 attribute 嘅 mean / mode
Wide column storeCassandraDistributed environment,處理 extremely large amount of data
In-memory databaseRedis速度
Search engineElasticsearch全文搜尋
Vector databasePinecone、Qdrant、Chroma、FAISSSemantic search
Document storeMongoDB下一章(Next chapter)

2. Graph database(slides 4–5)

Graph 其實可以用 table 表示(slide 4 嘅 edge table,共 4 個 nodes):

FromToWeight
123
234
315
345

既然 table 都存到,點解仲要 graph database?

⭐ RDBMS 嘅問題 vs Graph database 嘅解決方法(slide 5)
Problems with RDBMSGraph database solution
Joins are expensive:要搵 nodes 之間嘅關係,需要大量 joinsNative 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)

⭐ Graph analytics 同 application 配對
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 IslandsFraud Detection & Identity Resolution
Community detection(label propagation)每個 node 由 unique label 開始,反覆更新做鄰居入面嘅 majority label,直至 convergenceMarketing Segmentation、Content Targeting
Local clustering coefficient量度一個 node 嘅 immediate neighbours 幾接近形成 complete graphSpam and fake account detection
Single source shortest paths由一個 source 計去其他 nodes 嘅最短路徑(Dijkstra 1959)Route optimization
⚠️ 留意 slides 嘅寫法
  • 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)。

SubjectPredicateObject
Da VincipaintedMona 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):

x1x2x3x4
x5x6x7x8
x9x10x11x12
StorageData 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
⭐ Disk I/O 計算(slides 15–16,假設每次 disk I/O 讀 3 個 values)
TaskRDBMSColumn-oriented原因
Sum 第一個 column(x1, x5, x9)3 disk I/O1 disk I/ORow storage 入面 x1、x5、x9 分散喺三個 blocks:(x1–x3)、(x4–x6)、(x7–x9);column storage 就連續擺埋一齊
Adding a new record(4 values)may need 2 disk I/O4 disk I/ORow 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。

⭐ 兩種 encoding
方法例子 columnDataCompressed
Run-Length Encodingsex / genderF, F, F, M, M, F, FF3M2F2
Dictionary EncodingdistrictSha Tin, Central, Sha Tin, Tai Po1, 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。

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 data model(slide 22)

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):

IDNameAssociationHobby
1AmyRed Cross
2BobBadminton

對應嘅 Bigtable data:

Row IDColumnTimeValue
1Name1 Jan 2020Diana
1Name1 Jan 2023Amy
1Association1 Jan 2020Red Cross
2Name1 Jan 2020Bob
2Hobby1 Jan 2020Badminton

留意三件事:Row 1 嘅 Name 有兩個 versions,最新係 Amy;空格(Amy 冇 Hobby)根本唔使儲,就係 no null overhead;要還原返關係型嗰張 table,就要 self-join(slide 24)。

📎 Slide 小錯

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。

⭐ Log-Structured Merge-tree(LSM tree)

專為 append-only write operations 優化嘅 data structure:

  1. Buffer incoming writes in memory。
  2. 間中 flush 去 disk,變成 immutable, sorted records。
  3. 喺背景持續 merge and compact,清走 deleted / outdated records。

6.4 優缺點(slides 27–28)

⭐ Wide-column database 優缺點
AdvantagesProblems
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 overheadOnly 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。

7. In-memory key-value database:Redis(slides 30–37)

7.1 點解 in-memory?(slides 30、33)

StorageBenchmark read/write speed
Magnetic harddisk80 MB/s – 160 MB/s
SSD harddisk200 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)

⭐ Redis persistence
Option做法
Snapshot按指定 intervals 做 point-in-time snapshots
AOF (Append Only File)Log 每個 write operation,server 啟動時 replay 去重建 dataset;用同 Redis protocol 一樣嘅格式
No persistence斷電 data 就冇
Snapshot + AOF兩者一齊用

7.4 Indexing(slide 34)

Exam傳統 indexing(例如 B-tree)唔適合 in-memory database:佢哋係為 I/O optimal 而設計,放喺 memory 就 suboptimal。Preferred 方法係 Hash table:O(1)O(1) 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特點
VoltDBFor relational data;NewSQL
SAP HANAColumn-oriented storage
MemcachedKey-value store,even simpler than Redis

8. Search engine:Elasticsearch(slides 38–41)

Data 係 JSON 格式嘅 documents,Exam核心係 inverted index:mapping words to document IDs。

IDTermDocument
1butterfly1
2blue1, 2
3bright1, 2
🖼️ Slide 38 嘅圖

上表節錄自 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 嘅句子,應該係圖本身嘅問題,所以冇抄入表。

💡 點解叫 “inverted”

正常係「document → 入面有咩字」;inverted 就倒轉,變成「字 → 喺邊啲 documents」,搜尋時就唔使逐份 document 掃。

Elastic Stack (ELK)(slide 39):

Component角色
LogstashData pipeline tool,由多個 sources ingest data
ElasticsearchThe core engine
KibanaFrontend interface

Analysis pipeline:由 text 到 terms(slides 40–41)

⭐ Pipeline 次序同 slide 40 例子
Step做咩結果
原文<p> The quick brown Fox's Tail, is nice.</p>
1. Character filter抽取 text contents,例如移除 HTML tagsThe 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)

TF-IDF(t,d)=TF(t,d)×IDF(t)\text{TF-IDF}(t,d)=\text{TF}(t,d)\times\text{IDF}(t)

TF(t,d)\text{TF}(t,d) 係 term tt 喺 document dd 嘅 term frequency;IDF(t)\text{IDF}(t) 係 inverse document frequency,對所有 documents 都一樣。

⭐ 兩個版本要分清(slides 44–45)
Textbook versionScikit-learn version
TF(t,d)\text{TF}(t,d)count of t in dtotal number of terms in d\dfrac{\text{count of } t \text{ in } d}{\text{total number of terms in } d}count of tt in dd
IDF(t)\text{IDF}(t)log⁡10 ⁣(Ndf(t))\log_{10}\!\left(\dfrac{N}{\text{df}(t)}\right)ln⁡ ⁣(N+1df(t)+1)+1\ln\!\left(\dfrac{N+1}{\text{df}(t)+1}\right)+1

NN:total number of documents;df(t)\text{df}(t):number of documents containing tt。

💡 直覺理解

TF:呢份 document 提得越多,越可能同呢個字有關。IDF:越多 documents 都有嘅字越冇鑑別力。“cat” 三份都有,IDF 最低;“chased” 只得一份有,IDF 較高。

9.2 例題(slides 43、46–49)

Corpus:

  • d1d_1:The cat sat on the mat.
  • d2d_2:The cat chased the cat.
  • d3d_3:The mouse ran from the cat.

移除 stop words(the、on、from)後,Vocabulary = [cat, chased, mat, mouse, ran, sat]。

Step 1:TF(scikit-learn 版本,即 count)

catchasedmatmouseransat
d1d_1101001
d2d_2210000
d3d_3100110

Step 2:IDF(N=3N=3)

IDF(cat)=ln⁡1+31+3+1=1,IDF(chased)=ln⁡1+31+1+1=ln⁡2+1≈1.6931\text{IDF}(\text{cat})=\ln\frac{1+3}{1+3}+1=1,\qquad \text{IDF}(\text{chased})=\ln\frac{1+3}{1+1}+1=\ln2+1\approx1.6931

mat、mouse、ran、sat 都只喺一份 document 出現,所以 IDF 同 chased 一樣,都係 ln⁡2+1\ln2+1。

Step 3:TF × IDF(normalization 之前),例如 TF-IDF(cat,d1)=1×1=1\text{TF-IDF}(\text{cat},d_1)=1\times1=1:

catchasedmatmouseransat
d1d_110ln⁡2+1\ln2+100ln⁡2+1\ln2+1
d2d_22ln⁡2+1\ln2+10000
d3d_3100ln⁡2+1\ln2+1ln⁡2+1\ln2+10

Step 4:L2 norms

n1=n3=12+(ln⁡2+1)2+(ln⁡2+1)2≈2.5949,n2=22+(ln⁡2+1)2≈2.6204n_1=n_3=\sqrt{1^2+(\ln2+1)^2+(\ln2+1)^2}\approx2.5949,\qquad n_2=\sqrt{2^2+(\ln2+1)^2}\approx2.6204

Step 5:每行除以該行嘅 norm(final result,slide 49)

⭐ 最終結果(slide 49)
catchasedmatmouseransat
d1d_10.385400.6525000.6525
d2d_20.76320.64610000
d3d_30.3854000.65250.65250

手計方法:1/2.5949=0.38541/2.5949=0.3854;1.6931/2.5949=0.65251.6931/2.5949=0.6525;2/2.6204=0.76322/2.6204=0.7632;1.6931/2.6204=0.64611.6931/2.6204=0.6461。

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 內容):IDF(cat)=log⁡10(3/3)=0\text{IDF}(\text{cat})=\log_{10}(3/3)=0,所以 cat 嘅 TF-IDF 喺每份 document 都係 0。假設 total terms 以移除 stop words 後計(d2d_2 有 3 個),TF-IDF(chased,d2)=13×log⁡103≈0.159\text{TF-IDF}(\text{chased},d_2)=\frac13\times\log_{10}3\approx0.159。

⚠️ 常見錯誤
  • Textbook 用 log⁡10\log_{10},scikit-learn 用 ln⁡\ln;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 點改良
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 TuningNo hyperparameter tuning有 tuneable parameters
📎 BM25 formula(slide 51 列明 Not required in the exam)
score(D,Q)=∑i=1nIDF(qi)⋅f(qi,D)⋅(k1+1)f(qi,D)+k1⋅(1−b+b⋅∣D∣avgdl)\text{score}(D,Q)=\sum_{i=1}^{n}\text{IDF}(q_i)\cdot\frac{f(q_i,D)\cdot(k_1+1)}{f(q_i,D)+k_1\cdot\left(1-b+b\cdot\frac{|D|}{\text{avgdl}}\right)}

只作理解用:k1k_1 控制 saturation,bb 控制 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)。

⭐ Semantic search 步驟(slide 56)
  1. 將 text data chunk 成小塊。
  2. 每個 text chunk embed 成 vector。
  3. 將 query text 轉成 query vector。
  4. 用 query vector 搵最接近嘅 data vectors(k Nearest Neighbor search)。
  5. 結果 text chunks 就會同 query semantically similar。

Why not a keyword search? 有 keyword 唔代表 relevant;冇 keyword 亦唔代表唔 relevant。

⭐ Cosine similarity(slides 57–58)
Cosine similarity=x⋅y∣x∣∣y∣=cos⁡θ,Cosine distance=1−Cosine similarity\text{Cosine similarity}=\frac{x\cdot y}{|x||y|}=\cos\theta,\qquad \text{Cosine distance}=1-\text{Cosine similarity}

∣x∣|x| 係 vector xx 嘅 magnitude,θ\theta 係 xx 同 yy 之間嘅角度。Embedding model 通常 output unit vector(magnitude = 1),所以 cosine similarity 就等於 dot product。

自編例子:x=(1,2,2)x=(1,2,2),y=(2,0,1)y=(2,0,1)。x⋅y=2+0+2=4x\cdot y=2+0+2=4,∣x∣=3|x|=3,∣y∣=5|y|=\sqrt5,similarity =435≈0.596=\frac{4}{3\sqrt5}\approx0.596,distance ≈0.404\approx0.404。

Slide 58 列出 MongoDB 嘅 options:$similarityCosine、$similarityDotProduct、$similarityEuclidean。

13. kNN 計算:Brute force、IVF、HNSW(slides 59–62)

⭐ 三種方法比較(slides 59、62)
Brute forceIVF(Inverted File Index)HNSW(Hierarchical Navigable Small World)
Idea同每個 vector 比較先用 K-means 將 data 分 cluster,只搜尋 candidate clusters多層 graph,由 sparse 層逐步落到 dense 層
Complexity (average)O(n)O(n)O(n)O(\sqrt{n})O(lg⁡n)O(\lg n)
Worst caseO(n)O(n)O(n)O(n)O(n)O(n)
ResultsExactApproximate onlyApproximate only
Used byFAISSPinecone、Qdrant、Chroma、PostgreSQL(more popular)
AdvantagesUse 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。
⭐ HNSW search(slide 61)
  1. 由 top layer 開始。
  2. Loop:greedily hop 去最近嘅 neighbours,然後落去較 dense 嘅一層,發掘更近嘅 neighbours。
  3. 到 ground layer,refine closest neighbours 嘅 list,返回 top K。
💡 直覺理解

好似搭交通工具:先搭飛機(top layer,站少跳得遠)飛到附近城市,再轉火車,最後行路(ground layer)去到目的地。

自我測驗 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 有 O(1)O(1) 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 版本:N=4N=4,term tt 喺 1 份 document 出現,喺 dd 出現 3 次。求 TF-IDF(未 normalize)。

IDF=ln⁡4+11+1+1=ln⁡2.5+1≈1.9163\text{IDF}=\ln\frac{4+1}{1+1}+1=\ln2.5+1\approx1.9163,TF = 3,所以 TF-IDF ≈5.749\approx5.749。

Q11. 同上,改用 textbook 版本,假設 dd 共有 10 個 terms。

TF = 3/10 = 0.3;IDF=log⁡10(4/1)≈0.6021\text{IDF}=\log_{10}(4/1)\approx0.6021;TF-IDF ≈0.1806\approx0.1806。

Q12. BM25 解決咗 TF-IDF 嘅咩問題?

Term frequency saturation(TF 唔再線性上升)、improved length normalization(減少偏向長 documents),而且有 tuneable parameters。

Q13. 比較 IVF 同 HNSW。如果 RAM 好緊張,揀邊個?

IVF:O(n)O(\sqrt{n})、用較少 RAM、需要 K-means。HNSW:O(lg⁡n)O(\lg n)、較快、唔使 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 O(1)O(1)、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 = log⁡10(N/df)\log_{10}(N/\text{df});sklearn TF = count,IDF = ln⁡N+1df+1+1\ln\frac{N+1}{\text{df}+1}+1,再 L2 normalize 每個 document。
  • BM25:saturation、length normalization、tuneable;formula 唔使考。
  • Vector:chunk → embed → query vector → kNN。Cosine = x⋅y∣x∣∣y∣\frac{x\cdot y}{|x||y|},distance = 1 − similarity;unit vector 時 = dot product。
  • kNN:Brute O(n)O(n);IVF O(n)O(\sqrt{n})(K-means、省 RAM、FAISS);HNSW O(lg⁡n)O(\lg n)(多層、no re-training、更流行)。後兩者 worst case O(n)O(n),只係 approximate。