数据密集型应用系统设计 pdf_设计数据密集型应用(3):Storage and Retrieval

cecdb0fb7d564580da97d7474f828803.png

第三章主要介绍可持久化的数据索引——主流的可持久化数据索引有下面几种:

  1. Hash Index。
  2. LSM-Tree。
  3. B-Tree。
  4. B+Tree。书中没有提到 B+Tree,可能是因为它和 B-Tree 比较像。考虑到 B+Tree 作为世界上最流行的关系数据库 MySQL 的官方存储引擎 InnoDB 的索引结构,本文还是决定拿出来学习一下。

Hash Index

Hash Index 是一种相对简单的索引结构。几乎每一种程序设计语言都有提供内存数据结构 hash map/table 的标准库,比如 C++ 中的 std::unordered_map、Python 中的 dictionary、Golang 中的 map

简单的 Hash Index 可以在 hash map 的基础上实现将数据持久化:在内存中维护一个 hash map,保存 key -> <offset, size>,在磁盘上维护一个 append only 的文件用于持久化保存数据。

694c67c3bc2ad43475d5b48a3b7a6fd5.png

简单粗糙的 C++ 代码实现如下:

#include <assert.h>
#include <fcntl.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

#include <string>
#include <unordered_map>
#include <vector>

class HashIndex {
 public:
  HashIndex(const std::string& data_fname)
      : data_fname_(data_fname), data_fd_(-1) {}

  int Init() {
    data_fd_ = open(data_fname_.c_str(), O_CREAT | O_RDWR | O_APPEND, 0666);
    if (data_fd_ < 0) {
      fprintf(stderr, "open %s error %sn", data_fname_.c_str(),
              strerror(errno));
      return -1;
    }
    return 0;
  }

  int Get(const std::string& key, std::string* value) {
    auto itr = hash_.find(key);
    if (itr == hash_.end()) {
      return 1;
    }
    std::vector<char> buf(itr->second.size);
    ssize_t rsize =
        pread(data_fd_, &buf[0], itr->second.size, itr->second.offset);
    if (rsize != itr->second.size) {
      fprintf(stderr, "pread fd %d offset %lu size %u rsize %ld error %sn",
              data_fd_, itr->second.offset, itr->second.size, rsize,
              strerror(errno));
      return -1;
    }
    std::string tmp_key;
    DecodeData(buf.data(), tmp_key, *value);
    if (tmp_key != key)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值