前提
AWSのLambda、S3、Opensearchの使用を想定しています。
サンプルソースから、以下の動作は確認できた。
Amazon OpenSearch Service へのストリーミングデータをロードする - Amazon OpenSearch Service
https://docs.aws.amazon.com/ja_jp/opensearch-service/latest/developerguide/integrations.html
→「Amazon S3 からストリーミングデータをロードする」
1.S3へのcsvアップロードをトリガーとし
2.csvファイルをOpensearchへ転送する
という動作は確認できたのですが、
実際に利用するCSVはlogでなどではなく
以下のような単純なコンマ区切りのファイルになります。
正規表現ではなく、単純なコンマ区切りのcsvを取り込む方法を模索しております。
実現したいこと
-
正規表現取り込みをcsv読み取りへ変更したい。
-
ゴールは、取り込んだcsvデータをOpensearch上でグラフ化(視覚化)を実現したい
※フォーマットについて随時確認中。
csv中身例:
vmanage name, ip, host, session1, session2, sessionmax
vmanage-1, 1.1.1.1, testhost, 10, 9, 20
発生している問題・エラーメッセージ
ストリーム方式csv読み込み、配列に加えた後にdocumentへ入れる想定
エラーメッセージ: [ERROR] Runtime.UserCodesSyntaxError : Syntax error in module `sample` : unexpected indent (sample.py, line47) Trackback (most recent call last): File "/var/task/sample.py" Line 47 for row in csv.reader(textIo):
該当のソースコード
Python/Lambda
1 2import boto3 3import re 4import requests 5import csv 6import io 7import BytesIO 8from requests_aws4auth import AWS4Auth 9 10#配列 11vmanagename = [] 12ip = [] 13hostname = [] 14session1 = [] 15session2 = [] 16sessionmax = [] 17 18 19region = '' # e.g. us-west-1 20service = 'es' 21credentials = boto3.Session().get_credentials() 22awsauth = AWS4Auth(credentials.access_key, credentials.secret_key, region, service, session_token=credentials.token) 23 24host = '' # the OpenSearch Service domain, e.g. https://search-mydomain.us-west-1.es.amazonaws.com 25index = 'lambda-s3-index' 26type = '_doc' 27url = host + '/' + index + '/' + type 28 29headers = { "Content-Type": "application/json" } 30 31s3 = boto3.client('s3') 32 33# Lambda execution starts here 34def handler(event, context): 35 for record in event['Records']: 36 37 # Get the bucket name and key for the new file 38 bucket = record['s3']['bucket']['name'] 39 key = record['s3']['object']['key'] 40 41 # Get, read, and split the file into lines 42 obj = s3.get_object(Bucket=bucket, Key=key) 43 body = obj['Body'].read() 44 textIo = io.TextIOWrapper(io.BytesIO(body)) 45 46 # Match the regular expressions to each line and index the JSON 47 for row in lines csv.reader(textIo): 48 print(row) 49 vmanagename = row[0] 50 ip = row[1] 51 hostname = row[2] 52 session1 = row[3] 53 session2 = row[4] 54 sessionmax = row[5] 55 56 document = { "vmanagename ": vmanagename , "ip ": ip , "hostname ": hostname , "session1 ": session1 , "session2": session2, "sessionmax ": sessionmax } 57 r = requests.post(url, auth=awsauth, json=document, headers=headers)
試したこと
・csvのコンマ区切りを読み取り
・csvを辞書型にしたほうが良いか
・その他の方法について検討中
補足情報(FW/ツールのバージョンなど)
なし

回答1件
あなたの回答
tips
プレビュー