Files
airflow/dags/business/business/community/relative_price_ranking.py
T
2025-03-06 10:39:41 +08:00

166 lines
5.0 KiB
Python

"""
相对价格排名计算同步至206
即周边一公里内小区价格排名0-1之间
"""
import logging
import pandas as pd
from goojia_utils import ElasticSearchClient, commutils, dateutils, ClickHouseClient
from elasticsearch import helpers
from concurrent.futures import ThreadPoolExecutor
import sys
from threading import Lock
log = logging.getLogger(__name__)
es206_client = ElasticSearchClient(host='192.168.0.89', username='elastic', password='elasticsearch')
tmp_ck = ClickHouseClient(database='tmp')
index_name = "community_summary"
path = "/home/airflow/data/community"
m_date = dateutils.iso_format()
mutex = Lock()
def find_around_seaweed(city_now, 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": [
{
"term": {
"city": {
"value": city_now
}
}
},
{
"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:
if pd.notna(item['relative_price_ranking']):
doc_dict['relative_price_ranking'] = item['relative_price_ranking']
else:
doc_dict['relative_price_ranking'] = None
if 'credit_detail' in item:
doc_dict['credit_detail'] = item['credit_detail']
return doc_dict
find_count = 0
actions = list()
def find_around_price_item(seaweed):
if 'lng' not in seaweed:
return
lng = commutils.format_lat_lng(seaweed['lng'])
lat = commutils.format_lat_lng(seaweed['lat'])
if pd.notna(lng):
city_now = seaweed['city']
around_seaweed_df = find_around_seaweed(city_now, lng, lat)
# 某些经纬度根本不在该城市下,数据问题
if len(around_seaweed_df) == 0:
return
global find_count
find_count += 1
if find_count % 1000 == 0:
log.info("已查找" + str(find_count))
mutex.acquire()
if len(around_seaweed_df) > 1:
around_seaweed_df['relative_price_ranking'] = around_seaweed_df['avg_price'].rank(pct=True)
temp_df = around_seaweed_df[around_seaweed_df['id'] == seaweed['_id']]
if len(temp_df) > 0:
seaweed['relative_price_ranking'] = temp_df.iloc[0]['relative_price_ranking']
else:
seaweed['relative_price_ranking'] = None
elif len(around_seaweed_df) == 1:
seaweed['relative_price_ranking'] = 0.5
around_community_num = len(around_seaweed_df)
if around_community_num >= 20:
relative_price_ranking_score = 10
elif 5 <= around_community_num < 20:
relative_price_ranking_score = 9
elif 1 < around_community_num < 5:
relative_price_ranking_score = 8
elif around_community_num == 1:
relative_price_ranking_score = 7
seaweed['credit_detail'] = {'around_community_num': around_community_num, 'relative_price_ranking_score': relative_price_ranking_score}
doc_info = build_doc(seaweed)
action = {
"_op_type": "update",
"_index": index_name,
"_id": seaweed['_id'],
"doc": doc_info,
"_retry_on_conflict": 5
}
actions.append(action)
if len(actions) == 5000:
helpers.bulk(es206_client.elastic_client, actions)
log.info("更新:" + str(find_count))
actions.clear()
mutex.release()
def sync(city=None):
log.info("开始同步相对价格排名数据...")
tmp_sql = f"select * from community_summary "
if pd.notna(city):
tmp_sql += f" where city='{city}'"
seaweed_df = tmp_ck.read_sql_query(tmp_sql)
seaweed_list = list()
seaweed_df.apply(lambda x: seaweed_list.append(dict(x)), axis=1)
with ThreadPoolExecutor(max_workers=30) as pool:
for seaweed in seaweed_list:
pool.submit(find_around_price_item, seaweed)
# for seaweed in seaweed_list:
# find_around_price_item(seaweed)
if len(actions) > 0:
helpers.bulk(es206_client.elastic_client, actions)
actions.clear()
log.info("完成同步相对价格排名数据...")
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)