要将文档添加到AWS ElasticSearch索引中,您可以使用AWS Lambda和S3来实现。以下是一个代码示例,演示如何使用Lambda和S3将文档添加到ElasticSearch索引中:
import boto3
import requests
def lambda_handler(event, context):
# 获取S3桶名称和对象键
bucket_name = event['Records'][0]['s3']['bucket']['name']
object_key = event['Records'][0]['s3']['object']['key']
# 从S3获取文件内容
s3 = boto3.client('s3')
file = s3.get_object(Bucket=bucket_name, Key=object_key)
file_content = file['Body'].read().decode('utf-8')
# 将文件内容发送到ElasticSearch索引
index_document(file_content)
def index_document(file_content):
# ElasticSearch端点
es_endpoint = 'https://your-elasticsearch-endpoint'
# ElasticSearch索引名称
index_name = 'your-index-name'
# 发送POST请求将文档添加到索引中
response = requests.post(f'{es_endpoint}/{index_name}/_doc', json=file_content)
if response.status_code != 201:
print(f'Failed to index document: {response.text}')
else:
print('Document indexed successfully')
在上面的代码中,lambda_handler
函数被触发,当有新文件添加到S3时会被调用。它从S3中获取文件内容,然后调用index_document
函数将文件内容发送到ElasticSearch索引中。
将上述代码上传到Lambda函数,并配置触发器以在S3有新文件时调用Lambda函数。
在代码中,确保替换以下变量的值:
https://your-elasticsearch-endpoint
替换为您的ElasticSearch端点的URL。your-index-name
替换为您的ElasticSearch索引的名称。通过以上步骤,当有新文件添加到S3时,Lambda函数将被触发,并将文件内容添加到ElasticSearch索引中。