首页
/ 技术文档:使用 activerecord-postgres-hstore

技术文档:使用 activerecord-postgres-hstore

2024-12-20 17:52:22作者:柏廷章Berta

1. 安装指南

系统要求

  • PostgreSQL 8.4+ 版本,并安装 contrib 扩展
  • Rails 3.1+ 版本

在 Ubuntu 系统上,安装 contrib 非常简单:

sudo apt-get install postgresql-contrib-9.1

在 Mac 系统上,有几个选项:

  • 使用 EnterpriseDB 提供的二进制包:下载 EnterpriseDB
  • 使用 Homebrew 安装 Postgres,它包括 contrib 包:brew install postgres
  • 使用 Postgres.app,这是一个完整的 PostgreSQL 安装包,包含标准 Mac 应用程序:下载 Postgres.app

Gem 安装

将以下内容添加到 Gemfile 中:

gem 'activerecord-postgres-hstore'

然后运行 bundler:

bundle install

接下来,创建一个迁移来为 PostgreSQL 数据库添加 hstore 支持:

rails g hstore:setup

运行迁移:

rake db:migrate

最后,您可以创建使用 hstore 类型的表:

rails g model Person name:string data:hstore
rake db:migrate

别忘了添加索引以提高查询性能:

CREATE INDEX people_gist_data ON people USING GIST(data);

CREATE INDEX people_gin_data ON people USING GIN(data);

2. 使用说明

模型使用

在模型中,您需要指定 hstore 字段使用 serialize 方法:

class Person < ActiveRecord::Base
  serialize :data, ActiveRecord::Coders::Hstore
end

这样,您就可以直接使用 hstore 字段作为哈希表进行操作。

数据库查询

本项目支持一些特殊查询语法来操作 hstore 字段:

  • 查找包含键 'foo' 的记录:
    Person.where("data ? 'foo'")
    
  • 查找 'foo' 键等于 'bar' 的记录:
    Person.where("data -> 'foo' = 'bar'")
    
  • 查找 'foo' 键不等于 'bar' 的记录:
    Person.where("data -> 'foo' <> 'bar'")
    
  • 查找 'foo' 键类似于 'bar' 的记录:
    Person.where("data -> 'foo' LIKE '%bar%'")
    

3. 项目 API 使用文档

此项目主要提供了对 PostgreSQL hstore 类型的支持,其 API 包括:

  • destroy_key: 删除记录中的键
  • destroy_key!: 删除键并保存记录
  • destroy_keys: 批量删除多个键
  • delete_key: 在多行中删除键
  • delete_keys: 在多行中批量删除多个键

4. 项目安装方式

请遵循以下步骤进行安装:

  1. 确保系统满足要求(PostgreSQL 8.4+ 和 Rails 3.1+)。
  2. activerecord-postgres-hstore 添加到 Gemfile。
  3. 运行 bundle install
  4. 创建并运行迁移以设置 hstore 支持。
  5. 创建使用 hstore 字段的表并添加索引。

以上就是关于 activerecord-postgres-hstore 的技术文档,希望对您使用该项目有所帮助。

登录后查看全文
热门项目推荐
相关项目推荐