2016-03-08 48 views
0

我有一個方法將字符串轉換爲特定類型。數據從csv文件讀取並用於創建rdd。爲了讓這個函數起作用,我不得不將這些import語句放在函數定義中。這意味着每次調用函數時都會執行這些行。導入的軟件包必須存在於羣集節點上,否則該功能無法工作。是否有可能將導入移出該方法並仍然引用它們?如果是這樣,怎麼樣?RDD.map和嵌套導入的函數

def convertType(v, ftype, fmt = '%Y-%m-%d %H:%M:%S %Z', nodate = '1900-01-01 0:00:00: GMT', empty2None = False): 
    import datetime 
    import decimal 
    v = v.strip() # clean up the string 
    if empty2None: 
    if v == "": # do we have an empty string? 
     return None 
    ftypes = { 'null': 'None', \ 
     'date': 'datetime.date(int(v))', \ 
     'timestamp': 'datetime.datetime.strptime(v if not (v == "") else nodate, fmt)', \ 
     'binary': 'bytearray(v)', \ 
     'integer': 'int(v)', \ 
     'boolean': 'bool(v)', \ 
     'long': 'long(v)', \ 
     'double': 'float(v)', \ 
     'float': 'float(v)', \ 
     'short': 'int(v)', \ 
     'byte': 'int(v)', \ 
     'string': 'str(v)', \ 
     'decimal': 'decimal.Decimal(v)' \ 
     } 
    return eval(ftypes[ftype.lower()]) 

data = raw.map(lambda p: [convertType(p[0][i], typeparts[i], fmt, nodate, True) for i in indx]) # convert split text to data rows 

回答

1

爲了儘量減少導入開銷,你可以嘗試使用mapPartitions。然後,您將爲每個分區導入一次(而不是每行)。

def convertPartitionType(elements): 
    import ... 
    return [convertType(x) for x in elements] 

其中,當然,convertType不會導入任何東西。