2017-03-28

Tagging System Design

Tagging 也算是目前系統中常見的功能,實作上也被討論了不少,大致上分底下 3 種類型:
  1. Denormalized solution
    Pros:
    • 單一 table 易於直接人工閱讀資料與維護。
    Cons:
    • 所有 tag value 集中於一個 cell,需要保留一特殊字符作為分隔使用。
    • 查詢時將大量使用 LIKE,查詢條件字串組成受限;但效能上可能優於 JOIN [1]。
  2. Entity-Relation solution
    Pros:
    • 使用獨立的 table 專門紀錄 tag value 與 entity 對應的關係。
    • 個別 tag value 被拆分為獨立記錄,不需要保留特殊字符,也不會大量使用 LIKE 運算。
    Cons:
    • 必須嚴格確保每一個 entity id 與 tag value 組合只會存在一筆記錄;否則使用 HAVING-COUNT 查詢時會出現錯誤。
    • Tag 本身無法帶有其它屬性,例如:引用次數/日期、從屬關係、有效與否、與內部/顯示名稱等。
    • Tag 更名時需要更新大量資料。
  3. Intersection Table solution
    Pros:
    • 所有的 tag value 獨立一個 table 存放,易於統整 tag value 或更名。
    • Tag 本身被視為另一個獨立的 entity,可自由定義屬性。
Cascade Updates: 當使用 normalized solution 時,寫入時需要 cascade updates 往往是需特別注意的地方,但只要程式邏輯無誤,便不會產生 orphan relation/entity 的情形。

Tag vs. Category

  • Tag 是 many-to-many 的關係,category 是 one-to-many。
  • Tag 一般不實作階層式結構。階層式結構必須搭配 recursive search 才有效果,也就是以 parent tag 搜尋時,結果應包括與 child tag 關連的項目;但一般像 GMail 雖然表面上具備階層式的 label,實質上卻沒有 recursive search 的能力,屬於 一種 faux hierarchical tagging。

另外 [2] 提到 3 種常見的 tag 使用情境:(1) 使用 tag 搜尋;(2) 透過某一文件的 tags 尋找擁有類似 tags 的其他文章;(3) 透過一群 tags 搜尋其他相關 tags。

see also:
[1] Tags: Database schema
[2] In Lieu of the Promised Article on Tags and SQL

沒有留言: