我有一个名为Example的集合,集合的所有字段都是动态的。我想进行常见的搜索。我不知道我该怎么做。例如,如果我搜索“hello”,它应该返回包含名称的集合的所有对象,而不管包含值的字段。
例:
{ id: 111234, desc: 'hello world' },
{ id: 545ttt, title: 'hello title' },
{ id: sfsd3, data: 'hello' }
如果我搜索你好,我的查询应该返回以上所有记录。我找到了一个mongoid_search gem,但是我找不到任何与动态字段搜索相关的东西。
提前致谢。
步骤1.在所有字段上创建text index。
db.collection.createIndex({ "$**": "text" },{ name: "TextIndex" })
步骤2.您可以使用$text作为以下查询对象进行简单的文本搜索:
{ $text : { $search: <your string> } }
您还可以创建一个“虚拟字段”,其中包含所有字符串字段的连接内容。然后将其与mongoid_search一起使用:
search_in :search_data
def search_data
self.attributes.select{|k,v| v.is_a?(String) }.values.join(' ')
end
这是如何工作的:mongoid_search
gem在每次保存之前运行search_data
方法,并使用它的输出来填充(隐藏)_keywords
字段。当您执行YourModel.full_text_search('hello')
之类的操作时,此字段将用于实际搜索。