Skip to content

Commit 33b7ee2

Browse files
committed
Improve configuration and error handling for elasticsearch tests
1 parent 9fa90ea commit 33b7ee2

File tree

2 files changed

+31
-17
lines changed

2 files changed

+31
-17
lines changed

app/controllers/better_together/search_controller.rb

Lines changed: 19 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -10,20 +10,25 @@ def search # rubocop:todo Metrics/AbcSize, Metrics/MethodLength
1010
suggestions = []
1111

1212
if @query.present?
13-
response = Elasticsearch::Model.search(build_search_query(@query), searchable_models)
14-
15-
search_results = response.records.to_a
16-
suggestions = response.response['suggest']['suggestions'].map do |s|
17-
s['options'].map do |o|
18-
o['text']
19-
end
20-
end.flatten
21-
22-
BetterTogether::Metrics::TrackSearchQueryJob.perform_later(
23-
@query,
24-
search_results.length,
25-
I18n.locale.to_s
26-
)
13+
begin
14+
response = Elasticsearch::Model.search(build_search_query(@query), searchable_models)
15+
16+
search_results = response.records.to_a
17+
18+
suggest_source = response.response.dig('suggest', 'suggestions') || []
19+
suggestions = suggest_source.flat_map { |s| s.fetch('options', []).map { |o| o['text'] } }
20+
21+
BetterTogether::Metrics::TrackSearchQueryJob.perform_later(
22+
@query,
23+
search_results.length,
24+
I18n.locale.to_s
25+
)
26+
rescue StandardError => e
27+
Rails.logger.warn("Search error: #{e.class}: #{e.message}")
28+
# Fall back to empty results so the page still renders
29+
search_results = []
30+
suggestions = []
31+
end
2732
end
2833

2934
# Use Kaminari for pagination
Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,17 @@
11
# frozen_string_literal: true
22

33
# config/initializers/elasticsearch.rb
4+
5+
# Prefer a single URL. If ELASTICSEARCH_URL is not set, build it from ES_HOST and ES_PORT.
6+
url = ENV['ELASTICSEARCH_URL'] || begin
7+
host = ENV.fetch('ES_HOST', 'http://localhost')
8+
port = ENV.fetch('ES_PORT', 9200)
9+
"#{host}:#{port}"
10+
end
11+
412
Elasticsearch::Model.client = Elasticsearch::Client.new(
5-
port: ENV.fetch('ES_PORT', 9200),
6-
host: ENV.fetch('ES_HOST', 'http://elasticsearch'),
7-
url: ENV.fetch('ELASTICSEARCH_URL', 'http://elasticsearch:9201')
13+
url: url,
14+
retry_on_failure: true,
15+
reload_connections: true,
16+
transport_options: { request: { timeout: 5, open_timeout: 2 } }
817
)

0 commit comments

Comments
 (0)