]> git.ipfire.org Git - thirdparty/paperless-ngx.git/commitdiff
Enhancement: always place search term first in autocomplete results (#6142)
authorshamoon <4887959+shamoon@users.noreply.github.com>
Thu, 21 Mar 2024 19:03:17 +0000 (12:03 -0700)
committerGitHub <noreply@github.com>
Thu, 21 Mar 2024 19:03:17 +0000 (19:03 +0000)
src/documents/index.py
src/documents/tests/test_api_search.py

index b787c76355157864e7d6bece31d8bc734ec90113..388b994d8494cf509c69b487d62e603bfeda3575 100644 (file)
@@ -468,10 +468,14 @@ def autocomplete(
         termCounts = Counter()
         if results.has_matched_terms():
             for hit in results:
-                for _, term in hit.matched_terms():
-                    termCounts[term] += 1
+                for _, match in hit.matched_terms():
+                    termCounts[match] += 1
             terms = [t for t, _ in termCounts.most_common(limit)]
 
+        term_encoded = term.encode("UTF-8")
+        if term_encoded in terms:
+            terms.insert(0, terms.pop(terms.index(term_encoded)))
+
     return terms
 
 
index 0247d3293a43da0c25114a4cd6decc8122a23a3b..1b46f8e33033ba3917b18600df6d0c0d74f11d3b 100644 (file)
@@ -595,6 +595,28 @@ class TestDocumentSearchApi(DirectoriesMixin, APITestCase):
         self.assertEqual(response.status_code, status.HTTP_200_OK)
         self.assertEqual(response.data, [])
 
+    def test_search_autocomplete_search_term(self):
+        """
+        GIVEN:
+            - Search results for autocomplete include the exact search term
+        WHEN:
+            - API request for autocomplete
+        THEN:
+            - The search term is returned first in the autocomplete results
+        """
+        d1 = Document.objects.create(
+            title="doc1",
+            content="automobile automatic autobots automobile auto",
+            checksum="1",
+        )
+
+        with AsyncWriter(index.open_index()) as writer:
+            index.update_document(writer, d1)
+
+        response = self.client.get("/api/search/autocomplete/?term=auto")
+        self.assertEqual(response.status_code, status.HTTP_200_OK)
+        self.assertEqual(response.data[0], b"auto")
+
     @pytest.mark.skip(reason="Not implemented yet")
     def test_search_spelling_correction(self):
         with AsyncWriter(index.open_index()) as writer: