我正在尝试调用在 docker 上运行的本地 ES 实例。我使用以下说明来设置我的 ES 实例: https://www.elastic.co/guide/en/elasticsearch/reference/current/getting-started.html https://www.elastic.co/guide/en/elasticsearch/reference/current/docker.html#docker-cli-run-dev-mode
我可以在 http://0.0.0.0:5601/app/dev_tools#/console 上使用我在 Kibana 上的实例.到这里一切正常。
现在我正在尝试使用 Django 模型定义一些示例文档并通过库对它们进行索引;我正在按照此处的说明进行操作:https://django-elasticsearch-dsl.readthedocs.io/en/latest/quickstart.html#install-and-configure
首先,我安装了 pip 并将 django_elasticsearch_dsl
添加到 INSTALLED_APPS
接下来,我在settings.py中添加:
ELASTICSEARCH_DSL = {
'default': {
'hosts': 'localhost:9200'
},
}
然后我创建一个示例模型和文档,如下所示:
# models.py
from django.db import models
class Car(models.Model):
name = models.CharField(max_length=30)
color = models.CharField(max_length=30)
description = models.TextField()
type = models.IntegerField(choices=[
(1, "Sedan"),
(2, "Truck"),
(4, "SUV"),
])
# documents.py
from django_elasticsearch_dsl import Document
from django_elasticsearch_dsl.registries import registry
from .models import Car
@registry.register_document
class CarDocument(Document):
class Index:
# Name of the Elasticsearch index
name = 'cars'
# See Elasticsearch Indices API reference for available settings
settings = {'number_of_shards': 1,
'number_of_replicas': 0}
class Django:
model = Car # The model associated with this Document
# The fields of the model you want to be indexed in Elasticsearch
fields = [
'name',
'color',
'description',
'type',
]
最后,运行 python3 manage.py search_index --rebuild
导致以下连接错误:
raise ConnectionError("N/A", str(e), e)
elasticsearch.exceptions.ConnectionError: ConnectionError(('Connection aborted.', RemoteDisconnected('Remote end closed connection without response'))) caused by: ProtocolError(('Connection aborted.', RemoteDisconnected('Remote end closed connection without response')))
我怀疑我的 ELASTICSEARCH_DSL
设置可能有问题,因为我没有为 https 指定任何配置,但文档没有说清楚。
我该如何解决这个问题?
Django version:
Django==4.0.1
django-elasticsearch-dsl==7.2.2
Python version: Python 3.9.10
谢谢!
最佳答案
我认为这是我的证书的问题。
我需要向 ELASTICSEARCH_DSL
变量添加一些额外的配置参数。添加这个可以解决问题:
from elasticsearch import RequestsHttpConnection
# Elasticsearch configuration in settings.py
ELASTICSEARCH_DSL = {
'default': {
'hosts': 'localhost:9200',
'use_ssl': True,
'http_auth': ('user', 'password'),
'ca_certs': '/path/to/cert.crt'
'connection_class': RequestsHttpConnection
}
}
参见 this section关于验证证书的弹性文档。
如果您还没有设置证书来验证连接并且只需要快速启动和运行,您可以传递 'verify_certs': False
并设置 'ca_certs'
到 None
。
关于python - 使用 "django-elasticsearch-dsl"将 ElasticSearch 连接到 Django 导致在尝试创建/重建索引时出现 ConnectionError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71281717/