diff --git a/librarian/views.py b/librarian/views.py index 4e673f60d5600e2c8c43a89931b7c76c2a2b6eb6..4e35d4b8f04e37a10bec1ec87ab9762f3e3d33de 100644 --- a/librarian/views.py +++ b/librarian/views.py @@ -10,7 +10,7 @@ from django_opensearch_dsl.search import Search from django_tables2 import RequestConfig from markdownify import markdownify as md import requests -import random +from opensearchpy import Q from librarian.forms import BookAddForm, CopyAddForm, AuthorAddForm, PublisherAddForm, LocationForm, ShelfForm, \ SectionForm, UserForm, ProfileForm @@ -583,8 +583,15 @@ def search_books(request): # Get query query = request.GET.get("q") + query_conditions = Q("bool", should=[ + Q("fuzzy", title=query), + Q("fuzzy", description=query), + Q("term", isbn10=query), + Q("term", isbn13=query), + ]) + # Search books - books = BookDocument.search().query("multi_match", query=query).to_queryset() + books = BookDocument.search().query(query_conditions).to_queryset() # Search results return render(request, "librarian/search_results.html", {"results": books, "query": query}) @@ -593,11 +600,44 @@ def search_books(request): @staff_member_required(login_url=LOGIN_URL) def search_all(request): # Get query - query = request.GET.get("q") + query = request.GET.get("q", "") - # Search books + # Search everything indexed srch = Search(index="*") - qur = srch.query("multi_match", query=query).execute() + + # Define fields to search for + fuzzy_search_fields = [ + "title", + "description", + 'name', + 'website', + 'first_name', + 'last_name', + ] + + term_fields = [ + 'username', + 'email', + ] + + if query.isdigit(): + # If the query is a number, search for ISBNs and years + term_fields += [ + 'published_year', + 'isbn10', + 'isbn13', + ] + + # Build the query from the fields + query_conditions = Q("bool", should=[ + *[Q("fuzzy", **{f: query}) for f in fuzzy_search_fields], + *[Q("term", **{f: query}) for f in term_fields], + ]) + + print(query_conditions) + + qur = srch.query(query_conditions).execute() + print(qur.to_dict()) # Get results results = [] @@ -787,6 +827,7 @@ def renew_loan(request, loan_id): :param request: The request object :param loan_id: The ID of the loan to renew """ + # Get the loan and due date loan = get_object_or_404(Loan, id=loan_id) due_start = loan.due diff --git a/requirements.txt b/requirements.txt index 3a3a744fb2a4779091b327e8ae15503f508c39e2..35fe7623a8b75d8f7015d461f20f0e7afb343d5a 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,7 +1,7 @@ Django~=5.0.3 django-countries~=7.5.1 Pillow~=10.3.0 -requests==2.31.0 +requests==2.32.3 django-gravatar2~=1.4.4 django-tables2~=2.6.0 djangorestframework~=3.15.0 @@ -11,5 +11,5 @@ markdownify==0.12.1 python-barcode~=0.15.1 markdown bleach[css] >=5.0.0 -django-opensearch-dsl~=0.6.2 +django-opensearch-dsl~=0.7.0 django-allauth[socialaccount]~=65.1.0 \ No newline at end of file