WIP: CS-5432

First draft for optimizing backend search.

Please merge takeit's sql_optimize branch first.
wrong identation