Rails SQL DB 簡易效能判斷

紅寶鐵軌客
Join to follow...
Follow/Unfollow Writer: 紅寶鐵軌客
By following, you’ll receive notifications when this author publishes new articles.
Don't wait! Sign up to follow this writer.
WriterShelf is a privacy-oriented writing platform. Unleash the power of your voice. It's free!
Sign up. Join WriterShelf now! Already a member. Login to WriterShelf.
寫程式中、折磨中、享受中 ......
986   0  
·
2018/05/29
·
3 mins read


在 Rails 中可以很方便的知道 SQL 中的效能,就是使用 explain,舉個例子:

User.where(last_name: "xx").explain

就會有以下的輸出:

User Load (15.3ms)  SELECT "users".* FROM "users" WHERE "users"."last_name" = $1  [["last_name", "xx"]]
=> EXPLAIN for: SELECT "users".* FROM "users" WHERE "users"."locale_code" = $1 [["last_name", "xx"]]
                            QUERY PLAN
-------------------------------------------------------------------
 Seq Scan on user  (cost=0.00..17.25 rows=1 width=48)
   Filter: ((last_name)::text = 'x'::text)
(2 rows)

很方便,但是,這些數字到底是什麼呢?

我是用 postgreSQL,但是不管那一種 DB,都差不多:

  • 首先,在 Query Plan 那行字下,看到第一行是 Seq Scan.... 再來下一行是 Filter: ... 這就是指 SQL DB 的反向執行順序,越下面的越先執行,以這個例子來說,就是先過濾資料,再一筆一筆查,這在英文稱為 node list (串列),,Filter 是一個 node,Seq Scan 是另一個 node,你把它串起來就可以感覺到那種「串列」感覺了。
  • rows = 就這個查詢預計要查幾個 rows,也就是要查幾筆資料,越少越好!
  • (2 rows) :這是指這個表有幾行,當然是越少越好,不要跟前面的 rows = 搞錯了,很重要,但是它就只是告訴我們,這個 query 經 SQL 優化執行後,還要執行幾個(次)命令。
  • width = 資料寬度,單位是 byte,越寬,就要用越多記憶體儲存了。
  • cost: 指的是多少到多少個「電腦計算單元」,基本上,就是用來比大小用的,越小,就越快,用電腦的資源越小,至於,到底是多少 cpu cycle,沒人知道,也沒人想知道,就是一個比大小的單元。你如果要知道確實的數字,要到資料庫中執行 Explain Analyze,這樣,就會出相實際執行時間了。
  • Seq Scan 指的是查詢方式,常用的有以下:
    • Index Scan: 用索引表查
    • Seq Scan: 這就是一筆一筆順序查,最慢了
    • Filter: 過濾資料,這個例子就是。
    • Sort: 就是大到小,或小到大排列。

這個報告主要是用來設計資料庫的,用來比較加入 Index (索引)前後的效能差異,主要是看兩個值,一個是 cost 一個是 rows,都是越小越好,我覺得 Rails 用來做資料庫設計測試並不好用,但是也算還 ok 啦,要試的資料庫可以用 migration 建立後,試試,再 rollback/destory,再試試加上 index 後的差異,不算好用,但勉強,不知道有沒有其他更好用的測試法。

有一個很好玩的小插曲,我在試 explain 時,用了以下的 query:

User.find_by(id: 21).explain

結果,就一直 NoMethodError: undefined method `explain' for #<User:0x007ffca70b1a48>,嚇我一大跳,這什麼鬼,結果,就是自己忘了,find_by = where().first,first 當然沒有辦法 explain... 寫下來紀念自己的笨。


WriterShelf™ is a unique multiple pen name blogging and forum platform. Protect relationships and your privacy. Take your writing in new directions. ** Join WriterShelf**
WriterShelf™ is an open writing platform. The views, information and opinions in this article are those of the author.


Article info

This article is part of:
Categories:
Tags:
Total: 684 words


Share this article:
About the Author

很久以前就是個「寫程式的」,其實,什麼程式都不熟⋯⋯
就,這會一點點,那會一點點⋯⋯




Join the discussion now!
Don't wait! Sign up to join the discussion.
WriterShelf is a privacy-oriented writing platform. Unleash the power of your voice. It's free!
Sign up. Join WriterShelf now! Already a member. Login to WriterShelf.