Files
airflow/dags/business/business/community/relative_price_ranking.py
T
2022-11-02 09:37:52 +08:00

115 lines
3.5 KiB
Python

"""
相对价格排名计算同步至206
即周边一公里内小区价格排名0-1之间
"""
import logging
import pandas as pd
from goojia_utils import ElasticSearchClient, commutils, dateutils
from elasticsearch import helpers
from concurrent.futures import ThreadPoolExecutor
log = logging.getLogger(__name__)
es206_client = ElasticSearchClient(host='192.168.0.206')
index_name = "community_summary"
path = "/home/airflow/data/community"
m_date = dateutils.iso_format()
def find_around_seaweed(lng, lat):
"""
查找周边均价
"""
if pd.isna(lng):
return None
ret_es = es206_client.scan_to_data_frame('community_summary', {
"_source": ["id", "avg_price"],
"query": {
"bool": {
"filter": [
{
"range": {
"avg_price": {
"gt": 0
}
}
},
{
"geo_distance": {
"distance": 1000,
"location": [lng, lat]
}
}
]
}
}
})
return ret_es
def build_doc(item):
doc_dict = dict()
if 'relative_price_ranking' in item and pd.notna(item['relative_price_ranking']):
doc_dict['relative_price_ranking'] = item['relative_price_ranking']
return doc_dict
def sync(city=None):
log.info("开始同步相对价格排名数据...")
seaweed_df = pd.read_csv(path + '/seaweed.csv', sep='@', encoding='UTF-8')
if pd.notna(city):
seaweed_df = seaweed_df[seaweed_df['city'] == city].copy()
seaweed_df = seaweed_df.reset_index()
def find_around_price_item(index, item):
if index % 1000 == 0:
log.info("已处理" + str(index))
if 'lng' not in item:
return
lng = commutils.format_lat_lng(item['lng'])
lat = commutils.format_lat_lng(item['lat'])
if pd.notna(lng):
around_seaweed_df = find_around_seaweed(lng, lat)
if len(around_seaweed_df) > 1:
around_seaweed_df['relative_price_ranking'] = around_seaweed_df['avg_price'].rank(pct=True)
seaweed_df.loc[index, 'relative_price_ranking'] = around_seaweed_df.loc[around_seaweed_df['id'] == item['_id']]['relative_price_ranking'].tolist()[0]
elif len(around_seaweed_df) == 1:
seaweed_df.loc[index, 'relative_price_ranking'] = 0.5
with ThreadPoolExecutor(max_workers=30) as pool:
for index, item in seaweed_df.iterrows():
pool.submit(find_around_price_item, index, item)
actions = list()
count = 0
for index, item in seaweed_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:
try:
helpers.bulk(es206_client.elastic_client, actions)
count += len(actions)
log.info("更新:" + str(count))
except Exception as e:
log.error(e)
actions.clear()
if len(actions) > 0:
try:
helpers.bulk(es206_client.elastic_client, actions)
except Exception as e:
log.error(e)
actions.clear()
log.info("完成同步相对价格排名数据...")
sync()