ruby-on-rails - Tire gem:如何访问Elasticsearch的 'highlight'属性?

标签 ruby-on-rails ruby-on-rails-3 elasticsearch tire

我有一些在Elasticsearch(通过Tire gem)中建立索引的Rails模型。我可以索引新文档并查询现有索引。

我似乎无法做的是从Rails应用程序中获取附加到记录的高亮。但是,当我直接通过highlight与Elasticsearch进行交互时,我可以看到jsont返回了curl

当我尝试访问记录的highlight属性时,我得到:undefined method 'highlight' for #<Report:0x007fe8afa54700>

# app/views/reports/index.html.haml
%h1 Listing reports
...
  - @reports.results.each do |report|
    %tr
      %td= report.title
      %td= raw report.highlight.attachment.first.to_s

但是,如果我使用curl,我可以看到highlight返回到Tire ...
$ curl -X GET "http://localhost:9200/testapp_development_reports/report/_search?load=true&pretty=true" -d '{query":{"query_string":{"query":"contains","default_operator":"AND"}},"highlight":{"fields":{"attachment":{}}}}'
{
  "took" : 1,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "failed" : 0
  },
  "hits" : {
    "total" : 2,
    "max_score" : 0.111475274,
    "hits" : [ {
      "_index" : "testapp_development_reports",
      "_type" : "report",
      "_id" : "1",
      "_score" : 0.111475274, "_source" : {"id":1,"title":"Sample Number One",...,"attachment":"JVBERi0xMJ1Ci... ...UlRU9GCg==\n"},
      "highlight" : {
        "attachment" : [ "\nThis <em>contains</em> one\n\nodd\n\n\n" ]
      }
    }, {
      "_index" : "testapp_development_reports",
      "_type" : "report",
      "_id" : "2",
      "_score" : 0.111475274, "_source" : {"id":2,"title":"Number two",...,"attachment":"JVBERi0xLKM3OA... ...olJVPRgo=\n"},
      "highlight" : {
        "attachment" : [ "\nThis <em>contains</em> two\n\neven\n\n\n" ]
      }
    } ]
  }
}

模型中的搜索方法:
  ...
  def self.search(params)
    tire.search(load: true) do
      query { string params[:query], default_operator: "AND" } if params[:query].present?
      highlight :attachment
    end
  end
  ...

最佳答案

使用highlight选项时,无法使用load: true方法。这应该在Tire的将来版本中修复。

编辑:您可以使用each_with_hit方法立即访问返回的elasticsearch值

例如:

results = Article.search 'One', :load => true
  results.each_with_hit do |result, hit|
  puts "#{result.title} (score: #{hit['_score']})"
end

关于ruby-on-rails - Tire gem:如何访问Elasticsearch的 'highlight'属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12379194/

相关文章:

ruby-on-rails - 删除 rails 迁移中的默认列

ruby-on-rails-3 - Rails - Devise - "Your password was set successfully. You are now signed in"- 如何禁用?

ruby-on-rails - RSpec with Ruby on Rails - 测试路由时参数数量错误(1 代表 0)

ruby-on-rails - 定制产品引擎

elasticsearch - kibana在发现选项卡中未显示黄色标记的Elasticsearch索引

ruby-on-rails - Searchkick word_start与嵌套字段匹配

javascript - 在 .erb 文件中内联 <% f.submit %> 样式

ruby-on-rails - 模型验证失败时,在Rails中的哪里显示注释 Controller ?

ruby-on-rails - Heroku 部署 : Discourse Assets precompile

indexing - ElasticSearch 索引 Confluence 页面