用 Python 优雅地玩转 Elasticsearch:实用技巧与最佳实践
from datetime import datetime
from elasticsearch import Elasticsearch
# 假设我们已经有了一个Elasticsearch实例
es = Elasticsearch("http://localhost:9200")
# 创建一个新的文档
def create_document(index_name, document_id, document):
es.index(index=index_name, id=document_id, document=document)
# 获取一个文档
def get_document(index_name, document_id):
return es.get(index=index_name, id=document_id)
# 更新一个文档
def update_document(index_name, document_id, document):
es.update(index=index_name, id=document_id, document=document)
# 删除一个文档
def delete_document(index_name, document_id):
es.delete(index=index_name, id=document_id)
# 查询文档
def search_documents(index_name, query):
return es.search(index=index_name, body=query)
# 示例使用
index_name = "example_index"
document_id = "1"
document = {
"title": "Python Elasticsearch",
"content": "Elasticsearch is a great tool for full-text search.",
"date": datetime.now()
}
# 创建文档
create_document(index_name, document_id, document)
# 获取文档
print(get_document(index_name, document_id))
# 更新文档
document["content"] += " You can easily play with Elasticsearch in Python."
update_document(index_name, document_id, document)
# 删除文档
# delete_document(index_name, document_id)
# 查询文档
query = {
"query": {
"match": {
"content": "play"
}
}
}
results = search_documents(index_name, query)
print(results)
这段代码提供了创建、获取、更新、删除文档以及执行基本搜索的函数。它展示了如何使用Elasticsearch Python API与Elasticsearch集群交互。代码简洁,注重实用性,可以作为初学者学习和使用Elasticsearch的示例。
评论已关闭