尝试使用最近创建的弹性搜索索引时出现 TransportError(503, u'')

TransportError(503, u'') when trying to use a recently created elasticsearch index

我正在使用 Python API 创建 Elasticsearch 索引,如下所示:

from elasticsearch import Elasticsearch

es = Elasticsearch()

index_body = {"mappings": {".percolator": {"properties": {"message": {"type": "string", "analyzer": "english"}}}}}
# Creates the index if it doesn't exist
if not es.indices.exists('test'):
    es.indices.create(index='test', body=index_body)

print es.exists(index='test', id='1')

索引已成功创建,但是当我检查索引中是否存在文档时,它失败并出现以下错误:

Traceback (most recent call last):
  File "main.py", line 12, in <module>
    print es.exists(index='test', id='1')
  File "/usr/local/lib/python2.7/dist-packages/elasticsearch/client/utils.py", line 68, in _wrapped
    return func(*args, params=params, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/elasticsearch/client/__init__.py", line 282, in exists
    self.transport.perform_request('HEAD', _make_path(index, doc_type, id), params=params)
  File "/usr/local/lib/python2.7/dist-packages/elasticsearch/transport.py", line 307, in perform_request
    status, headers, data = connection.perform_request(method, url, params, body, ignore=ignore, timeout=timeout)
  File "/usr/local/lib/python2.7/dist-packages/elasticsearch/connection/http_urllib3.py", line 86, in perform_request
    self._raise_error(response.status, raw_data)
  File "/usr/local/lib/python2.7/dist-packages/elasticsearch/connection/base.py", line 102, in _raise_error
    raise HTTP_EXCEPTIONS.get(status_code, TransportError)(status_code, error_message, additional_info)
elasticsearch.exceptions.TransportError: TransportError(503, u'')

如果我第二次 运行 这个脚本,在索引已经创建的情况下它工作得很好。 有没有人知道可能出了什么问题?

创建新索引时,需要等到所有分片分配完毕。

我知道的最好的方法是:

  1. 获取<your_index>/_status
  2. 遍历所有 indices.<your_index>.shards 并验证 routing.state = STARTED 无处不在
  3. 转到 1),除非所有分片都已启动

Here's a (PHP) project 为单元测试做了这个:

protected function _waitForAllocation(Index $index)
{
    do {
        $settings = $index->getStatus()->get();
        $allocated = true;
        foreach ($settings['shards'] as $shard) {
            if ($shard[0]['routing']['state'] != 'STARTED') {
                $allocated = false;
            }
        }
    } while (!$allocated);
}

错误答案:

在继续之前,您必须给 ES 一些 space。 ES 接近实时,因此可能会有延迟。特别是当你 运行 你的代码几乎没有延迟时。

我认为您只需致电 _refresh endpoint 即可。

实际上我必须在我的单元测试中做同样的事情。它们执行得非常快,creating/pumping data/destroying 索引需要时间,所以在我的 setUp() 中,我在移交给相应的 test*() 方法之前调用了 _refresh。在一些我索引数据的测试中,我还必须进行 _refresh 调用。

通常,在正常操作期间你不需要调用它不应该。请记住,默认的 refresh_interval1s。如果您定期更新索引并希望反映亚秒级更新(我说的是 _search),那么这就是您需要开始的地方。

您可以像这样添加参数 wait_for_active_shards(默认为 1):

es.indices.create(index='test', body=index_body, wait_for_active_shards=all)

另请参阅:create(**kwargs)

的 elasticsearch-py 手册