在mongoid / mongo控制台中搜索不起作用

时间:2014-12-30 05:41:35

标签: ruby-on-rails mongodb activerecord mongoid mongodb-query

我的模型category中有一些字段tags包含大量text

以以下数据为例, 应该通过这些搜索关键字IronPigAcademic Data

找到它
{
    "_id" : "M0130AUSM561NNBR",
    "name" : "Pig Iron Production for United StatesMonthly, Not Seasonally Adjusted,  ",
    "categories" : [
        "Production of Commodities",
        "NBER Macrohistory Database",
        "Academic Data"
    ],
    "tags" : "[\"iron\", \"metals\", \"nber\", \"production\", \"monthly\", \"nation\", \"usa\", \"nsa\"]",
    "updated_at" : ISODate("2014-12-30T03:38:13.954Z"),
    "created_at" : ISODate("2014-12-30T03:38:13.954Z")
}

我尝试按Indicator.text_search("Pig")

进行查询

但我一无所获

irb(main):005:0> Indicator.text_search("Pig")
=> #<Mongoid::Contextual::TextSearch
  selector:   {}
  class:      Indicator
  search:     Pig
  filter:     {}
  project:    N/A
  limit:      N/A
  language:   default>

尝试使用Indicator.any_of({ :text => /.*Production.*/ })

进行搜索

我什么都没有。

=> #<Mongoid::Criteria
  selector: {"$or"=>[{"text"=>/.*Production.*/}]}
  options:  {}
  class:    Indicator
  embedded: false>

尝试在mongo控制台中搜索,仍然无效(结果中没有任何内容)

    > db.indicators.find({"title": /.*Production.*/})
    >

型号:Indicator.rb

class Indicator
  include Mongoid::Document
  include Mongoid::Timestamps
  include Mongoid::Attributes::Dynamic
  # include Mongoid::Search
  field :id, type: String
  field :name, type: String
  field :category, type: String
  field :tags, type: String
  # search_in :tags, :category
end

1 个答案:

答案 0 :(得分:0)

shell查询

db.indicators.find({ "title" : /.*Production.*/ })
根据您的示例文档,

找不到任何文档,因为没有title字段。是否定义了文本索引?

db.indicators.ensureIndex({ "name" : "text", "categories" : "text", "tags" : "text" })

此外,tags是一个类似于字符串数组的字符串 - 这是你想要的吗?或者你想要n个字符串数组?我认为你想要

"tags" : ["iron", "metals", "nber", "production", "monthly", "nation", "usa", "nsa"]

而不是

"tags" : "[\"iron\", \"metals\", \"nber\", \"production\", \"monthly\", \"nation\", \"usa\", \"nsa\"]"