Given several documents where the title of each document consists of a sequence of words as follows:
d1: “Set up your Apple ID for iCloud and iTunes” d2: “If your Apple ID has been locked” d3: “Apple Watch: Release date, price and specs” d4: “How to view iCloud Drive files on iPhone and iPad”
You would like to write a program to support the full text retrieval function: i.e. by giving one or more words as a query, your program has to return the IDs of the documents whose titles contain all the words in the query. For example, if the query is “Apple”, the program should output documents d1, d2, and d3. If the query is “iCloud” and “iPad”, the program should output document d4.
(a) (5 分) Please design a data structure to be the index structure such that the full text retrieval function can be performed efficiently. Please also show the constructed index structure for the given 4 documents.
(b) (5 分) Please show the pseudo codes and explain how to perform the full text retrieval function according to the designed data structure efficiently.
(a) inverted index:以 word 為 key,值是出現過這個 word 的 document ID 清單(posting list),清單依 ID 由小到大排好。key 放在 hash table(或 trie、balanced BST),用 word 一步查到它的 posting list
建法:逐篇文件把標題切成字(轉小寫),每個字把這篇文件的 ID 加到該字的 posting list 尾端(文件由小到大處理,所以清單自然排好)
| word | posting list | word | posting list | word | posting list |
|---|---|---|---|---|---|
| apple | d1, d2, d3 | icloud | d1, d4 | and | d1, d3, d4 |
| your | d1, d2 | id | d1, d2 | set, up, for, itunes | d1 |
| if, has, been, locked | d2 | watch, release, date, price, specs | d3 | how, to, view, drive, files, on, iphone, ipad | d4 |
(b) 查詢(字 \(w_1,\dots,w_k\)):
search(w1..wk):
for i = 1..k:
L[i] = index.lookup(lower(wi)) // hash 查詢,期望 O(1)
if L[i] is empty: return {} // 有一個字沒出現過,答案是空的
sort L by length ascending // 由最短的 list 開始
result = L[1]
for i = 2..k:
result = intersect(result, L[i]) // 兩個有序 list 的交集
if result is empty: return {}
return result
intersect(A, B): // A、B 已排序
p = 0; q = 0; R = []
while p < |A| and q < |B|:
if A[p] == B[q]: R.append(A[p]); p++; q++
else if A[p] < B[q]: p++
else: q++
return R
時間:查字 \(O(k)\);交集每次 \(O(|A|+|B|)\),總共 \(O\bigl(\sum_i|L_i|\bigr)\),與全部文件總字數無關(不必每次掃所有標題)
例:query iCloud、iPad:\(\{d1,d4\}\cap\{d4\}=\{d4\}\) ✓;query Apple:\(\{d1,d2,d3\}\) ✓。先從最短的 list 開始,結果最小,後面比對更少