首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用elasticsearch-dsl-py保持最新的Elasticsearch索引?

如何使用elasticsearch-dsl-py保持最新的Elasticsearch索引?
EN

Stack Overflow用户
提问于 2018-01-04 21:19:33
回答 1查看 1.8K关注 0票数 2

我开发了一个小的个人信息目录,我的客户通过Django管理界面访问和更新。这些信息必须是可搜索的,所以我建立了Django站点,以便将这些数据保存在搜索索引中。我最初使用Hay堆栈和Whoosh作为搜索索引,但最近我不得不离开这些工具,转而使用Elasticsearch 5。

以前,每当目录中的任何内容都被更新时,代码就会清除整个搜索索引并从头开始重建它。这个目录中只有几百个条目,所以这并不是完全不符合性能的。不幸的是,在Elasticsearch中尝试做同样的事情是非常不可靠的,因为我认为这是一种种族--在我的代码中是某种类型的条件。

下面是我编写的使用elasticsearch-py和elasticsearch-dsl的代码:

代码语言:javascript
复制
import elasticsearch
import time
from django.apps import apps
from django.conf import settings
from elasticsearch.helpers import bulk
from elasticsearch_dsl.connections import connections
from elasticsearch_dsl import DocType, Text, Search

# Create the default Elasticsearch connection using the host specified in settings.py.
elasticsearch_host = "{0}:{1}".format(
    settings.ELASTICSEARCH_HOST['HOST'], settings.ELASTICSEARCH_HOST['PORT']
)
elasticsearch_connection = connections.create_connection(hosts=[elasticsearch_host])


class DepartmentIndex(DocType):
    url = Text()
    name = Text()
    text = Text(analyzer='english')
    content_type = Text()

    class Meta:
        index = 'departmental_directory'


def refresh_index():
    # Erase the existing index.
    try:
        elasticsearch_connection.indices.delete(index=DepartmentIndex().meta.index)
    except elasticsearch.exceptions.NotFoundError:
        # If it doesn't exist, the job's already done.
        pass

    # Wait a few seconds to give enough time for Elasticsearch to accept that the 
    # DepartmentIndex is gone before we try to recreate it.
    time.sleep(3)

    # Rebuild the index from scratch.
    DepartmentIndex.init()
    Department = apps.get_model('departmental_directory', 'Department')
    bulk(
        client=elasticsearch_connection, 
        actions=(b.indexing() for b in Department.objects.all().iterator())
    )

我已经设置了Django信号,以便在保存refresh_index()时调用Department。但是由于这个错误,refresh_index()经常崩溃:

elasticsearch.exceptions.RequestError: TransportError(400, u'index_already_exists_exception', u'index [departmental_directory/uOQdBukEQBWvMZk83eByug] already exists')

这就是为什么我添加了那个time.sleep(3)调用。我假设在调用DepartmentIndex.init()时索引还没有完全删除,这导致了错误。

,我的猜测是,我一直在用完全错误的方式来做这件事。必须有一个更好的方法来使用elasticsearch -dsl来更新一个elasticsearch索引,但是我只是不知道它是什么,而且我还无法通过他们的文档找到它。

在google上搜索“从头开始重建elasticsearch索引”会为“如何重新索引elasticsearch数据”提供大量的结果,但这不是我想要的。我需要用新的,更最新的数据从我的应用程序的数据库中替换数据。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-01-05 14:43:50

也许这会有帮助:https://github.com/HonzaKral/es-django-example/blob/master/qa/models.py#L137-L146

无论哪种方法,您都希望有两个方法:批量将所有数据加载到新索引(data.py)中,或者使用上面提到的方法/或信号进行同步。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48103731

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档