2013-04-01 42 views
0

我想對我的收藏進行全文搜索。由於我使用蒙戈2.4,我想用MongoDB的text commandMongo 2.4文本命令/使用mongo-ruby-driver的全文搜索

做到在蒙戈的控制檯的方式是(按蒙戈的官方文檔。)

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

它返回預期的結果去做。

現在,我想在ruby/rails中實現同樣的效果。我使用mongo gem version 1.8.4

按他們change log/history 有新的MongoDB 2.4索引類型

但支持我怎麼能與紅寶石集合運行text command。我經歷了blog post。但它did'nt幫助

更新:

我試過,

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。我正在尋找同樣的紅寶石的等價物。

回答

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'}}) 
+0

「你只需要使用BSON :: OrderedHash和Ruby 1.8」>>當然是.. –

1

我沒有工作MongoDB的安裝位置,但下面應該做的伎倆:

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

希望這有助於。

+0

我以前試過。 Dint工作。它如何知道要搜索的集合。命令()在db對象上。 –

+0

請參閱最新的答案。 – mudasobwa

+0

我更新了我的問題。謝謝。 –

1

我用,

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

看起來像它的工作原理。 雖然我會等待其他答案。