-
Notifications
You must be signed in to change notification settings - Fork 0
/
DataReorganized.py
228 lines (181 loc) · 8.88 KB
/
DataReorganized.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
import time
import os
import datetime
from hdfs.ext.dataframe import read_dataframe, write_dataframe
from hdfs import Config
import json
import pandas as pd
import pandasql as pdsql
from pyspark.sql import SQLContext, SparkSession
from pyspark.sql.functions import lit
from pyspark.sql.types import *
from pymongo import MongoClient
from Constant import Constant
class DataReorganized:
def __init__(self, snode, mnode, port):
self.mongoClient = MongoClient(mnode, port)
self.db = self.mongoClient.indexes
self.hdfsClient = Config().get_client('dev')
self.spark = SparkSession.builder.appName("Spark with secondary indexes").getOrCreate()
self.customSchema = StructType([
StructField("_id", IntegerType(), True),
StructField("meterid", IntegerType(), True),
StructField("measurement", DoubleType(), True),
StructField("date", TimestampType(), True),
StructField("obs", StringType(), True)])
self.sqlContext = SQLContext(self.spark)
self.MONGO_METERDATA_COLLECTION_DIR = "mongodb://" + mnode + ":27017/indexes.meterdata"
self.HDFS_DIR = "hdfs://"+snode+":8020/user/meterdata"
def reorganizeByTimestamp(self, filenames, hdfsClientDir):
# filenames = ['file0.csv','file1.csv','file2.csv','file3.csv','file4.csv','file5.csv','file6.csv','file7.csv','file8.csv','file9.csv']
MONGO_METERDATA_COLLECTION_DIR = self.MONGO_METERDATA_COLLECTION_DIR
HOURS_PER_FILE = 8760 * 3600
MIN_TIMESTAMP = 1356998400 #2013-01-01 00:00:00
TIMESTAMPS_PER_FILE = int(HOURS_PER_FILE/len(filenames))
hdfsClient = self.hdfsClient
sqlContext = self.sqlContext
customSchema = self.customSchema
hdfsFiles = ""
filesToDelete = filenames
for f in filenames:
hdfsFiles += self.HDFS_DIR + "/" + f + ","
dataAfterReorganized = [None]*len(filenames)
df = sqlContext.read.format("org.apache.spark.csv").option("header", "false").schema(customSchema).csv(hdfsFiles[:len(hdfsFiles) - 1].split(','))
df.createOrReplaceTempView("data")
dataOrderByDate = sqlContext.sql("SELECT _id, meterid, measurement, date, obs FROM data ORDER BY date").cache()
filenames = appendTimestampPrefix(filenames)
for i in range(0, len(filenames)):
self.db.histogram.remove({"name": filesToDelete[i]})
self.db.meterdata.remove({"fname": filesToDelete[i]})
dataAfterReorganized[i] = dataOrderByDate.filter(dataOrderByDate.date >= datetime.datetime.fromtimestamp(MIN_TIMESTAMP + TIMESTAMPS_PER_FILE*i)).filter(dataOrderByDate.date < datetime.datetime.fromtimestamp(MIN_TIMESTAMP + TIMESTAMPS_PER_FILE*(i + 1)))
dataAfterReorganized[i].repartition(1).write.mode("append").csv(self.HDFS_DIR)
# self.createHistogramByPandas(filenames[i], dataAfterReorganized[i])
self.createHistogramBySpark(filenames[i], dataAfterReorganized[i])
files = hdfsClient.list(hdfsClientDir)
for f in files:
if "part-00" in f:
hdfsClient.rename(hdfsClientDir+f,hdfsClientDir+filenames[i])
dataAfterReorganized[i].drop('obs').drop('date').withColumn('fname', lit(filenames[i])).write.format("com.mongodb.spark.sql.DefaultSource")\
.option("spark.mongodb.output.uri", MONGO_METERDATA_COLLECTION_DIR)\
.mode("append")\
.save()
self.deleteHDFSFiles(filesToDelete, hdfsClientDir)
def reorganizeByMeasurement(self, filenames, hdfsClientDir):
MONGO_METERDATA_COLLECTION_DIR = self.MONGO_METERDATA_COLLECTION_DIR
HOURS_PER_FILE = 8760 * 3600
hdfsClient = self.hdfsClient
sqlContext = self.sqlContext
customSchema = self.customSchema
hdfsFiles = ""
for f in filenames:
hdfsFiles += self.HDFS_DIR + "/" + f + ","
dataAfterReorganized = [None]*len(filenames)
filesToDelete = filenames
filenames = appendMeasurementPrefix(filenames)
df = sqlContext.read.format("org.apache.spark.csv").option("header", "false").schema(customSchema).csv(hdfsFiles[:len(hdfsFiles) - 1].split(','))
df.createOrReplaceTempView("data")
dataOrderByMeasurement = sqlContext.sql("SELECT row_number() over (order by measurement) as rank ,_id, meterid, measurement, date, obs FROM data").cache()
for i in range(0, len(filenames)):
self.db.histogram.remove({"name": filesToDelete[i]})
self.db.meterdata.remove({"fname": filesToDelete[i]})
dataAfterReorganized[i] = dataOrderByMeasurement.filter(dataOrderByMeasurement.rank >= i * 43800).filter(dataOrderByMeasurement.rank < 1 + (i + 1) * 43800).drop('rank')
dataAfterReorganized[i].repartition(1).write.mode("append").csv(self.HDFS_DIR)
# self.createHistogramByPandas(filenames[i], dataAfterReorganized[i])
self.createHistogramBySpark(filenames[i], dataAfterReorganized[i])
files = hdfsClient.list(hdfsClientDir)
for f in files:
if "part-00" in f:
hdfsClient.rename(hdfsClientDir+f,hdfsClientDir+filenames[i])
dataAfterReorganized[i].drop('obs').drop('date').withColumn('fname', lit(filenames[i])).write.format("com.mongodb.spark.sql.DefaultSource")\
.option("spark.mongodb.output.uri", MONGO_METERDATA_COLLECTION_DIR)\
.mode("append")\
.save()
self.deleteHDFSFiles(filesToDelete, hdfsClientDir)
# dir = '/data-re/'
def reorganizeByMeterId(self, filenames, hdfsClientDir):
MONGO_METERDATA_COLLECTION_DIR = self.MONGO_METERDATA_COLLECTION_DIR
HOURS_PER_FILE = 8760 * 3600
hdfsClient = self.hdfsClient
hdfsFiles = ""
for f in filenames:
hdfsFiles += self.HDFS_DIR + "/" + f + ","
dataAfterReorganized = [None]*len(filenames)
sqlContext = self.sqlContext
customSchema = self.customSchema
filesToDelete = filenames
filenames = appendMeterPrefix(filenames)
df = sqlContext.read.format("org.apache.spark.csv").option("header", "false").schema(customSchema).csv(hdfsFiles[:len(hdfsFiles) - 1].split(','))
df.createOrReplaceTempView("data")
dataOrderByMeterId = sqlContext.sql("SELECT row_number() over (order by meterid) as rank ,_id, meterid, measurement, date, obs FROM data").cache()
for i in range(0, len(filenames)):
self.db.histogram.remove({"name": filesToDelete[i]})
self.db.meterdata.remove({"fname": filesToDelete[i]})
dataAfterReorganized[i] = dataOrderByMeterId.filter(dataOrderByMeterId.rank >= i * 43800).filter(dataOrderByMeterId.rank < 1 + (i + 1) * 43800).drop('rank')
dataAfterReorganized[i].repartition(1).write.mode("append").csv(self.HDFS_DIR)
# self.createHistogramByPandas(filenames[i], dataAfterReorganized[i])
self.createHistogramBySpark(filenames[i], dataAfterReorganized[i])
files = hdfsClient.list(hdfsClientDir)
for f in files:
if "part-00" in f:
hdfsClient.rename(hdfsClientDir+f,hdfsClientDir+filenames[i])
dataAfterReorganized[i].drop('obs').drop('date').withColumn('fname', lit(filenames[i])).write.format("com.mongodb.spark.sql.DefaultSource")\
.option("spark.mongodb.output.uri", MONGO_METERDATA_COLLECTION_DIR)\
.mode("append")\
.save()
self.deleteHDFSFiles(filesToDelete, hdfsClientDir)
# dir = '/data-re/'
def createHistogramByPandas(self, filename, sparkDataFrame):
pandasDF = sparkDataFrame.toPandas()
pandasDF.columns = ['id','meterid','measurement','date','comment']
data = {}
data["name"] = filename
hist = []
pysql = lambda q: pdsql.sqldf(q, {'pandasDF': pandasDF})
sql1 = "select date, count(*) as count from pandasDF group by date order by date"
df1 = pysql(sql1)
print df1
size = len(df1.index)
for num in range (size - 1, 0, -1):
hist.append({"date": (df1['date'][num]).split('.')[0], "cumulation": df1['count'][0:num+1].sum()})
data["hist"] = hist
json.dumps(data)
self.db.histogram.insert_one(data)
def createHistogramBySpark(self, filename, sparkDataFrame):
data = {}
data["name"] = filename
hist = []
sparkDataFrame.createOrReplaceTempView("data")
sql = "select date, count(*) as count from data group by date order by date"
results = self.sqlContext.sql(sql).collect()
size = len(results)
count = 0
for i in range(0, size - 1):
count += results[i][1]
hist.append({"date": str(results[i][0]), "cumulation": count})
data["hist"] = hist
json.dumps(data)
self.db.histogram.insert_one(data)
def deleteHDFSFiles(self, filenames, hdfsClientDir):
hdfsClient = self.hdfsClient
allHDFSFiles = hdfsClient.list(hdfsClientDir)
for f in allHDFSFiles:
if f in str(filenames):
hdfsClient.delete(hdfsClientDir+f)
def millis():
return int(round(time.time() * 1000))
# change name for file
def appendMeasurementPrefix(filenames):
for i in range(0, len(filenames) - 1):
filenames[i] = filenames[i].replace('time-', '')
return ['mea-' + s for s in filenames]
def appendTimestampPrefix(filenames):
for i in range(0, len(filenames) - 1):
filenames[i] = filenames[i].replace('mea-', '')
return ['time-' + s for s in filenames]
def appendMeterPrefix(filenames):
for i in range(0, len(filenames) - 1):
filenames[i] = filenames[i].replace('time-', '')
filenames[i] = filenames[i].replace('mea-', '')
return filenames
if __name__ == "__main__":
Reorganization()