如何在Django中使用ElasticSearch
什么是Elasticsearch?
Elasticsearch是基于Lucene庫的搜索引擎。它提供了具有HTTP Web界面和無模式JSON文檔的分布式,多租戶功能的全文本搜索引擎。Elasticsearch是用Java開發(fā)的。
Elasticsearch的用途是什么?
Elasticsearch可以使我們快速,近乎實時地存儲,搜索和分析大量數(shù)據(jù),并在幾毫秒內給出答復。之所以能夠獲得快速的搜索響應,是因為它可以直接搜索索引,而不是直接搜索文本。
Elasticsearch-一些基本概念
索引—不同類型的文檔和文檔屬性的集合。例如,文檔集可以包含社交網(wǎng)絡應用程序的數(shù)據(jù)。
類型/映射-共享共享同一索引中存在的一組公共字段的文檔集合。例如,索引包含社交網(wǎng)絡應用程序的數(shù)據(jù);對于用戶個人資料數(shù)據(jù),可以有一種特定的類型,對于消息傳遞數(shù)據(jù),可以有另一種類型,對于注釋數(shù)據(jù),可以有另一種類型。
文檔-以特定方式以JSON格式定義的字段的集合。每個文檔都屬于一種類型,并且位于索引內。每個文檔都與唯一的標識符(稱為UID)相關聯(lián)。
字段-Elasticsearch字段可以包含多個相同類型的值(本質上是一個列表)。另一方面,在SQL中,一列可以恰好包含所述類型的一個值。
在Django中使用Elasticsearch
安裝和配置,安裝Django Elasticsearch DSL:
- $ pip install django-elasticsearch-dsl
然后將django_elasticsearch_dsl添加到INSTALLED_APPS
必須在django設置中定義ELASTICSEARCH_DSL。
例如:
- ELASTICSEARCH_DSL={
- 'default': {
- 'hosts': 'localhost:9200'
- },
- }
聲明要索引的數(shù)據(jù),然后創(chuàng)建model:
- # models.py
- class Category(models.Model):
- name = models.CharField(max_length=30)
- desc = models.CharField(max_length=100, blank=True)
- def __str__(self):
- return '%s' % (self.name)
- 要使該模型與Elasticsearch一起使用,請創(chuàng)建django_elasticsearch_dsl.Document的子類,在Document類中創(chuàng)建一個Index類以定義我們的Elasticsearch索引,名稱,設置等,最后使用Registry.register_document裝飾器注冊該類。它需要在應用目錄中的documents.py中定義Document類。
- # documents.py
- from django_elasticsearch_dsl import Document
- from django_elasticsearch_dsl.registries import registry
- from .models import Category
- @registry.register_document
- class CategoryDocument(Document):
- class Index:
- name = 'category'
- settings = {
- 'number_of_shards': 1,
- 'number_of_replicas': 0
- }
- class Django:
- model = Category
- fields = [
- 'name',
- 'desc',
- ]
- 填充:
- 要創(chuàng)建和填充Elasticsearch索引和映射,請使用search_index命令:
- $python manage.py search_index — rebuild
- 要獲得更多幫助,請使用命令:
- $ python manage.py search_index —help
- 現(xiàn)在,當執(zhí)行以下操作時:
- category = Category(
- name="Computer and Accessories",
- desc="abc desc"
- )
- category.save()
- 該對象也將保存在Elasticsearch中(使用信號處理程序)。
- 搜索:
- 要獲取elasticsearch-dsl-py搜索實例,請使用:
- s = CategoryDocument.search().filter("term", name="computer")
- # or
- s = CategoryDocument.search().query("match", description="abc")
- for hit in s:
- print(
- "Category name : {}, description {}".format(hit.name, hit.desc)
- )
- 要將彈性搜索結果轉換為真實的Django查詢集,請注意,這會花費一個SQL請求來檢索具有由Elasticsearch查詢返回的ID的模型實例。
- s = CategoryDocument.search().filter("term", name="computer")[:30]
- qs = s.to_queryset()
- # qs is just a django queryset and it is called with order_by to keep
- # the same order as the elasticsearch result.
- for cat in qs:
- print(cat.name)
- 完畢,如果有任何疑問,歡迎留言交流。
【編輯推薦】