第二章 ElasticSearch 入门
warning:
这篇文章距离上次修改已过202天,其中的内容可能已经有所变动。
第二章 ElasticSearch 入门主要介绍了ElasticSearch的基本概念和安装,以及如何使用ElasticSearch的REST API进行基本操作。
以下是一个简单的Python代码示例,使用requests
库来与ElasticSearch进行交互:
import requests
from pprint import pprint
# 连接到ElasticSearch
es_url = 'http://localhost:9200/'
# 检查ElasticSearch服务状态
response = requests.get(es_url)
pprint(response.json())
# 创建一个新的索引
index_name = 'my_index'
create_index_response = requests.put(es_url + index_name)
pprint(create_index_response.json())
# 在索引中添加一个文档
document_id = '1'
document = {
'name': 'John Doe',
'age': 30,
'about': 'I love to go rock climbing'
}
add_document_response = requests.put(es_url + index_name + '/_doc/' + document_id, json=document)
pprint(add_document_response.json())
# 查询索引中的文档
search_response = requests.get(es_url + index_name + '/_search')
pprint(search_response.json())
# 删除索引
delete_index_response = requests.delete(es_url + index_name)
pprint(delete_index_response.json())
这段代码展示了如何使用Python和requests
库与ElasticSearch进行交互。它首先检查ElasticSearch服务状态,然后创建一个新的索引,在索引中添加一个文档,执行一个基本的搜索查询,并最后删除这个索引。这个过程涵盖了ElasticSearch的基本操作,对于初学者来说是一个很好的入门示例。
评论已关闭