Mongo 2.4 Text命令/全文搜索使用mongo-ruby-driver

时间:2013-04-01 10:25:58

标签: ruby mongodb

我想对我的收藏品进行全文搜索。由于我使用的是mongo 2.4,我想用mongodb的text command

来做

在mongo的控制台中执行此操作的方法是(根据mongo的官方文档。)

db.collection.runCommand( "text", { search: <string> })

返回预期结果。

现在,我想在ruby / rails中实现相同的功能。我正在使用mongo gem version 1.8.4

根据他们的change log/history 支持新的MongoDB 2.4索引类型

但是如何在ruby上运行text command集合。

我经历了这个blog post。但它没有帮助

更新

我试过了,

  command = BSON::OrderedHash.new
  command['find'] = collection
  command['text'] = {'search' => 'string'}
  result = @db.command(command)

但它给出了

Database command 'find' failed: (ok: '0.0'; errmsg: 'no such cmd: find'; bad cmd: '{"find"=>"project", "text"=>{"search"=>"string"}}').

更新2:

php存在类似情况。我正在寻找ruby相同的东西。

3 个答案:

答案 0 :(得分:2)

你只需要在Ruby 1.8中使用BSON :: OrderedHash。如果您运行的是Ruby 1.9或更高版本,则可以使用以下语法在文本索引上创建/查询。

require 'mongo'
include Mongo

client = MongoClient.new
db = client['my_database']
coll = db['my_collection']

# create a text index
coll.ensure_index({:field_name => Mongo::TEXT})

# run a text query
db.command({:text => 'my_collection', :search => 'search string'})
db.command({:text => 'my_collection', :search => 'search string', :filter => {:foo => 'bar'}})

答案 1 :(得分:1)

我这里没有安装mongodb,但以下应该可以解决这个问题:

command = OrderedHash.new
command['text'] = <collectionname>
command['search'] = <string>
result = @db.command(command)

希望这有帮助。

答案 2 :(得分:1)

我用过,

  command = {}
  command["text"] = collection_name
  command["search"] = "search_string"
  result = @db.command(command)

看起来很有效。 我会等待其他答案。

相关问题