Files
airflow/dags/business/business/community/avg_cost.py
T
2023-03-10 17:07:51 +08:00

158 lines
4.7 KiB
Python

"""
小区周边消费同步至206
"""
import logging
import pandas as pd
from goojia_utils import ElasticSearchClient, commutils, dateutils, areautils
from elasticsearch import helpers
from concurrent.futures import ThreadPoolExecutor
import sys
from threading import Lock
mutex = Lock()
log = logging.getLogger(__name__)
es206_client = ElasticSearchClient(host='192.168.0.206')
index_name = "community_summary"
m_date = dateutils.iso_format()
path = "/home/airflow/data/community"
file_path = "/opt/airflow/dags/repo/dags/business/business/community/data"
avg_cost_min_max_df = pd.read_excel(file_path + '/全国各区域人均消费中位值.xlsx')
avg_cost_city_region_dict = dict()
# 加载各区域人均消费最大最小值
def deal_avg_cost(x):
city_now = x['city']
region_now = x['region']
if pd.notna(city_now) and pd.notna(region_now):
avg_cost_city_region_dict[city_now + region_now] = {'min': x['3'], 'max': x['97']}
elif pd.notna(city_now):
avg_cost_city_region_dict[city_now] = {'min': x['3'], 'max': x['97']}
avg_cost_min_max_df.apply(lambda x: deal_avg_cost(x), axis=1)
def find_around_price(seaweed):
"""
查找周边均价
返回取值为10~300,为所有有价格的1-99百分位
"""
lng = commutils.format_lat_lng(seaweed['lng'])
lat = commutils.format_lat_lng(seaweed['lat'])
city_short = seaweed['city']
region_short = seaweed['region']
city_display = areautils.get_city_display(city_short)
filter_query = [{"terms": {"tag": ["美食;中餐厅", "美食;外国餐厅"]}}]
if pd.notna(city_display):
filter_query.append({"term": {"city": {"value": city_display}}})
min_now = 10
max_now = 300
if (city_short+region_short) in avg_cost_city_region_dict:
min_now = avg_cost_city_region_dict[city_short + region_short]['min']
max_now = avg_cost_city_region_dict[city_short + region_short]['max']
elif city_short in avg_cost_city_region_dict:
min_now = avg_cost_city_region_dict[city_short]['min']
max_now = avg_cost_city_region_dict[city_short]['max']
filter_query.append({"range": {"price": {"gte": min_now, "lte": max_now}}})
filter_query.append({"geo_distance": {"distance": 1000, "location": [lng, lat]}})
ret_es = es206_client.elastic_client.search({
"query": {
"bool": {
"filter": filter_query
}
},
"size": 0,
"aggs": {
"price": {
"avg": {
"field": "price"
}
}
}
}, index='bd_poi')
return ret_es['aggregations']['price']['value']
def build_doc(item):
doc_dict = dict()
if 'avg_cost' in item:
if pd.notna(item['avg_cost']) or item['avg_cost'] > 0:
doc_dict['avg_cost'] = int(item['avg_cost'])
else:
doc_dict['avg_cost'] = None
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
price = find_around_price(seaweed)
mutex.acquire(timeout=60)
if pd.notna(price):
seaweed['avg_cost'] = int(price)
else:
seaweed['avg_cost'] = None
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:
helpers.bulk(es206_client.elastic_client, actions)
actions.clear()
log.info("完成同步消费数据...")
city = sys.argv[1] if len(sys.argv) > 1 else None
sync(city)