【数据库】Elasticsearch的操作
warning:
这篇文章距离上次修改已过452天,其中的内容可能已经有所变动。
Elasticsearch是一个基于Lucene库的搜索引擎,它提供了分布式多用户能力的全文搜索引擎,基于RESTful web接口。以下是一些基本的Elasticsearch操作和相应的Python代码示例。
- 创建Elasticsearch客户端:
from elasticsearch import Elasticsearch
es = Elasticsearch(["http://localhost:9200"])- 创建索引:
res = es.indices.create(index='test-index', body={'settings': {'number_of_shards': 1}})
print(res['acknowledged'])- 获取索引:
res = es.indices.get('test-index')
print(res)- 添加/更新文档:
doc = {
'author': 'test author',
'text': 'Sample document',
}
res = es.index(index='test-index', id=1, document=doc)
print(res['result'])- 获取文档:
res = es.get(index='test-index', id=1)
print(res['_source'])- 删除文档:
res = es.delete(index='test-index', id=1)
print(res['result'])- 搜索文档:
res = es.search(index='test-index', query={'match': {'text': 'sample'}})
print(res['hits']['hits'])- 删除索引:
res = es.indices.delete(index='test-index')
print(res['acknowledged'])这些操作涵盖了Elasticsearch的基本使用,包括索引的创建、获取、文档的添加、更新、获取和删除,以及搜索操作。在实际应用中,你可能需要处理更复杂的场景,如批量操作、多索引搜索、分页等,但基本的操作和原理是相似的。
评论已关闭