我正在使用 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'')
如果我第二次运行这个脚本,在索引已经创建的情况下它工作得很好。 有没有人知道可能出了什么问题?
最佳答案
创建新索引时,需要等到所有分片分配完毕。
我知道的最好的方法是:
- 获取
<your_index>/_status
- 遍历所有
indices.<your_index>.shards
并验证routing.state = STARTED
无处不在 - 转到 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 一些空间。 ES 接近实时,因此可能会有延迟。尤其是当您几乎没有延迟地按顺序运行代码时。
我想你只需要调用 _refresh
endpoint你被覆盖了。
在实践中,我必须在我的单元测试中做同样的事情。它们执行得非常快,创建/提取数据/销毁索引需要时间,因此在我的 setUp()
中我调用 _refresh
在移交给各自的test*()
之前方法。在一些测试中,我索引数据的地方,我也必须放置 _refresh
电话。
通常,在正常操作期间,您不需要调用它。请记住,默认 refresh_interval
是1s
.如果您定期更新索引并希望反射(reflect)亚秒级更新(我说的是例如 _search
),这就是您需要开始的地方。
关于python - 尝试使用最近创建的 Elasticsearch 索引时出现 TransportError(503, u''),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30082240/