Files
airflow/dags/business/business/community/relative_price_ranking.py
T
2023-03-10 17:37:21 +08:00

143 lines
4.1 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
import sys
from threading import Lock
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()
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 and pd.notna(item['relative_price_ranking']):
doc_dict['relative_price_ranking'] = item['relative_price_ranking']
return doc_dict
find_count = 0
def find_around_price_item(seaweed):
global find_count
find_count += 1
if find_count % 1000 == 0:
log.info("已查找" + str(find_count))
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)
mutex.acquire(timeout=60)
if len(around_seaweed_df) > 1:
around_seaweed_df['relative_price_ranking'] = around_seaweed_df['avg_price'].rank(pct=True)
seaweed['relative_price_ranking'] = around_seaweed_df[around_seaweed_df['id'] == seaweed['_id']].iloc[0][
'relative_price_ranking']
elif len(around_seaweed_df) == 1:
seaweed['relative_price_ranking'] = 0.5
mutex.release()
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(drop=True)
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)
seaweed_df = pd.DataFrame(seaweed_list)
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,
"_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:
try:
helpers.bulk(es206_client.elastic_client, actions)
except Exception as e:
log.error(e)
actions.clear()
log.info("完成同步相对价格排名数据...")
city = sys.argv[1] if len(sys.argv) > 1 else None
sync(city)