5ab1c29c
tangwang
first commit
|
1
|
"""
|
b57c6eb4
tangwang
offline tasks: fi...
|
2
3
4
5
|
i2i - 基于ES向量的内容相似索引
从Elasticsearch获取商品向量,计算两种相似度:
1. 基于名称文本向量的相似度
2. 基于图片向量的相似度
|
5ab1c29c
tangwang
first commit
|
6
7
8
9
10
|
"""
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
|
b57c6eb4
tangwang
offline tasks: fi...
|
11
|
import json
|
5ab1c29c
tangwang
first commit
|
12
|
import pandas as pd
|
b57c6eb4
tangwang
offline tasks: fi...
|
13
14
|
from datetime import datetime, timedelta
from elasticsearch import Elasticsearch
|
5ab1c29c
tangwang
first commit
|
15
|
from db_service import create_db_connection
|
b57c6eb4
tangwang
offline tasks: fi...
|
16
17
|
from offline_tasks.config.offline_config import DB_CONFIG, OUTPUT_DIR
from offline_tasks.scripts.debug_utils import setup_debug_logger, log_processing_step
|
5ab1c29c
tangwang
first commit
|
18
|
|
b57c6eb4
tangwang
offline tasks: fi...
|
19
20
21
22
23
24
25
|
# ES配置
ES_CONFIG = {
'host': 'http://localhost:9200',
'index_name': 'spu',
'username': 'essa',
'password': '4hOaLaf41y2VuI8y'
}
|
5ab1c29c
tangwang
first commit
|
26
|
|
b57c6eb4
tangwang
offline tasks: fi...
|
27
28
29
30
31
32
33
|
# 算法参数
TOP_N = 50 # 每个商品返回的相似商品数量
KNN_K = 100 # knn查询返回的候选数
KNN_CANDIDATES = 200 # knn查询的候选池大小
def get_active_items(engine):
|
5ab1c29c
tangwang
first commit
|
34
|
"""
|
b57c6eb4
tangwang
offline tasks: fi...
|
35
|
获取最近1年有过行为的item列表
|
5ab1c29c
tangwang
first commit
|
36
|
"""
|
b57c6eb4
tangwang
offline tasks: fi...
|
37
38
39
40
41
42
43
44
45
46
47
|
one_year_ago = (datetime.now() - timedelta(days=365)).strftime('%Y-%m-%d')
sql_query = f"""
SELECT DISTINCT
se.item_id
FROM
sensors_events se
WHERE
se.event IN ('click', 'contactFactory', 'addToPool', 'addToCart', 'purchase')
AND se.create_time >= '{one_year_ago}'
AND se.item_id IS NOT NULL
|
5ab1c29c
tangwang
first commit
|
48
49
|
"""
|
5ab1c29c
tangwang
first commit
|
50
|
df = pd.read_sql(sql_query, engine)
|
b57c6eb4
tangwang
offline tasks: fi...
|
51
|
return df['item_id'].tolist()
|
5ab1c29c
tangwang
first commit
|
52
53
|
|
b57c6eb4
tangwang
offline tasks: fi...
|
54
55
56
57
58
59
60
61
62
63
64
65
|
def connect_es():
"""连接到Elasticsearch"""
es = Elasticsearch(
[ES_CONFIG['host']],
basic_auth=(ES_CONFIG['username'], ES_CONFIG['password']),
verify_certs=False,
request_timeout=30
)
return es
def get_item_vectors(es, item_id):
|
5ab1c29c
tangwang
first commit
|
66
|
"""
|
b57c6eb4
tangwang
offline tasks: fi...
|
67
|
从ES获取商品的向量数据
|
5ab1c29c
tangwang
first commit
|
68
|
|
b57c6eb4
tangwang
offline tasks: fi...
|
69
|
Returns:
|
fb8112e0
tangwang
offline tasks: me...
|
70
|
dict with keys: _id, name_zh, embedding_name_zh, embedding_pic_h14, on_sell_days_boost
|
b57c6eb4
tangwang
offline tasks: fi...
|
71
72
73
74
75
76
77
78
79
80
81
82
|
或 None if not found
"""
try:
response = es.search(
index=ES_CONFIG['index_name'],
body={
"query": {
"term": {
"_id": str(item_id)
}
},
"_source": {
|
fb8112e0
tangwang
offline tasks: me...
|
83
|
"includes": ["_id", "name_zh", "embedding_name_zh", "embedding_pic_h14", "on_sell_days_boost"]
|
b57c6eb4
tangwang
offline tasks: fi...
|
84
85
86
87
88
89
90
91
92
93
|
}
}
)
if response['hits']['hits']:
hit = response['hits']['hits'][0]
return {
'_id': hit['_id'],
'name_zh': hit['_source'].get('name_zh', ''),
'embedding_name_zh': hit['_source'].get('embedding_name_zh'),
|
fb8112e0
tangwang
offline tasks: me...
|
94
95
|
'embedding_pic_h14': hit['_source'].get('embedding_pic_h14'),
'on_sell_days_boost': hit['_source'].get('on_sell_days_boost', 1.0)
|
b57c6eb4
tangwang
offline tasks: fi...
|
96
97
98
99
|
}
return None
except Exception as e:
return None
|
5ab1c29c
tangwang
first commit
|
100
101
|
|
b57c6eb4
tangwang
offline tasks: fi...
|
102
|
def find_similar_by_vector(es, vector, field_name, k=KNN_K, num_candidates=KNN_CANDIDATES):
|
5ab1c29c
tangwang
first commit
|
103
|
"""
|
b57c6eb4
tangwang
offline tasks: fi...
|
104
|
使用knn查询找到相似的items
|
40442baf
tangwang
offline tasks: fi...
|
105
|
|
b57c6eb4
tangwang
offline tasks: fi...
|
106
107
108
109
110
111
|
Args:
es: Elasticsearch客户端
vector: 查询向量
field_name: 向量字段名 (embedding_name_zh 或 embedding_pic_h14.vector)
k: 返回的结果数
num_candidates: 候选池大小
|
5ab1c29c
tangwang
first commit
|
112
|
|
b57c6eb4
tangwang
offline tasks: fi...
|
113
|
Returns:
|
fb8112e0
tangwang
offline tasks: me...
|
114
|
List of (item_id, boosted_score, name_zh) tuples
|
b57c6eb4
tangwang
offline tasks: fi...
|
115
116
117
118
119
120
121
122
123
124
125
|
"""
try:
response = es.search(
index=ES_CONFIG['index_name'],
body={
"knn": {
"field": field_name,
"query_vector": vector,
"k": k,
"num_candidates": num_candidates
},
|
fb8112e0
tangwang
offline tasks: me...
|
126
|
"_source": ["_id", "name_zh", "on_sell_days_boost"],
|
b57c6eb4
tangwang
offline tasks: fi...
|
127
128
129
|
"size": k
}
)
|
5ab1c29c
tangwang
first commit
|
130
|
|
b57c6eb4
tangwang
offline tasks: fi...
|
131
132
|
results = []
for hit in response['hits']['hits']:
|
fb8112e0
tangwang
offline tasks: me...
|
133
134
135
136
137
138
139
140
141
142
143
144
145
|
# 获取基础分数
base_score = hit['_score']
# 获取on_sell_days_boost提权值,默认为1.0(不提权)
boost = hit['_source'].get('on_sell_days_boost', 1.0)
# 确保boost在合理范围内
if boost is None or boost < 0.9 or boost > 1.1:
boost = 1.0
# 应用提权
boosted_score = base_score * boost
|
b57c6eb4
tangwang
offline tasks: fi...
|
146
147
|
results.append((
hit['_id'],
|
fb8112e0
tangwang
offline tasks: me...
|
148
|
boosted_score,
|
b57c6eb4
tangwang
offline tasks: fi...
|
149
150
151
152
153
|
hit['_source'].get('name_zh', '')
))
return results
except Exception as e:
return []
|
5ab1c29c
tangwang
first commit
|
154
155
|
|
b57c6eb4
tangwang
offline tasks: fi...
|
156
|
def generate_similarity_index(es, active_items, vector_field, field_name, logger):
|
5ab1c29c
tangwang
first commit
|
157
|
"""
|
b57c6eb4
tangwang
offline tasks: fi...
|
158
159
160
161
162
163
164
165
166
167
168
|
生成一种向量的相似度索引
Args:
es: Elasticsearch客户端
active_items: 活跃商品ID列表
vector_field: 向量字段名 (embedding_name_zh 或 embedding_pic_h14)
field_name: 字段简称 (name 或 pic)
logger: 日志记录器
Returns:
dict: {item_id: [(similar_id, score, name), ...]}
|
5ab1c29c
tangwang
first commit
|
169
|
"""
|
b57c6eb4
tangwang
offline tasks: fi...
|
170
171
|
result = {}
total = len(active_items)
|
5ab1c29c
tangwang
first commit
|
172
|
|
b57c6eb4
tangwang
offline tasks: fi...
|
173
174
175
176
177
178
179
|
for idx, item_id in enumerate(active_items):
if (idx + 1) % 100 == 0:
logger.info(f"处理进度: {idx + 1}/{total} ({(idx + 1) / total * 100:.1f}%)")
# 获取该商品的向量
item_data = get_item_vectors(es, item_id)
if not item_data:
|
5ab1c29c
tangwang
first commit
|
180
181
|
continue
|
b57c6eb4
tangwang
offline tasks: fi...
|
182
183
184
185
186
187
188
189
190
191
192
193
194
|
# 提取向量
if vector_field == 'embedding_name_zh':
query_vector = item_data.get('embedding_name_zh')
elif vector_field == 'embedding_pic_h14':
pic_data = item_data.get('embedding_pic_h14')
if pic_data and isinstance(pic_data, list) and len(pic_data) > 0:
query_vector = pic_data[0].get('vector') if isinstance(pic_data[0], dict) else None
else:
query_vector = None
else:
query_vector = None
if not query_vector:
|
5ab1c29c
tangwang
first commit
|
195
196
|
continue
|
b57c6eb4
tangwang
offline tasks: fi...
|
197
198
199
200
201
|
# 使用knn查询相似items(需要排除自己)
knn_field = f"{vector_field}.vector" if vector_field == 'embedding_pic_h14' else vector_field
similar_items = find_similar_by_vector(es, query_vector, knn_field)
# 过滤掉自己,只保留top N
|
fb8112e0
tangwang
offline tasks: me...
|
202
|
# 注意:分数已经在find_similar_by_vector中应用了on_sell_days_boost提权
|
b57c6eb4
tangwang
offline tasks: fi...
|
203
|
filtered_items = []
|
fb8112e0
tangwang
offline tasks: me...
|
204
|
for sim_id, boosted_score, name in similar_items:
|
b57c6eb4
tangwang
offline tasks: fi...
|
205
|
if sim_id != str(item_id):
|
fb8112e0
tangwang
offline tasks: me...
|
206
|
filtered_items.append((sim_id, boosted_score, name))
|
b57c6eb4
tangwang
offline tasks: fi...
|
207
208
209
210
211
|
if len(filtered_items) >= TOP_N:
break
if filtered_items:
result[item_id] = filtered_items
|
5ab1c29c
tangwang
first commit
|
212
213
214
215
|
return result
|
b57c6eb4
tangwang
offline tasks: fi...
|
216
|
def save_index_file(result, es, output_file, logger):
|
5ab1c29c
tangwang
first commit
|
217
|
"""
|
b57c6eb4
tangwang
offline tasks: fi...
|
218
219
220
|
保存索引文件
格式: item_id \t item_name \t similar_id1:score1,similar_id2:score2,...
|
5ab1c29c
tangwang
first commit
|
221
|
"""
|
b57c6eb4
tangwang
offline tasks: fi...
|
222
|
logger.info(f"保存索引到: {output_file}")
|
5ab1c29c
tangwang
first commit
|
223
|
|
b57c6eb4
tangwang
offline tasks: fi...
|
224
225
226
227
228
229
230
231
232
233
234
235
|
with open(output_file, 'w', encoding='utf-8') as f:
for item_id, similar_items in result.items():
if not similar_items:
continue
# 获取当前商品的名称
item_data = get_item_vectors(es, item_id)
item_name = item_data.get('name_zh', 'Unknown') if item_data else 'Unknown'
# 格式化相似商品列表
sim_str = ','.join([f'{sim_id}:{score:.4f}' for sim_id, score, _ in similar_items])
f.write(f'{item_id}\t{item_name}\t{sim_str}\n')
|
5ab1c29c
tangwang
first commit
|
236
|
|
b57c6eb4
tangwang
offline tasks: fi...
|
237
|
logger.info(f"索引保存完成,共 {len(result)} 个商品")
|
5ab1c29c
tangwang
first commit
|
238
239
240
|
def main():
|
b57c6eb4
tangwang
offline tasks: fi...
|
241
|
"""主函数"""
|
14f3dcbe
tangwang
offline tasks
|
242
|
# 设置logger
|
b57c6eb4
tangwang
offline tasks: fi...
|
243
|
logger = setup_debug_logger('i2i_content_similar', debug=True)
|
14f3dcbe
tangwang
offline tasks
|
244
|
|
b57c6eb4
tangwang
offline tasks: fi...
|
245
246
247
248
249
250
|
logger.info("="*80)
logger.info("开始生成基于ES向量的内容相似索引")
logger.info(f"ES地址: {ES_CONFIG['host']}")
logger.info(f"索引名: {ES_CONFIG['index_name']}")
logger.info(f"Top N: {TOP_N}")
logger.info("="*80)
|
14f3dcbe
tangwang
offline tasks
|
251
|
|
5ab1c29c
tangwang
first commit
|
252
|
# 创建数据库连接
|
b57c6eb4
tangwang
offline tasks: fi...
|
253
|
log_processing_step(logger, "连接数据库")
|
5ab1c29c
tangwang
first commit
|
254
255
256
257
258
259
260
261
|
engine = create_db_connection(
DB_CONFIG['host'],
DB_CONFIG['port'],
DB_CONFIG['database'],
DB_CONFIG['username'],
DB_CONFIG['password']
)
|
b57c6eb4
tangwang
offline tasks: fi...
|
262
263
264
265
|
# 获取活跃商品
log_processing_step(logger, "获取最近1年有过行为的商品")
active_items = get_active_items(engine)
logger.info(f"找到 {len(active_items)} 个活跃商品")
|
5ab1c29c
tangwang
first commit
|
266
|
|
b57c6eb4
tangwang
offline tasks: fi...
|
267
268
269
270
|
# 连接ES
log_processing_step(logger, "连接Elasticsearch")
es = connect_es()
logger.info("ES连接成功")
|
5ab1c29c
tangwang
first commit
|
271
|
|
b57c6eb4
tangwang
offline tasks: fi...
|
272
273
|
# 生成两份相似度索引
date_str = datetime.now().strftime("%Y%m%d")
|
5ab1c29c
tangwang
first commit
|
274
|
|
b57c6eb4
tangwang
offline tasks: fi...
|
275
276
277
278
|
# 1. 基于名称文本向量
log_processing_step(logger, "生成基于名称文本向量的相似索引")
name_result = generate_similarity_index(
es, active_items, 'embedding_name_zh', 'name', logger
|
5ab1c29c
tangwang
first commit
|
279
|
)
|
b57c6eb4
tangwang
offline tasks: fi...
|
280
281
|
name_output = os.path.join(OUTPUT_DIR, f'i2i_content_name_{date_str}.txt')
save_index_file(name_result, es, name_output, logger)
|
5ab1c29c
tangwang
first commit
|
282
|
|
b57c6eb4
tangwang
offline tasks: fi...
|
283
284
285
286
287
288
289
|
# 2. 基于图片向量
log_processing_step(logger, "生成基于图片向量的相似索引")
pic_result = generate_similarity_index(
es, active_items, 'embedding_pic_h14', 'pic', logger
)
pic_output = os.path.join(OUTPUT_DIR, f'i2i_content_pic_{date_str}.txt')
save_index_file(pic_result, es, pic_output, logger)
|
14f3dcbe
tangwang
offline tasks
|
290
|
|
b57c6eb4
tangwang
offline tasks: fi...
|
291
292
293
294
295
|
logger.info("="*80)
logger.info("完成!生成了两份内容相似索引:")
logger.info(f" 1. 名称向量索引: {name_output} ({len(name_result)} 个商品)")
logger.info(f" 2. 图片向量索引: {pic_output} ({len(pic_result)} 个商品)")
logger.info("="*80)
|
5ab1c29c
tangwang
first commit
|
296
297
298
299
|
if __name__ == '__main__':
main()
|