python| Django Elasticsearch DSL


 

Django Elasticsearch DSL 介紹

Django Elasticsearch DSL是一個軟件包,允許在elasticsearch中索引Django模型。它是作為Elasticsearch-dsl-py的封裝而構建的, 因此您可以使用elasticsearch-dsl-py團隊開發的所有功能。

您可以在https://django-elasticsearch-dsl.readthedocs.io上查看完整文

特性

  • 基於elasticsearch-dsl-py,因此您可以使用Search類進行查詢。

  • Django信號接收器處於保存和刪除狀態,以保持Elasticsearch同步。

  • 從Django模型字段中的Elasticsearch自動映射。

  • 復雜字段類型支持(ObjectField,NestedField)。

  • 使用並行索引快速建立索引。

  • Requirements

    • Django >= 1.11
    • Python 2.7, 3.5, 3.6, 3.7

Elasticsearch兼容性:該庫與5.x以后的所有Elasticsearch版本兼容,但是您必須使用匹配的主要版本:

  • 對於Elasticsearch 7.0及更高版本,請使用該庫的主要版本7(7.x.y)。

  • 對於Elasticsearch 6.0及更高版本,請使用該庫的主要版本6(6.x.y)。

  • 對於Elasticsearch 5.0和更高版本,請使用庫的主要版本0.5(0.5.x)。

    1
    2
    3
    4
    5
    6
    7
    8
    # Elasticsearch 7.x
    elasticsearch-dsl>=7.0.0,<8.0.0

    # Elasticsearch 6.x
    elasticsearch-dsl>=6.0.0,<7.0.0

    # Elasticsearch 5.x
    elasticsearch-dsl>=0.5.1,<6.0.0

快速開始

安裝和配置

安裝 django-elasticsearch-dsl

1
pip install django-elasticsearch-dsl

然后添加 django-elasticsearch-dsl 到 INSTALLED_APPS

1
2
3
INSTALLED_APPS = [
'django_elasticsearch_dsl',
]

必須在django settings 中定義 ELASTICSEARCH_DSL

1
2
3
4
5
ELASTICSEARCH_DSL={
'default': {
'hosts': 'localhost:9200'
},
}

然后將ELASTICSEARCH_DSL傳遞到elasticsearch-dsl-py.connections.configure(詳細參數請看)。

### 生命要被索引的模型表

model.py

1
2
3
4
5
class NcInfo(models.Model):
cluster = models.CharField(max_length=12, verbose_name='用戶名')
ip = models.GenericIPAddressField(verbose_name='IP地址')
desc = models.CharField(max_length=128, verbose_name='簡介')
instance_id = models.CharField(max_length=64, verbose_name='實例id')

要使該模型與Elasticsearch一起使用,請創建django_elasticsearch_dsl.Document的子類,在Document類中創建一個Index類以定義您的Elasticsearch索引,名稱,設置等,最后使用Registry.register_document裝飾器注冊該類。 它需要在您的應用目錄中的documents.py中定義Document類。

創建document.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
from django_elasticsearch_dsl import Document
from django_elasticsearch_dsl.registries import registry
from .models import NcInfo

@registry.register_document
class NcInfoDocument(Document):
class Index:
# es 索引名
name = 'ncinfo'
# 有關可用設置,請參閱Elasticsearch Indices API參考。
settings = {'number_of_shards': 1,
'number_of_replicas': 0}

class Django:
model = NcInfo # 與此文檔關聯的模型

# 要在Elasticsearch中建立索引的模型的字段
fields = [
'cluster',
'ip',
'instance_id',
]

# 保存模型時忽略彈性搜索的自動更新
# or deleted:
# ignore_signals = True

# 每次更新后都不要執行索引刷新(覆蓋全局設置):
# auto_refresh = False

# 對django查詢集進行分頁,該查詢集用於以指定大小填充索引
#(默認情況下,它使用數據庫驅動程序的默認設置)
# queryset_pagination = 5000

遷移

要創建並填充Elasticsearch索引和映射,請使用search_index命令:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM