【中间件】ElasticSearch简介和基本操作
warning:
这篇文章距离上次修改已过190天,其中的内容可能已经有所变动。
Elasticsearch 是一个基于 Apache Lucene 的开源搜索和分析引擎,设计用于云计算中,能够快速地处理大量数据。它提供了一个分布式多用户能力的全文搜索引擎,基于 RESTful web 接口。Elasticsearch 是 Elastic Stack 的核心组件,Elastic Stack 是一个用于数据搜索、分析和可视化的开源平台。
以下是一些基本操作的示例代码:
安装和运行 ElasticSearch
# 使用 Docker 安装 ElasticSearch
docker pull docker.elastic.co/elasticsearch/elasticsearch:7.10.0
docker run -d -p 9200:9200 -p 9300:9300 --name elasticsearch docker.elastic.co/elasticsearch/elasticsearch:7.10.0
使用 Python 的 Elasticsearch 客户端
首先安装 Elasticsearch 客户端库:
pip install elasticsearch
然后,您可以使用以下 Python 代码与 ElasticSearch 进行交互:
from elasticsearch import Elasticsearch
# 连接到 ElasticSearch 服务
es = Elasticsearch("http://localhost:9200")
# 创建一个索引
es.indices.create(index='my_index', ignore=400)
# 添加一个文档到索引
doc = {
'name': 'John Doe',
'age': 30,
'about': 'I love to go rock climbing'
}
res = es.index(index="my_index", id=1, document=doc)
# 获取一个文档
res = es.get(index="my_index", id=1)
print(res['_source'])
# 搜索文档
res = es.search(index="my_index", query={'match': {'name': 'John'}})
print("Total hits", res['hits']['total']['value'])
for hit in res['hits']['hits']:
print(hit)
# 更新一个文档
doc = {
'name': 'Jane Doe',
'age': 35,
'about': 'I love to collect rock albums'
}
res = es.update(index="my_index", id=1, document=doc)
# 删除索引
es.indices.delete(index='my_index', ignore=[400, 404])
这些代码片段展示了如何使用 Python 客户端与 ElasticSearch 进行基本的索引操作,包括创建、获取、搜索、更新和删除。
评论已关闭