Elasticsearch--文档管理
在Elasticsearch中,可以使用RESTful API进行文档的添加、获取、更新和删除。以下是使用Python和requests
库进行文档管理的示例代码:
import requests
# 连接到Elasticsearch
es_url = 'http://localhost:9200'
index_name = 'my_index'
doc_type = 'my_type' # 在Elasticsearch 7.0+中已废弃,这里仅为示例
# 添加文档
def create_document(id, document):
url = f"{es_url}/{index_name}/{doc_type}/{id}"
response = requests.post(url, json=document)
print(response.json())
# 获取文档
def get_document(id):
url = f"{es_url}/{index_name}/{doc_type}/{id}"
response = requests.get(url)
print(response.json())
# 更新文档
def update_document(id, document):
url = f"{es_url}/{index_name}/{doc_type}/{id}"
response = requests.put(url, json=document)
print(response.json())
# 删除文档
def delete_document(id):
url = f"{es_url}/{index_name}/{doc_type}/{id}"
response = requests.delete(url)
print(response.json())
# 示例文档
document = {
"title": "Document 1",
"content": "This is the first document"
}
# 使用示例
create_document('1', document) # 添加文档
get_document('1') # 获取文档
# 更新文档
document['content'] = "Updated content"
update_document('1', document)
# 删除文档
delete_document('1')
确保Elasticsearch服务器正在运行,并且localhost:9200
可以连接到您的Elasticsearch实例。如果您的Elasticsearch设置不同,请相应地修改es_url
变量。
评论已关闭