Based on the python django
The source code
preparation
Install the library:
pip install django-haystack
pip install whoosh
pip install jieba
Copy the code
If the PIP installation times out, you can configure the PIP domestic source download as follows:
PIP install - http://mirrors.aliyun.com/pypi/simple/ - I trusted - host mirrors.aliyun.com < install libraries >Copy the code
pip install -i http://mirrors.aliyun.com/pypi/simple/ --trusted-host mirrors.aliyun.com django
Copy the code
If installing Django-Haystack fails, install SetupTools_scm first. Installing django – haystack.
pip install setuptools_scm
Copy the code
project
Create project demo:
# django-admin startProject < project name > django-admin startProject findCopy the code
Access demo terminal to create APP:
# python manage.py startApp <APP name > Python manage.py startApp searchshopCopy the code
INSTALLED_APPS configuration in settings.py injected just created APP(path: find/find/settings.py):
INSTALLED_APPS = [
...
'searchshop',
...
]
Copy the code
Add the model to the created APP
Models. Py file add the following (path: the find/searchshop/models. Py) :
class Shopp(models.Model):
shop_name = models.TextField(max_length=200)
shop_price = models.IntegerField(default=0)
shop_dsc = models.CharField(max_length=200)
Copy the code
Admin.py file registration model in app:
Add the admin.py file as follows (path: find/searchshop/admin.py):
from .models import Shopp
admin.site.register(Shopp)
Copy the code
Execute the command to make the model work (execute it once when modifying the model, so that the model can be synchronized!!) :
python manage.py makemigrations
python manage.py migrate
Copy the code
Create a background administrator account
Accessing background operable model data:
python manage.py createsuperuser
Copy the code
Run:
python manage.py runserver
Copy the code
Visit: HTTP: 127.0.0.1:8080 / admin login just set up the account, password to enter:
Site search
Configuration haystack
Inject haystack(path: find/find/settings.py) at the bottom of the INSTALLED_APPS configuration in settings.py:
INSTALLED_APPS = [
...
'haystack'
]
Copy the code
In the app, add search_indexes. Py (directory :find/searchshop/search_indexes.
From haystack import indexes from. Models import Shopp Class ArticlePostIndex(indexes.SearchIndex, indexes.Indexable): # document = True, This means that haystack and search engines will use the contents of this field as an index. # use_template=True Specifies that the instructions for creating an index file based on those fields in the table are placed in a file text = Def get_model(self): def get_model(self): def get_model(self): Def index_querySet (self, using=None): Return self.get_model().objects.all() return self.get_model().objects.all()Copy the code
Generate a search index
python manage.py rebuild_index
Copy the code
The project directory has the whoosh_index folder.
Modify the word divider
Copy a copy from pyrhon installation path (\Lib\site-packages\haystack\backends\whoosh_backend. Py) to app and rename it as whoosh_cn_backend (find/searchshop/whoosh_cn_backend.py) references at the top:
from jieba.analyse import ChineseAnalyzer
Copy the code
Find (Find StemmingAnalyzer) location:
schema_fields[field_class.index_fieldname] = TEXT(
stored=True,
analyzer=StemmingAnalyzer(),
field_boost=field_class.boost,
sortable=True,
)
Copy the code
Replacement:
schema_fields[field_class.index_fieldname] = TEXT(stored=True, analyzer=ChineseAnalyzer(),
field_boost=field_class.boost)
Copy the code
Add after the INSTALLED_APPS(path: find/find/settings.py) configuration:
HAYSTACK_CONNECTIONS = {'default': {# specify whoosh ENGINE (previously created whoosh_cn_backend) 'ENGINE': 'searchshop.whoosh_cn_backend.WhooshEngine', # 'ENGINE': Whoosh_backend.WhooshEngine', # whoosh_cn_backend is a file renamed from haystack whoosh_backend. Py to use jieba branch # index file PATH' PATH': Os.path. join(BASE_DIR, 'whooSH_index '),}} # = 'haystack. Signals. Very convenient HAYSTACK_SIGNAL_PROCESSOR RealtimeSignalProcessor'Copy the code
Add the templates
Create the Templates folder in your APP.
Add content retrieve content
Search -> indexes -> SearchShop (search + APP name); Add shopp_text.txt (APP name _text.txt) to path (find/searchshop\templates\search\indexes\searchshop) :
{{object.shop_name}}
{{object.shop_dsc}}
{{object.shop_price}}
Copy the code
Adding a Page Template
Create index.html under the Templates folder create folder (SearchShop) :
{% load highlight %} <! DOCTYPE HTML > < HTML lang="en"> <head> <meta charset="UTF-8"> <title> 标 签 </title> <style> sp.highlighted {color: red; } </style> </head> <body> <div class="search"> <form method="get" action="{% url 'shop:search' %}"> <input type="text" Name ="q" placeholder="a "> < form> </div> {% if shop_list and query %} <ul> {% for Question in shop_list %} <li> {% highlight question.object.shop_name with query %} {% highlight question.object.shop_price with query %} <span class="post-author"> <a> {% highlight question.object.shop_dsc with query %} </a></span> </li> {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %} </body> </html>Copy the code
Query: search terms (returned from the view layer for highlighting) shop_list: search results
The view layer
Directory: find/searchshop/views. Py
from django.shortcuts import render from django.http import HttpResponse #Create your views here. from .models import Shopp from haystack.forms import ModelSearchForm from haystack.query import EmptySearchQuerySet def index(request): shop_list = Shopp.objects.all() context = { 'query': '', 'shop_list': shop_list } return render(request, 'searchshop/index.html', context) def search(request, load_all=True, form_class=ModelSearchForm, searchqueryset=None): if request.GET.get('q'): form = form_class(request.GET, searchqueryset=searchqueryset, load_all=load_all) if form.is_valid(): query = form.cleaned_data['q'] results = form.search() context = { 'query': query, 'shop_list': results } return render(request, 'searchshop/index.html', Context) # results = form.search() return HttpResponse(request.get.GET ('q')) return HttpResponse(' query ')Copy the code
Configure the routing
Create urls.py in find/searchshop
Urlpatterns = [path('', views.index, name='index'), path('search', views.search, name='search'), # path(r'search/$', views.search, name='search') ]Copy the code
Modify urls.py(directory: find/find/urls.py)
from django.urls import path, include
urlpatterns = [
path('shop', include('searchshop.urls')),
path('admin/', admin.site.urls),
]
Copy the code
Run:
python manage.py runserver
Copy the code
test
http://127.0.0.1:8000/shopKey words: HuaweiKey words: red rice
Word segmentation is
Therefore, ‘redrice’ cannot be found at…..