【问题标题】:Mongo 2.4 Text Command/ full text search using mongo-ruby-driverMongo 2.4 文本命令/使用 mongo-ruby-driver 的全文搜索
【发布时间】:2013-04-01 10:25:58
【问题描述】:

我想对我的收藏进行全文搜索。由于我使用的是 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​​ 的等价物。

【问题讨论】:

    标签: ruby mongodb


    【解决方案1】:

    您只需要在 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'}})
    

    【讨论】:

      【解决方案2】:

      我用过,

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

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

      【讨论】:

        【解决方案3】:

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

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

        希望这会有所帮助。

        【讨论】:

        • 我以前试过这个。干活。它如何知道要搜索的集合。 command() 在 db 对象上。
        • 这很有用。 undefined method 'command' for #&lt;Mongo::Collection:0xa181910&gt;
        • @Mashit 对不起,我把事情搞砸了;最后我用对我有用的代码更新了答案。
        猜你喜欢
        • 2018-05-18
        • 1970-01-01
        • 2019-05-21
        • 2023-03-25
        • 2020-12-18
        • 2019-08-16
        • 2014-11-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多