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
     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,
    action.disable_delete_all_indices : true
     Copy code 
    • Installing the ES
    cd ../bin
    // Direct start 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 


    [email protected]*.25:/usr/local/elasticsearch-2.4.4/bin# netstat -anp|grep 9200
    tcp        0      0 192.168.*.58:9200*               LISTEN      11135/java          
    tcp        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
 Copy code 
  • Modify the configuration file
# Haystack
    'default': {
        'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine',
        'URL': '',  #  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.title }}
    {{ object.detail }}
     Copy code 
    • Manually generate initialization index
    python 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/

def _get_count(queryset):
    """ Determine an object count, supporting either querysets or regular lists. """
        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.

Random recommended