BS-11837, add unit tests and optimize query speed