current position:Home>Django: use of elastic search search system

Django: use of elastic search search system

2022-01-29 10:40:45 A nine barrel spring

Little knowledge , Great challenge ! This article is participating in 「 A programmer must have a little knowledge 」 Creative activities

  • Docker install ElasticSearch
  • Django:haystack Detailed tutorial of full-text retrieval

Use Docker install Elasticsearch And its expansion

  • establish Docker Mirror image
docker run -dit --name=myubuntu es
 Copy code 
  • install ElasticSearch

    • download
    wget https://download.elastic.co/elasticsearch/release/org/elasticsearch/distribution/tar/elasticsearch/2.4.4/elasticsearch-2.4.4.tar.gz
     Copy code 
    tar -xzvf elasticsearch-2.4.4.tar.gz -C /usr/local
    cd /usr/local/elasticsearch-2.4.4
     Copy code 
    • to update ES To configure
    cd conf
    
    vi elasticsearch.yml
     Copy code 
    bootstrap.memory_lock: true
    index.cache.field.max_size: 50000
    index.cache.field.expire: 30m
    index.cache.field.type: soft
    
    network.host: 0.0.0.0,127.0.0.1
    
    action.disable_delete_all_indices : true
     Copy code 
    • Installing the ES
    cd ../bin
    
    // Direct start ElasticSearch
    ./elasticsearch 
    
    // Or use the background mode to start 
    ./elasticsearch -d
     Copy code 

    Usually ES Will use 9200 and 9300 port , View port usage :

    netstat -anp|grep 9200
     Copy code 

    result:

    [email protected]*.25:/usr/local/elasticsearch-2.4.4/bin# netstat -anp|grep 9200
    tcp        0      0 192.168.*.58:9200       0.0.0.0:*               LISTEN      11135/java          
    tcp        0      0 127.0.0.1:9200          0.0.0.0:*               LISTEN      11135/java  
     Copy code 
    • Installation completed , Exit and view the list of running containers
    docker exit
    
    docker container ls --all
     Copy code 

Use Haystack docking Elasticsearch

  • We are Django You can use haystack To call Elasticsearch Search engine .
  • install
pip install drf-haystack
pip install elasticsearch==2.4.1
 Copy code 
  • Sign up for apps
INSTALLED_APPS = [
    ...
    'haystack',
    ...
]
 Copy code 
  • Modify the configuration file settings.py
# Haystack
HAYSTACK_CONNECTIONS = {
    'default': {
        'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine',
        'URL': 'http://127.0.0.1:9200/',  #  Here is elasticsearch Running servers ip Address , The port number is fixed to 9200
        'INDEX_NAME': 'XXXXXX',  #  Appoint elasticsearch The name of the index library created 
    },
}


#  When adding 、 modify 、 When deleting data , Automatically generate index 
HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'

 Copy code 

Use Elasticsearch Complete product search

  • Create index classes

By creating index classes , Well known search engines can retrieve data through the keywords of which fields .

from haystack import indexes

from goods.models import SKU


class SKUIndex(indexes.SearchIndex, indexes.Indexable):
    """ SKU Index data model classes  """
    text = indexes.CharField(document=True, use_template=True)

    def get_model(self):
        """ Return the indexed model class """
        return SKU

    def index_queryset(self, using=None):
        """ Return the data query set to be indexed """
        return self.get_model().objects.filter(is_launched=True)
 Copy code 
  • Generate the initial index manually

    • stay templates Create... In the directory text The template file used for the field

    Specific in templates/search/indexes/goods/sku_text.txt The document defines .

    {{ object.name }}
    {{ object.title }}
    {{ object.detail }}
     Copy code 
    • Manually generate initialization index
    python manage.py rebuild_index
     Copy code 
  • Define routes url

router = DefaultRouter()
router.register('skus/search', views.SKUSearchViewSet, base_name='skus_search')

urlpatterns += router.urls
 Copy code 
  • Create view
from drf_haystack.viewsets import HaystackViewSet

class SKUSearchViewSet(HaystackViewSet):
    """ SKU Search for  """
    index_models = [SKU]

    serializer_class = SKUIndexSerializer
    
 Copy code 
  • test

Use routing to enter the interface test

http://localhost:8000/skus/search/?text= Test product 
 Copy code 
  • bug Repair

haystack Yes Elasticsearch Version matching problem . It can be modified by REST framework Framework code , Add _get_count Just define the function .

File path pyenv In the environment  lib/python3.9/site-packages/rest_framework/pagination.py

def _get_count(queryset):
    """ Determine an object count, supporting either querysets or regular lists. """
    try:
        return queryset.count()
    except (AttributeError, TypeError):
        return len(queryset)
 Copy code 

copyright notice
author[A nine barrel spring],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201291040435004.html

Random recommended