批量写入数据到Elasticsearch
from elasticsearch import Elasticsearch
# 假设Elasticsearch运行在本地,端口是9200
es = Elasticsearch("http://localhost:9200")
# 准备数据,这里是一个包含字典的列表,每个字典代表一个文档
data = [
{
"author": "John Doe",
"text": "Elasticsearch is really good",
"timestamp": "2023-04-01T12:00:00"
},
{
"author": "Jane Smith",
"text": "Elasticsearch is great for logging",
"timestamp": "2023-04-01T12:00:00"
}
# ... 更多文档
]
# 指定索引名称
index_name = 'my_index'
# 批量写入数据到Elasticsearch
es.bulk(index=index_name, document_type='_doc', actions=(
{
"_index": index_name,
"_source": doc
} for doc in data
))
# 确认数据写入
response = es.search(index=index_name)
print("共搜索到文档数:", response['hits']['total']['value'])
这段代码首先建立了与Elasticsearch的连接,然后准备了要写入的数据。使用es.bulk()
方法将数据以批量的方式写入指定的索引。最后,通过一个搜索请求验证数据是否成功写入。
评论已关闭