【问题标题】:Python: elasticsearch.exceptions.NotFoundError: NotFoundError(404, '{"code":404,"message":"HTTP 404 Not Found"}')Python: elasticsearch.exceptions.NotFoundError: NotFoundError(404, '{"code":404,"message":"HTTP 404 Not Found"}')
【发布时间】:2020-10-30 09:19:40
【问题描述】:

我想在 Python 中使用 ElasticSearch 从给定的 URL(带前缀)获取数据。这是我的代码:

if __name__ == '__main__':
    username = "xxxx"
    password = "xxxx"
    url = "http://xxxx.xxx:80/xxxx/xxxx/" 
  
    _es = Elasticsearch([url], http_auth=(username, password))
    if _es.ping():
        print('Connect')
        print(_es)
        res = _es.search(index='index1', body={"query": {"match_all": {}}})
        print(res)
    else:
        print('It could not connect!')

其实我可以ping通_e,_es会是一个弹性对象:

另外,为了验证我的 URL、端口和前缀,我在 Postman 中检查了它,我可以正确获取 Json 格式的数据。但是当我在 Python 中运行代码时,我收到了以下错误:

Connect
<Elasticsearch([{'host': 'xxxx.xxx', 'url_prefix': 'xxxx/xxxx/', 'port': 80}])>
Traceback (most recent call last):
  File "/----.py", line 29, in <module>
    res = _es.search(index='index1', body={"query": {"match_all": {}}})
  File "/usr/local/lib/python3.5/dist-packages/elasticsearch/client/utils.py", line 139, in _wrapped
    return func(*args, params=params, headers=headers, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/elasticsearch/client/__init__.py", line 1484, in search
    body=body,
  File "/usr/local/lib/python3.5/dist-packages/elasticsearch/transport.py", line 352, in perform_request
    timeout=timeout,
  File "/usr/local/lib/python3.5/dist-packages/elasticsearch/connection/http_urllib3.py", line 256, in perform_request
    self._raise_error(response.status, raw_data)
  File "/usr/local/lib/python3.5/dist-packages/elasticsearch/connection/base.py", line 288, in _raise_error
    status_code, error_message, additional_info
elasticsearch.exceptions.NotFoundError: NotFoundError(404, '{"code":404,"message":"HTTP 404 Not Found"}')

有什么想法吗?

【问题讨论】:

    标签: python http elasticsearch search get


    【解决方案1】:

    请使用 try except 和 elasticsearch exceptions,如下:

    from elasticsearch import Elasticsearch, exceptions
    
    es = Elasticsearch()
    
    try:
        res2 = es.delete(index='my_index', id='not exist id')
    except exceptions.NotFoundError:
        pass
    

    【讨论】:

      【解决方案2】:

      您是否创建了要访问的索引? 尝试为文档编制索引(自动创建索引)或在搜索之前手动创建索引,否则您将收到 HTTP 404。

      _es.index(index="index-1", body={"key": "val"})
      print(_es.search(index="index-1", body={"query": {"match_all": {}}}))
      

      【讨论】:

        猜你喜欢
        • 2020-10-11
        • 1970-01-01
        • 2018-09-07
        • 1970-01-01
        • 2015-06-27
        • 1970-01-01
        • 1970-01-01
        • 2019-04-16
        • 1970-01-01
        相关资源
        最近更新 更多