#!/usr/bin/ruby require 'groonga' FILENAME = '/tmp/test.db' MAX_RECORDS = 2 begin db = Groonga::Database.open(FILENAME) rescue db = Groonga::Database.create(:path => FILENAME) end unless user_table = Groonga::Context.default['User'] user_table = Groonga::Hash.create( :name => 'User', :key_type => 'UInt32', # 主キーは数値! :persistent => true) end unless community_table = Groonga::Context.default['Community'] community_table = Groonga::Hash.create( :name => 'Community', :key_type => 'ShortText', :persistent => true) community_table.define_column('mtime', 'Time', {:persistent => true}) community_table.define_column('users', user_table, {:persistent => true, :type => :vector}) end user_table.truncate community_table.truncate communities = [['co1', 1263816091, [2, 3, 5, 6]], ['co4', 1263816090, [2, 3]], ['co9', 1263816089, [2]], ['co15', 1263816092, []], ] communities.each {|id, mtime, users| rec = community_table.add(id) rec['mtime'] = Time.at(mtime) rec['users'] = users.map{|u| user_table.add(u)} } # 主キーが2であるユーザが加入しているコミュニティを、mtimeが新しい順に2つ取得。つまり、'co1', 'co4'を取得 recs = community_table.select('users:@2') i = 0 recs.sort([{:key => 'mtime', :order => 'descending'}]).each {|r| rec = r.key puts "community: #{rec.key}" i += 1 break if i >= MAX_RECORDS }