使用Python脚本连接ES

1 投票
1 回答
8067 浏览
提问于 2025-04-18 17:58

我正在尝试连接并从一个ES引擎获取数据。

我使用了以下脚本:

from elasticsearch import Elasticsearch as ES

print "Setup connection..."
es=ES(['http://elasticsearch......com:9200/cuevents-2014.34,cuevents-2014.33/_search?pretty'])
print "Done!"

print "Count number of users..."
print es.count(index='cuevents-2014.34')

但是我得到的却是以下的错误信息。

Setup connection...
No handlers could be found for logger "elasticsearch"
Done!
Count number of users...
Traceback (most recent call last):
  File "/home/es.py", line 8, in <module>
    print es.count(index='cuevents-2014.34')
  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 622, in count
    params=params, body=body)
  File "/usr/local/lib/python2.7/dist-packages/elasticsearch/transport.py", line 284, 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 51, in perform_request
    raise ConnectionError('N/A', str(e), e)
elasticsearch.exceptions.ConnectionError: ConnectionError(('Connection aborted.', gaierror(-2, 'Name or service not known'))) caused by: ProtocolError(('Connection aborted.', gaierror(-2, 'Name or service not known')))

我想要连接并返回索引cuevents-2014.34中的文档数量。

1 个回答

2

好的,我仔细看了一下你的代码。Elasticsearch的构造函数需要指向根网址,也就是说,你不应该在网址中指定索引。

from elasticsearch import Elasticsearch as ES

print "Setup connection..."
es=ES(['http://elasticsearch......com:9200/'])
print "Done!"

print "Count number of users..."
print es.count(index='cuevents-2014.34')

可以参考这个链接:http://elasticsearch-py.readthedocs.org/en/master/api.html#elasticsearch

如果你想限制访问某些特定的索引,Elasticsearch本身并不提供访问控制。你可以通过在反向代理上进行网址重写来实现。

撰写回答