File: searchable.rb

package info (click to toggle)
ruby-elasticsearch-rails 7.2.1-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 4,420 kB
  • sloc: ruby: 1,661; makefile: 4
file content (224 lines) | stat: -rw-r--r-- 6,961 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
# Licensed to Elasticsearch B.V. under one or more contributor
# license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright
# ownership. Elasticsearch B.V. licenses this file to you under
# the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.

module Searchable
  extend ActiveSupport::Concern

  included do
    include Elasticsearch::Model

    # Customize the index name
    #
    index_name [Rails.application.engine_name, Rails.env].join('_')

    # Set up index configuration and mapping
    #
    settings index: { number_of_shards: 1, number_of_replicas: 0 } do
      mapping do
        indexes :title, type: 'text' do
          indexes :title,     analyzer: 'snowball'
          indexes :tokenized, analyzer: 'simple'
        end

        indexes :content, type: 'text'  do
          indexes :content,   analyzer: 'snowball'
          indexes :tokenized, analyzer: 'simple'
        end

        indexes :published_on, type: 'date'

        indexes :authors do
          indexes :full_name, type: 'text' do
            indexes :full_name
            indexes :raw, type: 'keyword'
          end
        end

        indexes :categories, type: 'keyword'

        indexes :comments, type: 'nested' do
          indexes :body, analyzer: 'snowball'
          indexes :stars
          indexes :pick
          indexes :user, type: 'keyword'
          indexes :user_location, type: 'text' do
            indexes :user_location
            indexes :raw, type: 'keyword'
          end
        end
      end
    end

    # Set up callbacks for updating the index on model changes
    #
    after_commit lambda { Indexer.perform_async(:index,  self.class.to_s, self.id) }, on: :create
    after_commit lambda { Indexer.perform_async(:update, self.class.to_s, self.id) }, on: :update
    after_commit lambda { Indexer.perform_async(:delete, self.class.to_s, self.id) }, on: :destroy
    after_touch  lambda { Indexer.perform_async(:update, self.class.to_s, self.id) }

    # Customize the JSON serialization for Elasticsearch
    #
    def as_indexed_json(options={})
      hash = self.as_json(
        include: { authors:    { methods: [:full_name], only: [:full_name] },
                   comments:   { only: [:body, :stars, :pick, :user, :user_location] }
                 })
      hash['categories'] = self.categories.map(&:title)
      hash
    end

    # Search in title and content fields for `query`, include highlights in response
    #
    # @param query [String] The user query
    # @return [Elasticsearch::Model::Response::Response]
    #
    def self.search(query, options={})

      # Prefill and set the filters (top-level `post_filter` and aggregation `filter` elements)
      #
      __set_filters = lambda do |key, f|
        @search_definition[:post_filter][:bool] ||= {}
        @search_definition[:post_filter][:bool][:must] ||= []
        @search_definition[:post_filter][:bool][:must]  |= [f]

        @search_definition[:aggregations][key.to_sym][:filter][:bool][:must] ||= []
        @search_definition[:aggregations][key.to_sym][:filter][:bool][:must]  |= [f]
      end

      @search_definition = {
        query: {},

        highlight: {
          pre_tags: ['<em class="label label-highlight">'],
          post_tags: ['</em>'],
          fields: {
            title:    { number_of_fragments: 0 },
            abstract: { number_of_fragments: 0 },
            content:  { fragment_size: 50 }
          }
        },

        post_filter: { bool: { must: [ match_all: {} ] } },

        aggregations: {
          categories: {
            filter: { bool: { must: [ match_all: {} ] } },
            aggregations: { categories: { terms: { field: 'categories' } } }
          },
          authors: {
            filter: { bool: { must: [ match_all: {} ] } },
            aggregations: { authors: { terms: { field: 'authors.full_name.raw' } } }
          },
          published: {
            filter: { bool: { must: [ match_all: {} ] } },
            aggregations: {
              published: { date_histogram: { field: 'published_on', interval: 'week' } }
            }
          }
        }
      }

      unless query.blank?
        @search_definition[:query] = {
          bool: {
            should: [
              { multi_match: {
                  query: query,
                  fields: ['title^10', 'abstract^2', 'content'],
                  operator: 'and'
                }
              }
            ]
          }
        }
      else
        @search_definition[:query] = { match_all: {} }
        @search_definition[:sort]  = { published_on: 'desc' }
      end

      if options[:category]
        f = { term: { categories: options[:category] } }

        __set_filters.(:authors, f)
        __set_filters.(:published, f)
      end

      if options[:author]
        f = { term: { 'authors.full_name.raw' => options[:author] } }

        __set_filters.(:categories, f)
        __set_filters.(:published, f)
      end

      if options[:published_week]
        f = {
          range: {
            published_on: {
              gte: options[:published_week],
              lte: "#{options[:published_week]}||+1w"
            }
          }
        }

        __set_filters.(:categories, f)
        __set_filters.(:authors, f)
      end

      if query.present? && options[:comments]
        @search_definition[:query][:bool][:should] ||= []
        @search_definition[:query][:bool][:should] << {
          nested: {
            path: 'comments',
            query: {
              multi_match: {
                query: query,
                fields: ['comments.body'],
                operator: 'and'
              }
            }
          }
        }
        @search_definition[:highlight][:fields].update 'comments.body' => { fragment_size: 50 }
      end

      if options[:sort]
        @search_definition[:sort]  = { options[:sort] => 'desc' }
        @search_definition[:track_scores] = true
      end

      unless query.blank?
        @search_definition[:suggest] = {
          text: query,
          suggest_title: {
            term: {
              field: 'title.tokenized',
              suggest_mode: 'always'
            }
          },
          suggest_body: {
            term: {
              field: 'content.tokenized',
              suggest_mode: 'always'
            }
          }
        }
      end

      __elasticsearch__.search(@search_definition)
    end
  end
end