224 lines
8.0 KiB
Python
224 lines
8.0 KiB
Python
"""
|
|
同步小区基本信息至ES206
|
|
"""
|
|
import logging
|
|
import pandas as pd
|
|
from goojia_utils import MAIN_MONGO_CLIENT, ElasticSearchClient, commutils, dateutils, ClickHouseClient
|
|
from elasticsearch import helpers
|
|
import os
|
|
import sys
|
|
|
|
log = logging.getLogger(__name__)
|
|
seaweed_conn = MAIN_MONGO_CLIENT.get_collection('fangjia', 'seaweed')
|
|
es206_client = ElasticSearchClient(host='192.168.0.89', username='elastic', password='elasticsearch')
|
|
tmp_ck = ClickHouseClient(database='tmp')
|
|
|
|
index_name = "community_summary"
|
|
m_date = dateutils.iso_format()
|
|
|
|
path = "/home/airflow/data/community"
|
|
if not os.path.exists(path):
|
|
os.makedirs(path)
|
|
|
|
|
|
def build_doc(item):
|
|
"""
|
|
构建字典
|
|
:param item:
|
|
:return:
|
|
"""
|
|
doc_dict = dict()
|
|
doc_dict['id'] = item["_id"]
|
|
doc_dict['m_date'] = m_date
|
|
doc_dict['city'] = item["city"]
|
|
doc_dict['region'] = item["region"]
|
|
doc_dict['name'] = item["name"]
|
|
doc_dict['estate_type'] = item['estate_type2']
|
|
|
|
build_type = commutils.format_build_type(item['build_type'])
|
|
if pd.notna(build_type):
|
|
doc_dict['build_type'] = build_type
|
|
if pd.notna(item['block']):
|
|
doc_dict['block'] = item['block']
|
|
|
|
household_count = commutils.format_households(item['household_count'])
|
|
if pd.notna(household_count):
|
|
doc_dict['household_count'] = household_count
|
|
|
|
estate_charge = commutils.format_property_fee(item['estate_charge'])
|
|
if pd.notna(estate_charge):
|
|
# 剔除过大物业费导致ES报错
|
|
if float(estate_charge) <= 1000:
|
|
doc_dict['estate_charge'] = float(estate_charge)
|
|
# 表示该物业费已经从库中补充
|
|
doc_dict['estate_charge_flag'] = 0
|
|
# 先打10分,对于其他的流程在修改分数
|
|
doc_dict['credit_detail'] = {'estate_charge_score': 10}
|
|
|
|
finish_building_date = commutils.format_finish_building_date(item['finish_building_date'])
|
|
if pd.notna(finish_building_date):
|
|
doc_dict["finish_building_date"] = int(finish_building_date)
|
|
|
|
lng = commutils.format_lat_lng(item['lng'])
|
|
lat = commutils.format_lat_lng(item['lat'])
|
|
if pd.notna(lng) and pd.notna(lat):
|
|
doc_dict['location'] = {'lon': lng, 'lat': lat}
|
|
|
|
# 新增字段存储
|
|
all_area = commutils.format_all_area(item['all_area'])
|
|
if pd.notna(all_area):
|
|
doc_dict['all_area'] = int(all_area)
|
|
build_area = commutils.format_build_area(item['build_area'])
|
|
if pd.notna(build_area):
|
|
doc_dict['build_area'] = int(build_area)
|
|
greening_rate = commutils.format_greening_rate(item['virescence_percent'])
|
|
if pd.notna(greening_rate):
|
|
doc_dict['greening_rate'] = greening_rate
|
|
volume_rate = commutils.format_plot_ratio(item['cubage_percent'])
|
|
if pd.notna(volume_rate):
|
|
doc_dict['volume_rate'] = volume_rate
|
|
house_type_area_dic = commutils.format_house_type_area(item['main_type'], item['main_type_area'])
|
|
main_house_type = house_type_area_dic['house_type']
|
|
main_house_area = house_type_area_dic['house_area']
|
|
if pd.notna(main_house_area):
|
|
try:
|
|
doc_dict['main_house_area'] = int(float(main_house_area))
|
|
except Exception as e:
|
|
pass
|
|
if pd.notna(main_house_type):
|
|
doc_dict['main_house_type'] = main_house_type
|
|
|
|
return doc_dict
|
|
|
|
|
|
def deal_comm(community_summary_df, seaweed_df):
|
|
"""
|
|
删除额外小区信息
|
|
"""
|
|
actions = list()
|
|
diff_ids = set(community_summary_df['_id']).difference(set(seaweed_df['_id']))
|
|
for _id in diff_ids:
|
|
action = {
|
|
"_op_type": "delete",
|
|
"_index": index_name,
|
|
"_id": _id,
|
|
}
|
|
actions.append(action)
|
|
if len(actions) == 5000:
|
|
helpers.bulk(es206_client.elastic_client, actions)
|
|
actions.clear()
|
|
if len(actions) > 0:
|
|
helpers.bulk(es206_client.elastic_client, actions)
|
|
actions.clear()
|
|
|
|
|
|
def sync(city=None):
|
|
log.info(f"开始同步小区基本属性至206 {index_name}...")
|
|
seaweed_query = {'status': 0, 'cat': 'district'}
|
|
ck_sql = "ALTER TABLE tmp.community_summary DELETE WHERE 1=1 "
|
|
if pd.notna(city):
|
|
seaweed_query['city'] = city
|
|
ck_sql += " AND city='" + city + "'"
|
|
tmp_ck.execute(ck_sql)
|
|
|
|
seaweed_df = pd.DataFrame(
|
|
list(seaweed_conn.find(seaweed_query, {'city': 1, 'region': 1, 'name': 1, 'lng': 1, 'lat': 1,
|
|
'alias': 1, 'estate_type2': 1, 'build_type': 1,
|
|
'household_count': 1, 'block': 1,
|
|
'estate_charge': 1, 'finish_building_date': 1,
|
|
'all_area': 1, 'build_area': 1, 'main_type': 1, 'main_type_area': 1, 'cubage_percent': 1, 'virescence_percent': 1
|
|
})
|
|
.batch_size(100000)))
|
|
|
|
sql = f"select id from {index_name} "
|
|
|
|
if pd.notna(city):
|
|
sql += f" where city='{city}'"
|
|
community_summary_df = es206_client.scan_by_sql_to_data_frame(sql)
|
|
seaweed_df['_id'] = seaweed_df['_id'].astype(str)
|
|
# 清除别名中逗号
|
|
def dealAlias(x):
|
|
if isinstance(x, list) and len(x) > 0:
|
|
for index, element in enumerate(x):
|
|
if "'" in element:
|
|
x[index] = str(element).replace("'", "")
|
|
return x
|
|
seaweed_df['alias'] = seaweed_df['alias'].apply(lambda x: dealAlias(x))
|
|
|
|
if len(community_summary_df) > 0:
|
|
community_summary_df['flag'] = 1
|
|
seaweed_new_df = pd.merge(seaweed_df, community_summary_df, how='left', on=['_id'])
|
|
seaweed_existed_df = seaweed_new_df[seaweed_new_df['flag'] == 1]
|
|
seaweed_not_existed_df = seaweed_new_df[seaweed_new_df['flag'] != 1]
|
|
else:
|
|
seaweed_existed_df = pd.DataFrame()
|
|
seaweed_not_existed_df = seaweed_df
|
|
|
|
# 写入csv文件,防止小区变动导致的后续过程更新报错,
|
|
# seaweed_df.to_csv(path + '/seaweed.csv', sep='@', encoding='UTF-8', index=False)
|
|
# 写入中间表clickhouse,解决多worker节点问题
|
|
tmp_ck.to_sql_plus(seaweed_df[['_id', 'city', 'region', 'name', 'lng', 'lat', 'alias', 'estate_type2', 'build_type',
|
|
'household_count', 'block', 'estate_charge', 'finish_building_date']], 'community_summary')
|
|
|
|
actions = list()
|
|
# 对于存在的更新
|
|
count = 0
|
|
for index, item in seaweed_existed_df.iterrows():
|
|
doc_info = build_doc(item)
|
|
|
|
action = {
|
|
"_op_type": "update",
|
|
"_index": index_name,
|
|
"_id": item['_id'],
|
|
"doc": doc_info
|
|
}
|
|
|
|
actions.append(action)
|
|
if len(actions) == 5000:
|
|
helpers.bulk(es206_client.elastic_client, actions)
|
|
count += len(actions)
|
|
log.info("更新:" + str(count))
|
|
actions.clear()
|
|
if len(actions) > 0:
|
|
helpers.bulk(es206_client.elastic_client, actions)
|
|
count += len(actions)
|
|
log.info("更新:" + str(count))
|
|
actions.clear()
|
|
|
|
# 对于不存在的插入
|
|
count = 0
|
|
for index, item in seaweed_not_existed_df.iterrows():
|
|
doc_info = build_doc(item)
|
|
|
|
action = {
|
|
"_op_type": "index",
|
|
"_index": index_name,
|
|
"_id": item['_id'],
|
|
"_source": doc_info,
|
|
"_retry_on_conflict": 5
|
|
}
|
|
|
|
actions.append(action)
|
|
if len(actions) == 5000:
|
|
helpers.bulk(es206_client.elastic_client, actions)
|
|
count += len(actions)
|
|
log.info("插入:" + str(count))
|
|
actions.clear()
|
|
if len(actions) > 0:
|
|
helpers.bulk(es206_client.elastic_client, actions)
|
|
count += len(actions)
|
|
log.info("插入:" + str(count))
|
|
actions.clear()
|
|
|
|
deal_comm(community_summary_df, seaweed_df)
|
|
log.info(f"完成同步小区基本属性至206 {index_name}")
|
|
|
|
|
|
sys_city = sys.argv[1] if len(sys.argv) > 1 else None
|
|
if pd.notna(sys_city) and "," in sys_city:
|
|
cities = sys_city.split(",")
|
|
for city in cities:
|
|
sync(city)
|
|
else:
|
|
sync(sys_city)
|