From 653edc1fdcbd63f3a21e29971e5ad6357b193aed Mon Sep 17 00:00:00 2001 From: Jonas Winkler Date: Tue, 27 Oct 2020 17:07:13 +0100 Subject: [PATCH] added autocomplete to backend --- src/documents/index.py | 11 +++++++++++ src/documents/views.py | 27 +++++++++++++++++++++++++++ src/paperless/urls.py | 4 +++- 3 files changed, 41 insertions(+), 1 deletion(-) diff --git a/src/documents/index.py b/src/documents/index.py index 428d500fe..e3b71f905 100644 --- a/src/documents/index.py +++ b/src/documents/index.py @@ -75,6 +75,7 @@ def update_document(writer, doc): content=doc.content ) + @receiver(models.signals.post_save, sender=Document) def add_document_to_index(sender, instance, **kwargs): ix = open_index() @@ -102,3 +103,13 @@ def query_index(ix, querystr): 'score': r.score, 'title': r['title'] } for r in results] + + +def autocomplete(ix, term, limit=10): + with ix.reader() as reader: + terms = [] + for t in reader.expand_prefix("content", term.lower()): + terms.append(t) + if len(terms) >= limit: + break + return terms diff --git a/src/documents/views.py b/src/documents/views.py index b94f9aaeb..ee0fbe403 100755 --- a/src/documents/views.py +++ b/src/documents/views.py @@ -151,7 +151,11 @@ class LogViewSet(ReadOnlyModelViewSet): class SearchView(APIView): + + permission_classes = (IsAuthenticated,) + ix = index.open_index() + def get(self, request, format=None): if 'query' in request.query_params: query = request.query_params['query'] @@ -162,3 +166,26 @@ class SearchView(APIView): return Response(query_results) else: return Response([]) + + +class SearchAutoCompleteView(APIView): + + permission_classes = (IsAuthenticated,) + + ix = index.open_index() + + def get(self, request, format=None): + if 'term' in request.query_params: + term = request.query_params['term'] + else: + term = None + + if 'limit' in request.query_params: + limit = int(request.query_params['limit']) + else: + limit = 10 + + if term is not None: + return Response(index.autocomplete(self.ix, term, limit)) + else: + return Response([]) diff --git a/src/paperless/urls.py b/src/paperless/urls.py index 6bf010234..07c9a96ed 100755 --- a/src/paperless/urls.py +++ b/src/paperless/urls.py @@ -11,7 +11,8 @@ from documents.views import ( TagViewSet, DocumentTypeViewSet, SearchView, - IndexView + IndexView, + SearchAutoCompleteView ) api_router = DefaultRouter() @@ -26,6 +27,7 @@ urlpatterns = [ # API url(r"^api/auth/",include(('rest_framework.urls', 'rest_framework'), namespace="rest_framework")), + url(r"^api/search/autocomplete/", SearchAutoCompleteView.as_view(), name="autocomplete"), url(r"^api/search/", SearchView.as_view(), name="search"), url(r"^api/token/", views.obtain_auth_token), url(r"^api/", include((api_router.urls, 'drf'), namespace="drf")),