使用“django-elasticsearch-dsl”将ElasticSearch连接到Django会在尝试创建/重建索引时导致ConnectionError

n6lpvg4x  于 2023-06-21  发布在  ElasticSearch
关注(0)|答案(2)|浏览(141)

我正在尝试调用一个运行在docker上的本地ES示例。我使用以下指令来设置我的ES示例:https://www.elastic.co/guide/en/elasticsearch/reference/current/docker.html#docker-cli-run-dev-mode
我可以在www.example.com上玩我的Kibana示例http://0.0.0.0:5601/app/dev_tools#/console。
现在我正在尝试使用Django模型定义一些示例文档,并通过库对它们进行索引;我在这里遵循指示:https://django-elasticsearch-dsl.readthedocs.io/en/latest/quickstart.html#install-and-configure
首先,我添加pip installed并将django_elasticsearch_dsl添加到INSTALLED_APPS
接下来,我在www.example.com中添加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

谢谢!

zqry0prt

zqry0prt1#

我以为是我的证书出了问题。
我需要添加一些额外的配置参数到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
    }
}

请参阅弹性文档中关于验证证书的这一部分。
如果您还没有设置证书来验证连接,只是需要快速启动和运行一些东西,您可以传递'verify_certs': False并将'ca_certs'设置为None

goqiplq2

goqiplq22#

如果你正在使用docker,这个回复(@cs95提到)会有所帮助。
您设置“主机”:'localhost:9200'但是你必须确保你的端口暴露在localhost上,如果你的python服务也在docker中运行,它必须和你的elasticsearch在同一个网络中,在这种情况下,你应该有服务名称,而不是localhost。

相关问题