How does bitcoin find the block locator hashes in the leveldb database?

How does bitcoin find the block locator hashes in the leveldb database?

I am trying to understand how bitcoin core builds the list of block locator hashes needed for sendheaders and getheaders messages. I have looked on the wiki and I have seen that after the 10 most recent block hashes, it goes back exponentially until the genesis block.

So it seems that I have to get a block hash knowing its index in the blockchain. But how can bitcoin core find a block hash by its index? From my understanding leveldb lets you query data only by a key, and in this case the key is what I want.