Catalog
Foreword
Installation and configuration
Full-text search basics
Search engine configuration
Index configuration
Search views and templates
Filters and sorting
Custom search logic
Application scenario
- Product Search in E-Commerce Website
-
Article Search for News Websites
-
User search for social networking sites
4.Document search for systems within the enterprise
Sum up
Foreword
Hello everyone, today we share a very useful Python library-django-haystack
Github address: https://github.com/django-haystack/django-haystack.
The Django Haystack library is a powerful tool for implementing full-text search functionality in Django projects. It integrates various search engines, such as Elasticsearch, Whoosh, etc., to provide developers with a flexible and efficient search solution. In this article, we’ll delve into the installation, configuration, and application of the Django Haystack library, as well as how to take advantage of its rich functionality to implement advanced full-text search capabilities.
Installation and configuration
First, see how to install and configure the Python Django Haystack library:
pip install django-haystack
Once installed, configure in the Django project’s settings. Py file:
INSTALLED_APPS = [
...
'haystack',
...
]
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.elasticsearch2_backend.Elasticsearch2SearchEngine',
'URL': 'http://localhost:9200/',
'INDEX_NAME': 'haystack',
},
}
This completes the installation and basic configuration of the Django Haystack library.
Full-text search basics
The basic principle of Django Haystack library to implement full-text search is to index and store the data into the search engine, and then make search queries through the search engine.
Here is a simple example of a data model:
from django.db import models
from haystack import indexes
class Book(models.Model):
title = models.CharField(max_length=255)
author = models.CharField(max_length=255)
content = models.TextField()
class BookIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
title = indexes.CharField(model_attr='title')
author = indexes.CharField(model_attr='author')
def get_model(self):
return Book
In the above example, a Book model and the corresponding BookIndex index are defined, and the index fields are defined using the template by using use \ _ template = True.
Search engine configuration
The Django Haystack library supports multiple search engines, such as Elasticsearch, Whoosh, and others. The appropriate search engine can be selected and configured according to the needs of the project.
The following is an example of a configuration using the Elasticsearch search engine:
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.elasticsearch2_backend.Elasticsearch2SearchEngine',
'URL': 'http://localhost:9200/',
'INDEX_NAME': 'haystack',
},
}
With this configuration, you can use Elastics Search as the back-end search engine to implement the full-text search function.
Index configuration
In the Django Haystack library, you can define and configure a search index to specify the fields and weights you want to search.
Here is an example of an index configuration:
class BookIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
title = indexes.CharField(model_attr='title')
author = indexes.CharField(model_attr='author')
def get_model(self):
return Book
def index_queryset(self, using=None):
return self.get_model().objects.all()
In this example, the text, title, and author fields are defined, and the text field is defined using the template with use \ _ template = True. Also, the index \ _ queryset method is implemented to specify the set of queries that need to be indexed.
Search views and templates
In the Django Haystack library, you can process search requests through views and display search results in templates.
Here is an example of a simple search view and template:
from django.shortcuts import render
from haystack.query import SearchQuerySet
def search(request):
query = request.GET.get('q', '')
results = SearchQuerySet().filter(text=query)
return render(request, 'search_results.html', {'results': results})
In the search results template search_results.html
, we can show the search results:
{% for result in results %}
<h3>{{ result.title }}</h3>
<p>{{ result.author }}</p>
<p>{{ result.object.content }}</p>
{% endfor %}
Filters and sorting
The Django Haystack library also supports applying filters and sorting rules in search results to optimize the search experience.
The following is an example of a filter and sort:
from haystack.query import SearchQuerySet
# Filter example
filtered_results = SearchQuerySet().filter(author='John Doe')
# Sorting example
sorted_results = SearchQuerySet().order_by('-pub_date')
Through such filtering and sorting operations, the search results can be accurately filtered and displayed in order.
Custom search logic
The Django Haystack library also allows developers to customize search logic and weighting to further optimize the accuracy and relevance of search results.
The following is an example of custom search logic:
from haystack.query import SearchQuerySet
from haystack.inputs import Exact
# Custom search logic example
custom_results = SearchQuerySet().filter(content=Exact('Python programming'))
With this custom search logic, you can search for specific criteria and get more accurate search results.
Application scenario
1. Product Search in E-Commerce Website
Description: E-commerce websites usually need to provide powerful product search functions, including keyword search, filters, sorting and other functions.
Sample code:
# Define search index
class ProductIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
title = indexes.CharField(model_attr='title')
category = indexes.CharField(model_attr='category__name')
def get_model(self):
return Product
“`python
# search view
class ProductSearchView(SearchView):
template_name = 'product_search.html'
queryset = Product.objects.filter(status='active')
“`
“`html
<!– product_search.html –>
{% for result in page.object_list %}
<h3>{{ result.object.title }}</h3>
Category: {{ result.object.category }}
{% empty %}
No results found.
{% endfor %}
<pre><code class="line-numbers">#### 2. Article Search for News Websites
Description: News websites need to provide fast and accurate article search function to help users find interesting news content.
Sample code:
“`shell
# Define search index
class ArticleIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
title = indexes.CharField(model_attr=’title’)
author = indexes.CharField(model_attr=’author__name’)
def get_model(self):
return Article
# search view
class ArticleSearchView(SearchView):
template_name = 'article_search.html'
queryset = Article.objects.filter(status='published')
<!-- article_search.html -->
{% for result in page.object_list %}
<h3>{{ result.object.title }}</h3>
Author: {{ result.object.author }}
{% empty %}
No results found.
{% endfor %}
3. User search for social networking sites
Description: Social networking sites need to provide user search capabilities that allow users to find people or organizations they are interested in.
Sample code:
# Define search index
class UserProfileIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
username = indexes.CharField(model_attr='user__username')
bio = indexes.CharField(model_attr='bio')
def get_model(self):
return UserProfile
# search view
class UserProfileSearchView(SearchView):
template_name = 'user_profile_search.html'
queryset = UserProfile.objects.all()
```
```html
<!-- user_profile_search.html -->
{% for result in page.object_list %}
<h3>{{ result.object.username }}</h3>
Bio: {{ result.object.bio }}
{% empty %}
No results found.
{% endfor %}
4.Document search for systems within the enterprise
Description: The internal system of the enterprise needs to provide a document search function to help employees quickly find and access enterprise documents.
Sample code:
# Define search index
class DocumentIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
title = indexes.CharField(model_attr='title')
category = indexes.CharField(model_attr='category__name')
def get_model(self):
return Document
# search view
class DocumentSearchView(SearchView):
template_name = 'document_search.html'
queryset = Document.objects.filter(status='published')
```
```html
<!-- document_search.html -->
{% for result in page.object_list %}
<h3>{{ result.object.title }}</h3>
Category: {{ result.object.category }}
{% empty %}
No results found.
{% endfor %}
Sum up
The Python Django Haystack library is a powerful full-text search engine for all types of projects, including e-commerce sites, news sites, social networking sites, and internal enterprise systems. Through simple configuration and flexible API, developers can easily implement efficient full-text search functions, including keyword search, filters, sorting and other functions. The library is compatible with different search engines (such as Elasticsearch, Whoosh, etc.), and provides rich search indexes and view classes, enabling developers to quickly build reliable search systems and improve user experience and data retrieval efficiency. All in all, the Python Django Haystack library provides developers with a powerful and flexible tool for implementing full-text search requirements for a variety of projects.
This article is reposted from https://blog.csdn.net/m0_67847535/article/details/137290035,If there is any infringement,Please contact to delete。
“`