From 40ed936f1bb081ec5f47a18df446d5f9cdd4dccc Mon Sep 17 00:00:00 2001
From: Dylan Griffith <dyl.griffith@gmail.com>
Date: Tue, 14 Jan 2020 11:41:40 +1100
Subject: [PATCH] Monkey patch ES gem to handle v7 API total count

This is due to the breaking change introduced in ES7
https://www.elastic.co/guide/en/elasticsearch/reference/current/breaking-changes-7.0.html#hits-total-now-object-search-response
. This can be handled by the v7 client gem but since our main target is
ES6 for now we will just monkey patch the gem with this fix. When we
remove support for ES6 or use the ES7 gem and default to supporting ES7
then we can remove it.
---
 config/initializers/elastic_client_setup.rb   |  1 +
 .../elasticsearch/model/response/results.rb   | 23 +++++++++++++++++++
 2 files changed, 24 insertions(+)
 create mode 100644 ee/lib/gem_extensions/elasticsearch/model/response/results.rb

diff --git a/config/initializers/elastic_client_setup.rb b/config/initializers/elastic_client_setup.rb
index f38b606b3a8c5..fce2c6782087b 100644
--- a/config/initializers/elastic_client_setup.rb
+++ b/config/initializers/elastic_client_setup.rb
@@ -10,6 +10,7 @@
   ### Monkey patches
 
   Elasticsearch::Model::Response::Records.prepend GemExtensions::Elasticsearch::Model::Response::Records
+  Elasticsearch::Model::Response::Results.prepend GemExtensions::Elasticsearch::Model::Response::Results
   Elasticsearch::Model::Adapter::Multiple::Records.prepend GemExtensions::Elasticsearch::Model::Adapter::Multiple::Records
   Elasticsearch::Model::Indexing::InstanceMethods.prepend GemExtensions::Elasticsearch::Model::Indexing::InstanceMethods
   Elasticsearch::Model::Adapter::ActiveRecord::Importing.prepend GemExtensions::Elasticsearch::Model::Adapter::ActiveRecord::Importing
diff --git a/ee/lib/gem_extensions/elasticsearch/model/response/results.rb b/ee/lib/gem_extensions/elasticsearch/model/response/results.rb
new file mode 100644
index 0000000000000..992a54b2abaaa
--- /dev/null
+++ b/ee/lib/gem_extensions/elasticsearch/model/response/results.rb
@@ -0,0 +1,23 @@
+# frozen_string_literal: true
+
+module GemExtensions
+  module Elasticsearch
+    module Model
+      module Response
+        module Results
+          # Handle ES7 API where total is returned as an object. This
+          # change is taken from the V7 gem
+          # https://github.com/elastic/elasticsearch-rails/commit/9c40f630e1b549f0b7889fe33dcd826b485af6fc
+          # and can be removed when we upgrade the gem to V7
+          def total
+            if response.response['hits']['total'].respond_to?(:keys)
+              response.response['hits']['total']['value']
+            else
+              response.response['hits']['total']
+            end
+          end
+        end
+      end
+    end
+  end
+end
-- 
GitLab