使用python连接elasticsearch
官方文档地址:https://www.elastic.co/guide/en/elasticsearch/client/python-api/current/overview.html
安装的时候注意版本,要与使用的elasticsearch兼容
The library is compatible with all Elasticsearch versions since 0.90.x but you have to use a matching major version:
For Elasticsearch 7.0 and later, use the major version 7 (7.x.y) of the library.
For Elasticsearch 6.0 and later, use the major version 6 (``6.x.y`) of the library.
For Elasticsearch 5.0 and later, use the major version 5 (5.x.y) of the library.
For Elasticsearch 2.0 and later, use the major version 2 (2.x.y) of the library, and so on.
The recommended way to set your requirements in your setup.py or requirements.txt is::
# Elasticsearch 7.x
elasticsearch>=7,<8
# Elasticsearch 6.x
elasticsearch>=6,<7
# Elasticsearch 5.x
elasticsearch>=5,<6
# Elasticsearch 2.x
elasticsearch>=2,<3
安装步骤地址:https://www.elastic.co/guide/en/elasticsearch/client/python-api/current/installation.html
$ python -m pip install elasticsearch
$ python -m pip install elasticsearch[async] # If your application uses async/await in Python you can install with the async extra
简单使用步骤:
>>> from datetime import datetime
>>> from elasticsearch import Elasticsearch
# By default we connect to localhost:9200
>>> es = Elasticsearch()
# Datetimes will be serialized...
>>> es.index(index="my-index-000001", doc_type="test-type", id=42, body={"any": "data", "timestamp": datetime.now()})
{'_id': '42', '_index': 'my-index-000001', '_type': 'test-type', '_version': 1, 'ok': True}
# ...but not deserialized
>>> es.get(index="my-index-000001", doc_type="test-type", id=42)['_source']
{'any': 'data', 'timestamp': '2013-05-12T19:45:31.804229'}
api地址:https://elasticsearch-py.readthedocs.io/en/master/api.html
api文档下载地址:https://readthedocs.org/projects/elasticsearch-py/downloads/
from datetime import datetime
from elasticsearch import Elasticsearch
es = Elasticsearch()
doc = {
'author': 'kimchy',
'text': 'Elasticsearch: cool. bonsai cool.',
'timestamp': datetime.now(),
}
res = es.index(index="test-index", id=1, body=doc)
print(res['result'])
res = es.get(index="test-index", id=1)
print(res['_source'])
es.indices.refresh(index="test-index")
res = es.search(index="test-index", body={"query": {"match_all": {}}})
print("Got %d Hits:" % res['hits']['total']['value'])
for hit in res['hits']['hits']:
print("%(timestamp)s %(author)s: %(text)s" % hit["_source"])
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!