在Elasticsearch中进行增删改查操作,通常使用Elasticsearch的REST API。以下是使用Python的requests
库进行基本操作的示例代码:
import requests
from pprint import pprint
# 连接到Elasticsearch
es_url = 'http://localhost:9200'
# 创建索引
def create_index(index_name):
response = requests.put(f'{es_url}/{index_name}')
print(f"创建索引: {response.json()}")
# 删除索引
def delete_index(index_name):
response = requests.delete(f'{es_url}/{index_name}')
print(f"删除索引: {response.json()}")
# 添加文档
def add_document(index_name, document_id, document):
response = requests.post(f'{es_url}/{index_name}/_doc/{document_id}', json=document)
print(f"添加文档: {response.json()}")
# 获取文档
def get_document(index_name, document_id):
response = requests.get(f'{es_url}/{index_name}/_doc/{document_id}')
pprint(f"获取文档: {response.json()}")
# 更新文档
def update_document(index_name, document_id, document):
response = requests.post(f'{es_url}/{index_name}/_update/{document_id}', json=document)
print(f"更新文档: {response.json()}")
# 删除文档
def delete_document(index_name, document_id):
response = requests.delete(f'{es_url}/{index_name}/_doc/{document_id}')
print(f"删除文档: {response.json()}")
# 示例操作
index_name = 'example_index'
document_id = '1'
document = {
'name': 'John Doe',
'age': 30,
'about': 'I love to go rock climbing'
}
# 创建索引
create_index(index_name)
# 添加文档
add_document(index_name, document_id, document)
# 获取文档
get_document(index_name, document_id)
# 更新文档
document['age'] = 31
update_document(index_name, document_id, {'doc': document})
get_document(index_name, document_id)
# 删除文档
delete_document(index_name, document_id)
# 删除索引
delete_index(index_name)
确保Elasticsearch服务器运行中,并且在本地9200端口监听。上述代码中的create_index
, delete_index
, add_document
, get_document
, update_document
, 和 delete_document
函数分别用于创建、删除索引,添加、获取、更新和删除文档。