From 816c764713f9b42a2280866a07c326101c03543e Mon Sep 17 00:00:00 2001
From: Nick <nick@bywatersolutions.com>
Date: Tue, 22 Oct 2019 14:38:58 +0000
Subject: [PATCH] Bug 23875: Explicitly srt searches by score and provide
 local-number as tie breaker

To test:
 1 - Set search engine to ES
 2 - Search the catalog for "*"
 3 - Note results
 4 - Edit first result
 5 - Repeat search, results are reordered
 6 - Apply patch
 7 - Search for "*"
 8 - Highest biblionumbers are returned first
 9 - Edit first result, repeat search
10 - Order does not change
11 - Confirm sorting by author, title, etc passes the same trials
---
 .../Elasticsearch/QueryBuilder.pm             |  7 +++++++
 .../SearchEngine/Elasticsearch/QueryBuilder.t | 20 +++++++++++++------
 2 files changed, 21 insertions(+), 6 deletions(-)

diff --git a/Koha/SearchEngine/Elasticsearch/QueryBuilder.pm b/Koha/SearchEngine/Elasticsearch/QueryBuilder.pm
index f36264e423d..12962bb1635 100644
--- a/Koha/SearchEngine/Elasticsearch/QueryBuilder.pm
+++ b/Koha/SearchEngine/Elasticsearch/QueryBuilder.pm
@@ -223,6 +223,13 @@ sub build_query {
             push @{ $res->{sort} }, { $f => { order => $d } };
         }
     }
+    # If not sorting by anything explicitly search by score
+    if ( !defined $res->{sort} ) {
+        push @{ $res->{sort} }, { _score => { order => 'desc' } };
+    }
+
+    # Add a tie breaker in case of equally relevant records
+    push @{ $res->{sort} }, { 'local-number' => { order => 'desc' } };
 
     # See _convert_facets in Search.pm for how these get turned into
     # things that Koha can use.
diff --git a/t/db_dependent/Koha/SearchEngine/Elasticsearch/QueryBuilder.t b/t/db_dependent/Koha/SearchEngine/Elasticsearch/QueryBuilder.t
index a320b445c80..4928445c327 100755
--- a/t/db_dependent/Koha/SearchEngine/Elasticsearch/QueryBuilder.t
+++ b/t/db_dependent/Koha/SearchEngine/Elasticsearch/QueryBuilder.t
@@ -219,7 +219,7 @@ subtest 'build_authorities_query_compat() tests' => sub {
 };
 
 subtest 'build_query tests' => sub {
-    plan tests => 61;
+    plan tests => 62;
 
     my $qb;
 
@@ -237,15 +237,23 @@ subtest 'build_query tests' => sub {
     is_deeply(
         $query->{sort},
         [
-            {
-            'title__sort' => {
-                    'order' => 'asc'
-                }
-            }
+            { 'title__sort'  => { 'order' => 'asc' } },
+            { 'local-number' => { 'order' => 'desc' } }
         ],
         "sort parameter properly formed"
     );
 
+    $query = $qb->build_query('test', () );
+
+    is_deeply(
+        $query->{sort},
+        [
+            { '_score'       => { 'order' => 'desc' } },
+            { 'local-number' => { 'order' => 'desc' } }
+        ],
+        "sort parameter properly formed if no sort passed"
+    );
+
     t::lib::Mocks::mock_preference('FacetMaxCount','37');
     t::lib::Mocks::mock_preference('DisplayLibraryFacets','both');
     $query = $qb->build_query('test', %options);
-- 
2.39.5