diff --git a/README.md b/README.md index a21cc24..2c13f1b 100644 --- a/README.md +++ b/README.md @@ -342,6 +342,32 @@ Advanced Product.search "2% Milk", facets: {store_id: {where: {in_stock: true}, limit: 10}} ``` +### Highlight [master - subject to change] + +Highlight the search query in the results. + +```ruby +bands = Band.search "cinema", fields: [:name], highlight: true +``` + +**Note:** The `fields` option is required. + +View the highlighted fields with: + +```ruby +bands.each_with_hit do |band, hit| + puts hit["highlight"]["name.analyzed"].first # "Two Door Cinema Club" +end +``` + +**Note:** A simpler interface coming before the next release. + +To change the tag, use: + +```ruby +Band.search "cinema", fields: [:name], highlight: {tag: ""} +``` + ### Similar Items Find similar items. diff --git a/lib/searchkick/reindex.rb b/lib/searchkick/reindex.rb index cd6c751..9fcb4c1 100644 --- a/lib/searchkick/reindex.rb +++ b/lib/searchkick/reindex.rb @@ -202,7 +202,9 @@ module Searchkick type: "multi_field", fields: { field => {type: "string", index: "not_analyzed"}, - "analyzed" => {type: "string", index: "analyzed"} + "analyzed" => {type: "string", index: "analyzed", term_vector: "with_positions_offsets"} + # term_vector for fast / correct highlighting + # http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-highlighting.html#_fast_vector_highlighter } } if autocomplete.include?(field) diff --git a/lib/searchkick/search.rb b/lib/searchkick/search.rb index aed8fa4..c7775f9 100644 --- a/lib/searchkick/search.rb +++ b/lib/searchkick/search.rb @@ -288,6 +288,17 @@ module Searchkick end end + # highlight + if options[:highlight] + payload[:highlight] = { + fields: Hash[ fields.map{|f| [f, {}] } ] + } + if options[:highlight].is_a?(Hash) and tag = options[:highlight][:tag] + payload[:highlight][:pre_tags] = [tag] + payload[:highlight][:post_tags] = [tag.to_s.gsub(/\A