#include #include #include #include "leveldb/db.h" // 为字段创建索引 void TestCreateIndexOnField(leveldb::DB* db) { // 创建索引 leveldb::Status status = db->CreateIndexOnField("name"); assert(status.ok() && "Failed to create index on field 'name'"); std::cout << "Index on 'name' created successfully." << std::endl; } // 按照索引查询 void TestQueryByIndex(leveldb::DB* db) { // 插入一些数据 leveldb::WriteOptions write_options; leveldb::Status status; // 插入记录,格式为 "name:Customer#000000001|address:IVhzIApeRb|phone:25-989-741-2988" status = db->Put(write_options, "k_1", "name:Customer#000000001|address:IVhzIApeRb|phone:25-989-741-2988"); assert(status.ok() && "Failed to insert data for k_1"); status = db->Put(write_options, "k_2", "name:Customer#000000002|address:XSTf4,NCwDVaW|phone:23-768-687-3665"); assert(status.ok() && "Failed to insert data for k_2"); status = db->Put(write_options, "k_3", "name:Customer#000000003|address:MG9kdTD2WBHm|phone:11-719-748-3364"); assert(status.ok() && "Failed to insert data for k_3"); status = db->Put(write_options, "k_4", "name:Customer#000000004|address:XxVSJsLAGtn|phone:14-128-190-5944"); assert(status.ok() && "Failed to insert data for k_4"); status = db->Put(write_options, "k_5", "name:Customer#000000005|address:KvpyuHCplrB84Wg|phone:13-750-942-6364"); assert(status.ok() && "Failed to insert data for k_5"); std::cout << "Data inserted successfully." << std::endl; // 查询索引(我们假设查询字段值为 name:Customer#000000001) std::vector results = db->QueryByIndex("name:Customer#000000001"); assert(!results.empty() && "Query by index returned no results"); std::cout << "Query by index results for name=Customer#000000001: "; for (const auto& result : results) { std::cout << result << ", "; } std::cout << std::endl; // 验证查询结果 assert(results.size() == 1 && results[0] == "k_1"); std::cout << "Query by index test passed." << std::endl; } // 删除索引测试 void TestDeleteIndex(leveldb::DB* db) { // 删除索引 leveldb::Status status = db->DeleteIndex("name"); assert(status.ok() && "Failed to delete index on field 'name'"); std::cout << "Index on 'name' deleted successfully." << std::endl; // 尝试查询已删除的索引 std::vector results = db->QueryByIndex("name:Customer#000000001"); assert(results.empty() && "Query on deleted index should return no results"); std::cout << "Query after deleting index returned no results as expected." << std::endl; } int main() { // 配置数据库选项 leveldb::Options options; options.create_if_missing = true; // 打开数据库 leveldb::DB* db = nullptr; leveldb::Status status = leveldb::DB::Open(options, "./testdb", &db); assert(status.ok() && "Failed to open database"); // 测试创建索引 TestCreateIndexOnField(db); // 测试查询索引 TestQueryByIndex(db); // 测试删除索引 TestDeleteIndex(db); // 关闭数据库 delete db; std::cout << "All tests passed." << std::endl; return 0; }