0

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

我似乎无法从我的 Rails 应用程序中获取附加到记录的亮点。但是,当我直接highlight通过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返回到轮胎......

$ 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
  ...
4

2 回答 2

3

使用选项highlight时无法访问方法。load: true这应该在轮胎的未来版本中修复。

编辑:您现在可以使用each_with_hit方法访问返回的弹性搜索值

例如:

results = Article.search 'One', :load => true
  results.each_with_hit do |result, hit|
  puts "#{result.title} (score: #{hit['_score']})"
end
于 2012-09-12T08:46:31.730 回答
0

你可以在这篇文章Elasticsearch/Lucene highlight中找到我的答案

我的方法对我来说很好,希望你也能得到它。

于 2012-11-15T12:58:35.753 回答