現(xiàn)在遇到一個性能問題,解決辦法就是給字段加索引,現(xiàn)在糾結(jié)的是字段組合索引還是單個索引查詢效率問題?
場景
現(xiàn)在查詢字段是parentId,key ,兩個字段同時查詢。
現(xiàn)在見索引的方案是
1 分別給 parentId,key添加索引
2 建一個組合索引 {parentId:1,key:1}這樣的方式:
這兩個查詢性能是不是差不多???
求證
In terms of index efficiency, the joint index is definitely more efficient. In many cases, if you use multiple fields to query, you should consider using the joint index.
But things are not completely absolute, and the overhead of indexing must also be taken into consideration.
Take your conditions as an example. Assuming that key
can uniquely determine a record, is it unnecessary to add parentId
? key
能夠唯一確定一條記錄,parentId
是不是就沒有必要加上了呢?
退一步,即使key
不能唯一確定一條,如果它能夠把結(jié)果集確定在一定的小范圍內(nèi),比如5條記錄,10條記錄,那parentId
Take a step back, even if key
cannot uniquely determine one, if it can determine the result set within a certain small range, such as 5 records or 10 records, then parentId
This condition is nothing more than scanning these 10 records again to find the appropriate record. Compared with the writing, storage, and memory overhead caused by adding it to the index, I may choose not to put it into the joint index at all.
The more records a condition can filter out, the better its "selectivity" is. Generally speaking, when we build an index, we should put the conditions with better selectivity at the front and the conditions with poor selectivity at the back. If it's bad enough, don't let it in.
This is actually a balance of time and space. Conditions put into the index save time (including CPU time, query time) and space (including storage space, memory space); conditions not put into the index cost time and save space. Most of the time we expect the former. When to choose the latter depends on your own assessment of the actual situation.