Python 玩转 Elasticsearch的一些技巧与经验
from datetime import datetime
import elasticsearch
# 连接到Elasticsearch
es = elasticsearch.Elasticsearch(hosts=['localhost:9200'])
# 创建一个新的Elasticsearch文档
def create_es_doc(index_name, doc_id, doc_data):
doc = {
'doc': doc_data,
'_index': index_name,
'_id': doc_id,
'_source': doc_data
}
res = es.index(body=doc)
print(f"Document {doc_id} created: {res['result']}")
# 更新Elasticsearch文档
def update_es_doc(index_name, doc_id, doc_data):
doc = {
'doc': doc_data,
'_index': index_name,
'_id': doc_id
}
res = es.update(body=doc)
print(f"Document {doc_id} updated: {res['result']}")
# 获取Elasticsearch文档
def get_es_doc(index_name, doc_id):
res = es.get(index=index_name, id=doc_id)
print(f"Document {doc_id} retrieved: {res['_source']}")
# 删除Elasticsearch文档
def delete_es_doc(index_name, doc_id):
res = es.delete(index=index_name, id=doc_id)
print(f"Document {doc_id} deleted: {res['result']}")
# 创建一个新的Elasticsearch索引
def create_es_index(index_name):
res = es.indices.create(index=index_name, ignore=400)
print(f"Index {index_name} created: {res['acknowledged']}")
# 删除Elasticsearch索引
def delete_es_index(index_name):
res = es.indices.delete(index=index_name, ignore=[400, 404])
print(f"Index {index_name} deleted: {res['acknowledged']}")
# 使用示例
index_name = 'example_index'
doc_id = 'example_doc'
doc_data = {
'title': 'Python Elasticsearch Example',
'content': 'This is an example document for Elasticsearch',
'date': datetime.now()
}
create_es_index(index_name)
create_es_doc(index_name, doc_id, doc_data)
update_es_doc(index_name, doc_id, doc_data)
get_es_doc(index_name, doc_id)
delete_es_doc(index_name, doc_id)
delete_es_index(index_name)
这段代码展示了如何使用Python和elasticsearch
库来与Elasticsearch进行交互。代码中包含了创建索引、创建和更新文档、获取文档以及删除文档的基本操作,并提供了使用这些操作的示例。
评论已关闭