Blame view

offline_tasks/scripts/load_index_to_redis.py 13.7 KB
5ab1c29c   tangwang   first commit
1
2
3
4
  """
  将生成的索引加载到Redis
  用于在线推荐系统查询
  """
5ab1c29c   tangwang   first commit
5
6
7
  import redis
  import argparse
  import logging
e89d7a84   tangwang   deepwalk refactor...
8
9
  import os
  import sys
092804bc   tangwang   fix(offline): 修复离...
10
  from collections import Counter
5ab1c29c   tangwang   first commit
11
  from datetime import datetime
be9c0900   tangwang   之前多个任务,配置分散,进行集中管...
12
13
14
  
  # 添加父目录到Python路径
  sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
8b9ea8ee   tangwang   feat(recommendati...
15
16
17
  from config.offline_config import REDIS_CONFIG, OUTPUT_DIR, ITEM_FRESHNESS_CONFIG
  from scripts.item_freshness import (
      cutoff_date_for_dimension, filter_item_score_value, get_item_age_cutoff_date,
092804bc   tangwang   fix(offline): 修复离...
18
      is_item_fresh, load_item_create_times, normalize_item_id
8b9ea8ee   tangwang   feat(recommendati...
19
  )
5ab1c29c   tangwang   first commit
20
  
9eb36bd2   tangwang   add logs
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
  def setup_logger():
      """设置logger配置"""
      # 创建logs目录
      logs_dir = 'logs'
      os.makedirs(logs_dir, exist_ok=True)
      
      # 创建logger
      logger = logging.getLogger('load_index_to_redis')
      logger.setLevel(logging.INFO)
      
      # 避免重复添加handler
      if logger.handlers:
          return logger
      
      # 创建文件handler
      log_file = os.path.join(logs_dir, f'load_index_to_redis_{datetime.now().strftime("%Y%m%d")}.log')
      file_handler = logging.FileHandler(log_file, encoding='utf-8')
      file_handler.setLevel(logging.INFO)
      
      # 创建控制台handler
      console_handler = logging.StreamHandler()
      console_handler.setLevel(logging.INFO)
      
      # 创建formatter
      formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
      file_handler.setFormatter(formatter)
      console_handler.setFormatter(formatter)
      
      # 添加handler到logger
      logger.addHandler(file_handler)
      logger.addHandler(console_handler)
      
      return logger
  
  logger = setup_logger()
5ab1c29c   tangwang   first commit
56
57
  
  
092804bc   tangwang   fix(offline): 修复离...
58
59
60
61
62
63
64
65
  def looks_like_item_id(key_suffix):
      try:
          int(float(str(key_suffix).strip()))
          return True
      except (ValueError, OverflowError, TypeError):
          return False
  
  
8b9ea8ee   tangwang   feat(recommendati...
66
67
68
  def load_index_file(file_path, redis_client, key_prefix, expire_seconds=None,
                      create_times=None, cutoff_date=None, strict_cutoff_date=None,
                      filter_key_as_item=False):
5ab1c29c   tangwang   first commit
69
70
71
72
73
74
75
76
      """
      加载索引文件到Redis
      
      Args:
          file_path: 索引文件路径
          redis_client: Redis客户端
          key_prefix: Redis key前缀
          expire_seconds: 过期时间(秒),None表示不过期
8b9ea8ee   tangwang   feat(recommendati...
77
78
79
          create_times: 商品创建日期映射,用于新鲜度截断
          cutoff_date: 最早允许进入索引的创建日期 YYYY-MM-DD
          filter_key_as_item: True 时把 key 当作商品 ID(i2i),过老则整行跳过
5ab1c29c   tangwang   first commit
80
81
82
83
84
85
86
87
88
      
      Returns:
          加载的记录数
      """
      if not os.path.exists(file_path):
          logger.error(f"File not found: {file_path}")
          return 0
      
      count = 0
8b9ea8ee   tangwang   feat(recommendati...
89
90
      skipped_old_keys = 0
      skipped_empty_after_filter = 0
092804bc   tangwang   fix(offline): 修复离...
91
92
      skipped_malformed = 0
      skipped_age_years = Counter()
8b9ea8ee   tangwang   feat(recommendati...
93
94
95
      keep_unknown = ITEM_FRESHNESS_CONFIG['keep_unknown_age']
      apply_freshness = bool(create_times) and bool(cutoff_date)
  
5ab1c29c   tangwang   first commit
96
97
98
99
100
101
102
      with open(file_path, 'r', encoding='utf-8') as f:
          for line in f:
              line = line.strip()
              if not line:
                  continue
              
              parts = line.split('\t')
f53ede48   tangwang   deepwalk refactor...
103
              if len(parts) < 2:
092804bc   tangwang   fix(offline): 修复离...
104
                  skipped_malformed += 1
5ab1c29c   tangwang   first commit
105
106
                  continue
              
f53ede48   tangwang   deepwalk refactor...
107
108
109
110
111
              # 支持2字段和3字段格式
              # 格式1 (2字段): item_id \t similar_items
              # 格式2 (3字段): item_id \t item_name \t similar_items (推荐格式)
              # 取第一个字段作为key,最后一个字段作为value
              key_suffix = parts[0]
d35d18eb   tangwang   fix
112
113
114
115
116
117
118
119
              
              # 修复:将浮点数ID转换为整数(如 "60678.0" -> "60678")
              try:
                  if '.' in key_suffix:
                      key_suffix = str(int(float(key_suffix)))
              except (ValueError, OverflowError):
                  # 如果转换失败,保持原样
                  pass
8b9ea8ee   tangwang   feat(recommendati...
120
  
092804bc   tangwang   fix(offline): 修复离...
121
122
123
124
              if filter_key_as_item and not looks_like_item_id(key_suffix):
                  skipped_malformed += 1
                  continue
  
8b9ea8ee   tangwang   feat(recommendati...
125
126
127
              if apply_freshness and filter_key_as_item:
                  if not is_item_fresh(key_suffix, create_times, cutoff_date, keep_unknown):
                      skipped_old_keys += 1
092804bc   tangwang   fix(offline): 修复离...
128
129
                      create_date = create_times.get(normalize_item_id(key_suffix), '')
                      skipped_age_years[create_date[:4] if create_date else 'unknown'] += 1
8b9ea8ee   tangwang   feat(recommendati...
130
                      continue
d35d18eb   tangwang   fix
131
                  
f53ede48   tangwang   deepwalk refactor...
132
              value = parts[-1]
8b9ea8ee   tangwang   feat(recommendati...
133
134
135
136
137
138
139
140
141
              if apply_freshness:
                  value_cutoff = cutoff_date
                  if not filter_key_as_item and strict_cutoff_date:
                      value_cutoff = cutoff_date_for_dimension(key_suffix, cutoff_date, strict_cutoff_date)
                  value = filter_item_score_value(value, create_times, value_cutoff, keep_unknown)
                  if not value:
                      skipped_empty_after_filter += 1
                      continue
  
5ab1c29c   tangwang   first commit
142
143
144
145
146
147
148
149
150
151
152
153
154
              redis_key = f"{key_prefix}:{key_suffix}"
              
              # 存储到Redis
              redis_client.set(redis_key, value)
              
              # 设置过期时间
              if expire_seconds:
                  redis_client.expire(redis_key, expire_seconds)
              
              count += 1
              
              if count % 1000 == 0:
                  logger.info(f"Loaded {count} records...")
8b9ea8ee   tangwang   feat(recommendati...
155
  
092804bc   tangwang   fix(offline): 修复离...
156
157
158
159
160
      if skipped_malformed:
          logger.warning(
              f"Skipped {skipped_malformed} malformed lines in {os.path.basename(file_path)} "
              f"(likely names containing newlines from older outputs)"
          )
8b9ea8ee   tangwang   feat(recommendati...
161
162
163
164
165
166
      if apply_freshness:
          logger.info(
              f"Freshness filter on {os.path.basename(file_path)}: loaded={count}, "
              f"skipped_old_keys={skipped_old_keys}, skipped_empty={skipped_empty_after_filter}, "
              f"cutoff={cutoff_date}"
          )
092804bc   tangwang   fix(offline): 修复离...
167
168
169
170
171
          if skipped_age_years:
              top_years = ', '.join(
                  f"{year}:{cnt}" for year, cnt in skipped_age_years.most_common(8)
              )
              logger.info(f"Skipped old-key create years: {top_years}")
5ab1c29c   tangwang   first commit
172
173
174
175
      
      return count
  
  
8b9ea8ee   tangwang   feat(recommendati...
176
  def load_cpp_swing_index(redis_client, expire_days=60, create_times=None, cutoff_date=None):
c0b24bef   tangwang   fix redis data
177
178
      """
      加载C++ Swing相似度索引
8b9ea8ee   tangwang   feat(recommendati...
179
  
c0b24bef   tangwang   fix redis data
180
181
182
      Args:
          redis_client: Redis客户端
          expire_days: 过期天数
8b9ea8ee   tangwang   feat(recommendati...
183
  
c0b24bef   tangwang   fix redis data
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
      Returns:
          加载的记录数
      """
      # C++ Swing输出文件
      file_path = os.path.join(os.path.dirname(OUTPUT_DIR), 'collaboration', 'output', 'swing_similar.txt')
      
      if not os.path.exists(file_path):
          logger.warning(f"C++ Swing file not found: {file_path}, skipping...")
          return 0
      
      expire_seconds = expire_days * 24 * 3600 if expire_days else None
      
      logger.info(f"Loading C++ Swing indices from {file_path}...")
      count = load_index_file(
          file_path,
          redis_client,
          "item:similar:swing_cpp",
8b9ea8ee   tangwang   feat(recommendati...
201
202
203
204
          expire_seconds,
          create_times=create_times,
          cutoff_date=cutoff_date,
          filter_key_as_item=True,
c0b24bef   tangwang   fix redis data
205
206
207
208
209
      )
      logger.info(f"Loaded {count} C++ Swing indices")
      return count
  
  
8b9ea8ee   tangwang   feat(recommendati...
210
  def load_i2i_indices(redis_client, date_str=None, expire_days=60, create_times=None, cutoff_date=None):
5ab1c29c   tangwang   first commit
211
212
      """
      加载i2i相似度索引
8b9ea8ee   tangwang   feat(recommendati...
213
  
5ab1c29c   tangwang   first commit
214
215
216
217
218
219
220
221
222
223
224
      Args:
          redis_client: Redis客户端
          date_str: 日期字符串,格式YYYYMMDD,None表示使用今天
          expire_days: 过期天数
      """
      if not date_str:
          date_str = datetime.now().strftime('%Y%m%d')
      
      expire_seconds = expire_days * 24 * 3600 if expire_days else None
      
      # i2i索引类型
c0b24bef   tangwang   fix redis data
225
      i2i_types = ['swing', 'session_w2v', 'deepwalk', 'content_name', 'content_pic', 'item_behavior']
5ab1c29c   tangwang   first commit
226
227
228
229
230
231
232
233
234
235
236
237
      
      for i2i_type in i2i_types:
          file_path = os.path.join(OUTPUT_DIR, f'i2i_{i2i_type}_{date_str}.txt')
          
          if not os.path.exists(file_path):
              logger.warning(f"File not found: {file_path}, skipping...")
              continue
          
          logger.info(f"Loading {i2i_type} indices...")
          count = load_index_file(
              file_path,
              redis_client,
c0b24bef   tangwang   fix redis data
238
              f"item:similar:{i2i_type}",  # 修复: 使用正确的key前缀
8b9ea8ee   tangwang   feat(recommendati...
239
240
241
242
              expire_seconds,
              create_times=create_times,
              cutoff_date=cutoff_date,
              filter_key_as_item=True,
5ab1c29c   tangwang   first commit
243
244
245
246
          )
          logger.info(f"Loaded {count} {i2i_type} indices")
  
  
8b9ea8ee   tangwang   feat(recommendati...
247
248
  def load_interest_indices(redis_client, date_str=None, expire_days=60, create_times=None,
                            cutoff_date=None, strict_cutoff_date=None):
5ab1c29c   tangwang   first commit
249
250
      """
      加载兴趣点聚合索引
8b9ea8ee   tangwang   feat(recommendati...
251
  
5ab1c29c   tangwang   first commit
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
      Args:
          redis_client: Redis客户端
          date_str: 日期字符串,格式YYYYMMDD,None表示使用今天
          expire_days: 过期天数
      """
      if not date_str:
          date_str = datetime.now().strftime('%Y%m%d')
      
      expire_seconds = expire_days * 24 * 3600 if expire_days else None
      
      # 兴趣点索引类型
      list_types = ['hot', 'cart', 'new', 'global']
      
      for list_type in list_types:
          file_path = os.path.join(OUTPUT_DIR, f'interest_aggregation_{list_type}_{date_str}.txt')
          
          if not os.path.exists(file_path):
              logger.warning(f"File not found: {file_path}, skipping...")
              continue
          
          logger.info(f"Loading {list_type} interest indices...")
          count = load_index_file(
              file_path,
              redis_client,
              f"interest:{list_type}",
8b9ea8ee   tangwang   feat(recommendati...
277
278
279
280
281
              expire_seconds,
              create_times=create_times,
              cutoff_date=cutoff_date,
              strict_cutoff_date=strict_cutoff_date,
              filter_key_as_item=False,
5ab1c29c   tangwang   first commit
282
283
284
285
286
287
          )
          logger.info(f"Loaded {count} {list_type} indices")
  
  
  def main():
      parser = argparse.ArgumentParser(description='Load recommendation indices to Redis')
be9c0900   tangwang   之前多个任务,配置分散,进行集中管...
288
      parser.add_argument('--redis-host', type=str, default=REDIS_CONFIG['host'],
5ab1c29c   tangwang   first commit
289
                         help='Redis host')
be9c0900   tangwang   之前多个任务,配置分散,进行集中管...
290
      parser.add_argument('--redis-port', type=int, default=REDIS_CONFIG['port'],
5ab1c29c   tangwang   first commit
291
                         help='Redis port')
be9c0900   tangwang   之前多个任务,配置分散,进行集中管...
292
      parser.add_argument('--redis-db', type=int, default=REDIS_CONFIG['db'],
5ab1c29c   tangwang   first commit
293
                         help='Redis database')
be9c0900   tangwang   之前多个任务,配置分散,进行集中管...
294
      parser.add_argument('--redis-password', type=str, default=REDIS_CONFIG['password'],
5ab1c29c   tangwang   first commit
295
296
297
                         help='Redis password')
      parser.add_argument('--date', type=str, default=None,
                         help='Date string (YYYYMMDD), default is today')
8b9ea8ee   tangwang   feat(recommendati...
298
      parser.add_argument('--expire-days', type=int, default=60,
5ab1c29c   tangwang   first commit
299
300
301
302
303
304
305
                         help='Expire days for Redis keys')
      parser.add_argument('--load-i2i', action='store_true', default=True,
                         help='Load i2i indices')
      parser.add_argument('--load-interest', action='store_true', default=True,
                         help='Load interest indices')
      parser.add_argument('--flush-db', action='store_true',
                         help='Flush database before loading (危险操作!)')
8b9ea8ee   tangwang   feat(recommendati...
306
307
308
309
310
311
312
313
      parser.add_argument('--max-item-age-years', type=float,
                         default=ITEM_FRESHNESS_CONFIG['max_item_age_years'],
                         help='Skip items older than this many years when writing Redis (default 3)')
      parser.add_argument('--strict-item-age-years', type=float,
                         default=ITEM_FRESHNESS_CONFIG.get('strict_item_age_years', 2),
                         help='Category/region/platform dimension cutoff years (default 2)')
      parser.add_argument('--skip-freshness-filter', action='store_true',
                         help='Disable the item age filter while loading Redis')
5ab1c29c   tangwang   first commit
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
      
      args = parser.parse_args()
      
      # 创建Redis连接
      logger.info("Connecting to Redis...")
      redis_client = redis.Redis(
          host=args.redis_host,
          port=args.redis_port,
          db=args.redis_db,
          password=args.redis_password,
          decode_responses=True
      )
      
      # 测试连接
      try:
          redis_client.ping()
          logger.info("Redis connection successful")
      except Exception as e:
          logger.error(f"Failed to connect to Redis: {e}")
          return 1
      
      # Flush数据库(如果需要)
      if args.flush_db:
          logger.warning("Flushing Redis database...")
          redis_client.flushdb()
          logger.info("Database flushed")
      
8b9ea8ee   tangwang   feat(recommendati...
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
      create_times = None
      cutoff_date = None
      strict_cutoff_date = None
      if not args.skip_freshness_filter:
          create_times = load_item_create_times(logger=logger)
          cutoff_date = get_item_age_cutoff_date(args.max_item_age_years)
          strict_cutoff_date = get_item_age_cutoff_date(args.strict_item_age_years)
          if create_times:
              logger.info(
                  f"Redis freshness cutoff: default >= {cutoff_date} ({args.max_item_age_years} years); "
                  f"category/region/platform >= {strict_cutoff_date} ({args.strict_item_age_years} years)"
              )
          else:
              logger.warning("Item create times unavailable, Redis load will skip freshness filtering")
              create_times = None
              cutoff_date = None
              strict_cutoff_date = None
  
c0b24bef   tangwang   fix redis data
359
360
361
362
363
      # 加载C++ Swing索引
      if args.load_i2i:
          logger.info("\n" + "="*80)
          logger.info("Loading C++ Swing indices")
          logger.info("="*80)
8b9ea8ee   tangwang   feat(recommendati...
364
          load_cpp_swing_index(redis_client, args.expire_days, create_times, cutoff_date)
c0b24bef   tangwang   fix redis data
365
      
5ab1c29c   tangwang   first commit
366
367
368
369
370
      # 加载i2i索引
      if args.load_i2i:
          logger.info("\n" + "="*80)
          logger.info("Loading i2i indices")
          logger.info("="*80)
8b9ea8ee   tangwang   feat(recommendati...
371
          load_i2i_indices(redis_client, args.date, args.expire_days, create_times, cutoff_date)
5ab1c29c   tangwang   first commit
372
373
374
375
376
377
      
      # 加载兴趣点索引
      if args.load_interest:
          logger.info("\n" + "="*80)
          logger.info("Loading interest aggregation indices")
          logger.info("="*80)
8b9ea8ee   tangwang   feat(recommendati...
378
379
380
          load_interest_indices(
              redis_client, args.date, args.expire_days, create_times, cutoff_date, strict_cutoff_date
          )
5ab1c29c   tangwang   first commit
381
382
383
384
385
386
387
388
389
390
      
      logger.info("\n" + "="*80)
      logger.info("All indices loaded successfully!")
      logger.info("="*80)
      
      return 0
  
  
  if __name__ == '__main__':
      sys.exit(main())