0

I have some Rails models that are indexed in Elasticsearch (via Tire gem). I can index new documents and query the existing index.

What I can't seem to do is get ahold of the highlight attached to a record from within my Rails app. I can however see that highlight is returned in the json when I interact with Elasticsearch directly via curl.

When I try to access the highlight property of my record I get: 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

But if I use curl I can see the highlight is returned to 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" ]
      }
    } ]
  }
}

The search method in the model:

  ...
  def self.search(params)
    tire.search(load: true) do
      query { string params[:query], default_operator: "AND" } if params[:query].present?
      highlight :attachment
    end
  end
  ...
Meltemi
  • 37,979
  • 50
  • 195
  • 293

2 Answers2

3

Method highlight is inaccessible when you are using load: true option. This should be fixed in future versions of Tire.

edit: you can use each_with_hit method to access returned elasticsearch values now

For example:

results = Article.search 'One', :load => true
  results.each_with_hit do |result, hit|
  puts "#{result.title} (score: #{hit['_score']})"
end
vhyza
  • 1,030
  • 6
  • 9
  • Do you know when and how it will be fixed (accessing directly to `@response['hits']['hits']`)? Because I've not found in issues any info about it. – Dmitry Polushkin Apr 15 '13 at 08:15
0

You can find my answer right at this post Elasticsearch/Lucene highlight

My method works fine for me and wish you can get it work as well.

Community
  • 1
  • 1
fth
  • 2,478
  • 2
  • 30
  • 44