334 lines
12 KiB
Python
334 lines
12 KiB
Python
"""
|
|
物业费补全
|
|
"""
|
|
from goojia_utils import ElasticSearchClient, areautils, dateutils
|
|
import pandas as pd
|
|
import logging
|
|
import sys
|
|
from elasticsearch import helpers
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
from threading import Lock
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
es206_client = ElasticSearchClient(host='192.168.0.89', username='elastic', password='elasticsearch')
|
|
index_name = "community_summary"
|
|
file_path = "/opt/airflow/dags/repo/dags/business/business/community/data"
|
|
mutex = Lock()
|
|
estate_charge_min_max_df = pd.read_excel(file_path + '/全国各区域物业费中位值.xlsx')
|
|
estate_charge_city_region_dict = dict()
|
|
|
|
|
|
# 加载各区域物业费最大最小值
|
|
def deal_estate_charge(x):
|
|
city_now = x['city']
|
|
region_now = x['region']
|
|
if pd.notna(city_now) and pd.notna(region_now):
|
|
estate_charge_city_region_dict[city_now + region_now] = {'min': x['3'], 'max': x['97']}
|
|
elif pd.notna(city_now):
|
|
estate_charge_city_region_dict[city_now] = {'min': x['3'], 'max': x['97']}
|
|
estate_charge_min_max_df.apply(lambda x: deal_estate_charge(x), axis=1)
|
|
|
|
|
|
def save_fix(community_summary_df):
|
|
if 'estate_charge_fix' not in community_summary_df.columns:
|
|
log.info("该城市无调整物业费")
|
|
return
|
|
df = community_summary_df[['_id', 'city', 'estate_charge_fix', 'estate_charge_score']]
|
|
df = df.dropna(subset=['estate_charge_fix'])
|
|
actions = list()
|
|
count = 0
|
|
|
|
# 批量更新
|
|
m_date = dateutils.iso_format()
|
|
for index, item in df.iterrows():
|
|
row = dict()
|
|
_id = str(item["_id"])
|
|
row['estate_charge_fix'] = item['estate_charge_fix']
|
|
row['credit_detail'] = {'estate_charge_score': int(item['estate_charge_score'])}
|
|
row['m_date'] = m_date
|
|
|
|
action = {'_op_type': 'update',
|
|
'_index': index_name,
|
|
'_id': _id, # 请勿忘记ID
|
|
'doc': row,
|
|
"_retry_on_conflict": 5
|
|
}
|
|
actions.append(action)
|
|
if len(actions) == 5000:
|
|
helpers.bulk(client=es206_client.elastic_client, actions=actions)
|
|
count += len(actions)
|
|
actions.clear()
|
|
log.info("已更新{}".format(count))
|
|
if len(actions) > 0:
|
|
helpers.bulk(client=es206_client.elastic_client, actions=actions)
|
|
count += len(actions)
|
|
actions.clear()
|
|
log.info("更新完成,共更新: {}".format(count))
|
|
return df
|
|
|
|
|
|
|
|
def save_fill(community_summary_df):
|
|
if 'estate_charge' not in community_summary_df.columns or 'estate_charge_score' not in community_summary_df.columns:
|
|
log.info("该城市无补充物业费")
|
|
return
|
|
df = community_summary_df[['_id', 'city', 'estate_charge', 'estate_charge_score']]
|
|
df = df.dropna(subset=['estate_charge'])
|
|
actions = list()
|
|
count = 0
|
|
|
|
# 批量更新
|
|
m_date = dateutils.iso_format()
|
|
for index, item in df.iterrows():
|
|
row = dict()
|
|
_id = str(item["_id"])
|
|
row['estate_charge'] = item['estate_charge']
|
|
if pd.notna(item['estate_charge_score']):
|
|
row['credit_detail'] = {'estate_charge_score': int(item['estate_charge_score'])}
|
|
# 1 表示为物业费补充的,在实际应用中不输出
|
|
row['estate_charge_flag'] = 1
|
|
row['m_date'] = m_date
|
|
|
|
action = {'_op_type': 'update',
|
|
'_index': index_name,
|
|
'_id': _id, # 请勿忘记ID
|
|
'doc': row,
|
|
"_retry_on_conflict": 5
|
|
}
|
|
actions.append(action)
|
|
if len(actions) == 5000:
|
|
helpers.bulk(client=es206_client.elastic_client, actions=actions)
|
|
count += len(actions)
|
|
actions.clear()
|
|
log.info("已更新{}".format(count))
|
|
if len(actions) > 0:
|
|
helpers.bulk(client=es206_client.elastic_client, actions=actions)
|
|
count += len(actions)
|
|
actions.clear()
|
|
log.info("更新完成,共更新: {}".format(count))
|
|
return df
|
|
|
|
|
|
def find_nearest_by_location(city, location):
|
|
docs = list()
|
|
try:
|
|
scan = es206_client.scan(index_name, {
|
|
"size": 4,
|
|
"_source": ["finish_building_date", "estate_charge", "estate_charge_fix"],
|
|
"query": {
|
|
"bool": {
|
|
"filter": [
|
|
{
|
|
"term": {
|
|
"city": city
|
|
}
|
|
}
|
|
],
|
|
"must_not": [
|
|
{
|
|
"term": {
|
|
"estate_charge_flag": {
|
|
"value": 1
|
|
}
|
|
}
|
|
}
|
|
]
|
|
}
|
|
},
|
|
"sort": [
|
|
{
|
|
"_geo_distance": {
|
|
"location": location,
|
|
"order": "asc"
|
|
}
|
|
}
|
|
]
|
|
}, preserve_order=True)
|
|
ignored_first = False
|
|
for doc in scan:
|
|
# 忽略自己
|
|
if ignored_first is False:
|
|
ignored_first = True
|
|
continue
|
|
docs.append(doc['_source'])
|
|
if len(docs) == 3:
|
|
return pd.DataFrame(docs)
|
|
return None
|
|
except Exception as e:
|
|
logging.error(e)
|
|
return None
|
|
|
|
|
|
def get_estate_charge_for_adjust(finish_building_date, docs):
|
|
aim_year = int(finish_building_date / 10)
|
|
for index, item in docs.iterrows():
|
|
if pd.notna(item['finish_building_date']) and pd.notna(item['estate_charge']) and aim_year == int(item['finish_building_date'] / 10):
|
|
return item['estate_charge']
|
|
return None
|
|
|
|
|
|
def get_estate_charge(finish_building_date, docs):
|
|
aim_year = int(finish_building_date / 10)
|
|
for index, item in docs.iterrows():
|
|
if pd.notna(item['finish_building_date']) and pd.notna(item['estate_charge_fix']) and aim_year == int(item['finish_building_date'] / 10):
|
|
return item['estate_charge_fix']
|
|
return None
|
|
|
|
|
|
find_count = 0
|
|
def deal_adjust(community):
|
|
global find_count
|
|
find_count += 1
|
|
if find_count % 1000 == 0:
|
|
log.info("已查找" + str(find_count))
|
|
max_now = 7
|
|
city_short = community['city']
|
|
region_short = community['region']
|
|
if (city_short + region_short) in estate_charge_city_region_dict:
|
|
max_now = estate_charge_city_region_dict[city_short + region_short]['max']
|
|
elif city_short in estate_charge_city_region_dict:
|
|
max_now = estate_charge_city_region_dict[city_short]['max']
|
|
|
|
if community['estate_charge'] > max_now:
|
|
estate_charge, score = find_estate_charge_for_adjust(community, max_now)
|
|
if pd.notna(estate_charge):
|
|
mutex.acquire(timeout=60)
|
|
community['estate_charge_fix'] = estate_charge
|
|
community['estate_charge_score'] = score
|
|
mutex.release()
|
|
|
|
def adjust_estate_charge(city_now):
|
|
log.info(f"{city_now}开始调整物业费....")
|
|
sql = f"select id, city, region, name, estate_charge, finish_building_date, location from community_summary where city='{city_now}' and estate_charge_flag != 1 and estate_type != '别墅' "
|
|
community_summary_df = es206_client.scan_by_sql_to_data_frame(sql)
|
|
community_summary_list = list()
|
|
community_summary_df.apply(lambda x: community_summary_list.append(dict(x)), axis=1)
|
|
|
|
with ThreadPoolExecutor(max_workers=30) as pool:
|
|
for community_summary in community_summary_list:
|
|
pool.submit(deal_adjust, community_summary)
|
|
# for community_summary in community_summary_list:
|
|
# deal_adjust(community_summary)
|
|
community_summary_df = pd.DataFrame(community_summary_list)
|
|
save_fix(community_summary_df)
|
|
|
|
log.info(f"{city_now}完成调整物业费....")
|
|
|
|
|
|
def find_estate_charge_for_adjust(community, max_now):
|
|
"""
|
|
查找小区周边物业费
|
|
"""
|
|
estate_charge = None
|
|
if pd.isna(community['location']) or pd.isna(community['location']['lon']):
|
|
return estate_charge
|
|
location = [community['location']['lon'], community['location']['lat']]
|
|
docs = find_nearest_by_location(community['city'], location)
|
|
if len(docs) <= 0 or 'estate_charge' not in docs.columns:
|
|
return estate_charge
|
|
# 记录打分
|
|
score = None
|
|
if pd.notna(community['finish_building_date']) and 'finish_building_date' in docs.columns:
|
|
# 根据相近建筑年代赋值
|
|
estate_charge = get_estate_charge_for_adjust(community['finish_building_date'], docs)
|
|
score = 9
|
|
if pd.isna(estate_charge) or estate_charge > max_now:
|
|
# 取周边均值
|
|
estate_charge = docs['estate_charge'].mean()
|
|
score = 8
|
|
# 如果查找的还大于分位值,不调整
|
|
if estate_charge > max_now:
|
|
estate_charge = None
|
|
score = None
|
|
return estate_charge, score
|
|
|
|
def find_estate_charge(community, max_now):
|
|
"""
|
|
查找小区周边物业费
|
|
"""
|
|
estate_charge = None
|
|
if pd.isna(community['location']) or pd.isna(community['location']['lon']):
|
|
return estate_charge, 5
|
|
location = [community['location']['lon'], community['location']['lat']]
|
|
docs = find_nearest_by_location(community['city'], location)
|
|
if len(docs) <= 0 or 'estate_charge' not in docs.columns:
|
|
return estate_charge, 5
|
|
if 'estate_charge_fix' not in docs.columns:
|
|
docs['estate_charge_fix'] = None
|
|
# 用修正后的物业费补充
|
|
docs['estate_charge_fix'].fillna(docs['estate_charge'], inplace=True)
|
|
score = None
|
|
if pd.notna(community['finish_building_date']) and 'finish_building_date' in docs.columns:
|
|
# 根据相近建筑年代赋值
|
|
estate_charge = get_estate_charge(community['finish_building_date'], docs)
|
|
score = 7
|
|
if pd.isna(estate_charge) or estate_charge > max_now:
|
|
# 取周边均值
|
|
estate_charge = docs['estate_charge_fix'].mean()
|
|
score = 6
|
|
if estate_charge > max_now:
|
|
estate_charge = None
|
|
score = None
|
|
return estate_charge, score
|
|
|
|
find_count = 0
|
|
def deal_fill(community):
|
|
global find_count
|
|
find_count += 1
|
|
if find_count % 1000 == 0:
|
|
log.info("已查找" + str(find_count))
|
|
|
|
max_now = 7
|
|
city_short = community['city']
|
|
region_short = community['region']
|
|
if (city_short + region_short) in estate_charge_city_region_dict:
|
|
max_now = estate_charge_city_region_dict[city_short + region_short]['max']
|
|
elif city_short in estate_charge_city_region_dict:
|
|
max_now = estate_charge_city_region_dict[city_short]['max']
|
|
if community['estate_type'] == '别墅':
|
|
# 别墅不限制物业费最大值
|
|
max_now = 99
|
|
estate_charge, score = find_estate_charge(community, max_now)
|
|
if pd.notna(estate_charge):
|
|
mutex.acquire(timeout=60)
|
|
community["estate_charge"] = estate_charge
|
|
community["estate_charge_score"] = score
|
|
mutex.release()
|
|
|
|
def fill_estate_charge(city_now):
|
|
log.info(f"{city_now}开始补充物业费....")
|
|
sql = "select id, city, region, name, estate_charge, estate_charge_fix, finish_building_date, estate_type, location from community_summary where city='" + city_now + "' and (estate_charge is null or estate_charge_flag=1) "
|
|
community_summary_df = es206_client.scan_by_sql_to_data_frame(sql)
|
|
|
|
community_summary_list = list()
|
|
community_summary_df.apply(lambda x: community_summary_list.append(dict(x)), axis=1)
|
|
|
|
with ThreadPoolExecutor(max_workers=30) as pool:
|
|
for community_summary in community_summary_list:
|
|
pool.submit(deal_fill, community_summary)
|
|
community_summary_df = pd.DataFrame(community_summary_list)
|
|
save_fill(community_summary_df)
|
|
log.info(f"{city_now}完成补充物业费....")
|
|
|
|
|
|
def sync_by_city(city_now):
|
|
adjust_estate_charge(city_now)
|
|
fill_estate_charge(city_now)
|
|
|
|
|
|
def sync(city=None):
|
|
if pd.isna(city):
|
|
for city_now in areautils.get_all_cities():
|
|
sync_by_city(city_now)
|
|
else:
|
|
sync_by_city(city)
|
|
|
|
|
|
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) |