diff --git a/README.md b/README.md index 4ef5e53..111f3bc 100644 --- a/README.md +++ b/README.md @@ -348,7 +348,7 @@ Advanced Product.search "2% Milk", facets: {store_id: {where: {in_stock: true}, limit: 10}} ``` -### Highlight [master - subject to change] +### Highlight [master] Highlight the search query in the results. @@ -361,13 +361,11 @@ bands = Band.search "cinema", fields: [:name], highlight: true View the highlighted fields with: ```ruby -bands.each_with_hit do |band, hit| - puts hit["highlight"]["name.analyzed"].first # "Two Door Cinema Club" +bands.with_details.each do |band, details| + puts details[:highlight][:name] # "Two Door Cinema Club" end ``` -**Note:** A simpler interface coming before the next release. - To change the tag, use: ```ruby diff --git a/lib/searchkick/results.rb b/lib/searchkick/results.rb index c1c0b7d..fdaca24 100644 --- a/lib/searchkick/results.rb +++ b/lib/searchkick/results.rb @@ -9,6 +9,16 @@ module Searchkick end end + def with_details + each_with_hit.map do |model, hit| + details = {} + if hit["highlight"] + details[:highlight] = Hash[ hit["highlight"].map{|k, v| [k.sub(/\.analyzed\z/, "").to_sym, v.first] } ] + end + [model, details] + end + end + # fixes deprecation warning def __find_records_by_ids(klass, ids) @options[:load] === true ? klass.find(ids) : klass.includes(@options[:load][:include]).find(ids) diff --git a/test/highlight_test.rb b/test/highlight_test.rb index 92a2506..04ae2ad 100644 --- a/test/highlight_test.rb +++ b/test/highlight_test.rb @@ -4,19 +4,19 @@ class TestHighlight < Minitest::Unit::TestCase def test_basic store_names ["Two Door Cinema Club"] - assert_equal "Two Door Cinema Club", Product.search("cinema", fields: [:name], highlight: true).each_with_hit.first[1]["highlight"]["name.analyzed"].first + assert_equal "Two Door Cinema Club", Product.search("cinema", fields: [:name], highlight: true).with_details.first[1][:highlight][:name] end def test_tag store_names ["Two Door Cinema Club"] - assert_equal "Two Door Cinema Club", Product.search("cinema", fields: [:name], highlight: {tag: ""}).each_with_hit.first[1]["highlight"]["name.analyzed"].first + assert_equal "Two Door Cinema Club", Product.search("cinema", fields: [:name], highlight: {tag: ""}).with_details.first[1][:highlight][:name] end def test_multiple_fields store [{name: "Two Door Cinema Club", color: "Cinema Orange"}] - highlight = Product.search("cinema", fields: [:name, :color], highlight: true).each_with_hit.first[1]["highlight"] - assert_equal "Two Door Cinema Club", highlight["name.analyzed"].first - assert_equal "Cinema Orange", highlight["color.analyzed"].first + highlight = Product.search("cinema", fields: [:name, :color], highlight: true).with_details.first[1][:highlight] + assert_equal "Two Door Cinema Club", highlight[:name] + assert_equal "Cinema Orange", highlight[:color] end end -- libgit2 0.21.0