-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathroute.ts
More file actions
247 lines (214 loc) Β· 8.43 KB
/
Copy pathroute.ts
File metadata and controls
247 lines (214 loc) Β· 8.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db/drizzle';
import { listings, images, listingsEnglish } from '@/lib/db/schema';
import { sql, eq, and, inArray } from 'drizzle-orm';
export async function GET(
request: NextRequest,
{ params }: { params: Promise<{ listingId: string }> }
) {
console.log('π [SimilarAPI] API route hit!');
try {
const { listingId } = await params;
console.log('π [SimilarAPI] Listing ID:', listingId);
if (!listingId) {
return NextResponse.json({ error: 'Listing ID is required' }, { status: 400 });
}
// First check if this listing has a vector in the hokkaido_lfm2_fused_mlp table
console.log('π [SimilarAPI] Looking for vector for listing ID:', listingId, 'type:', typeof listingId);
const vectorResult = await db.execute(
sql`SELECT id, vec FROM vecs.hokkaido_lfm2_fused_mlp WHERE id = ${listingId}`
);
console.log('π [SimilarAPI] Vector result length:', vectorResult.length || 0);
if (!vectorResult || vectorResult.length === 0) {
// If no vector exists for this listing, return empty results
return NextResponse.json({
listings: [],
message: 'No vector embedding available for this listing'
}, { status: 200 });
}
const vectorData = vectorResult[0] as any;
// Get the current listing's details for hybrid filtering
const currentListingResult = await db
.select({
lat: listings.lat,
lng: listings.lng,
price: listings.price
})
.from(listings)
.where(eq(listings.listingId, listingId))
.limit(1);
if (currentListingResult.length === 0) {
return NextResponse.json({
listings: [],
message: 'Current listing not found'
}, { status: 404 });
}
const currentListing = currentListingResult[0];
// Check if location data exists
if (!currentListing.lat || !currentListing.lng || !currentListing.price) {
return NextResponse.json({
listings: [],
message: 'Current listing missing required data (location or price)'
}, { status: 400 });
}
const priceRange = {
min: currentListing.price * 0.5, // -50% (more flexible)
max: currentListing.price * 2.0 // +100% (more flexible)
};
const locationRange = {
latMin: currentListing.lat - 0.2, // ~5km (wider area)
latMax: currentListing.lat + 0.2,
lngMin: currentListing.lng - 0.2,
lngMax: currentListing.lng + 0.2
};
// Debug logging
console.log('π [HybridSearch] Current listing:', {
id: listingId,
lat: currentListing.lat,
lng: currentListing.lng,
price: currentListing.price
});
console.log('π [HybridSearch] Search ranges:', { priceRange, locationRange });
// Step 1: Apply location and price filters FIRST (hard filters)
const locationPriceFiltered = await db
.select({
listingId: listings.listingId,
lat: listings.lat,
lng: listings.lng,
price: listings.price
})
.from(listings)
.where(
and(
sql`${listings.lat} BETWEEN ${locationRange.latMin} AND ${locationRange.latMax}`,
sql`${listings.lng} BETWEEN ${locationRange.lngMin} AND ${locationRange.lngMax}`,
sql`${listings.price} BETWEEN ${priceRange.min} AND ${priceRange.max}`,
eq(listings.isActive, true),
sql`${listings.listingId} != ${listingId}`
)
);
console.log('π [HybridSearch] Location+Price filtered candidates:', locationPriceFiltered.length);
if (locationPriceFiltered.length === 0) {
console.log('π [HybridSearch] No candidates after location+price filtering');
}
// Step 2: For the location+price filtered results, check which have vectors and rank by similarity
const candidateIds = locationPriceFiltered.map(l => l.listingId);
let similarResult = null;
if (candidateIds.length > 0) {
// Use the original function but filter the results to only include our candidates
const allVectorResults = await db.execute(
sql`SELECT * FROM match_listings_hokkaido_lfm2(${vectorData.vec}::vector, 0.5, 100)`
);
// Filter to only candidates that passed location+price filters
const candidateSet = new Set(candidateIds);
similarResult = (allVectorResults as any[])
.filter((result: any) => candidateSet.has(result.id) && result.id !== listingId)
.slice(0, 6);
console.log('π [HybridSearch] Filtered vector results to candidates:', similarResult.length);
}
console.log('π [HybridSearch] Initial results:', similarResult?.length || 0);
// Only use results that passed location+price filters - NO fallback to unrestricted vector search
const finalResult = similarResult;
if (!finalResult || finalResult.length === 0) {
return NextResponse.json({
listings: [],
message: 'No similar listings found'
}, { status: 200 });
}
// Extract listing IDs from results
const similarListingIds = (finalResult as any[])
.slice(0, 5) // Take only 5 similar listings
.map((v: any) => v.id);
if (similarListingIds.length === 0) {
return NextResponse.json({
listings: [],
message: 'No similar listings found'
}, { status: 200 });
}
// Fetch full listing details for similar listings using Drizzle
const similarListings = await db
.select({
listingId: listings.listingId,
title: listings.title,
price: listings.price,
previousPrice: listings.previousPrice,
location: listings.location,
sizeSqm: listings.sizeSqm,
rooms: listings.rooms,
yearBuilt: listings.yearBuilt,
listingType: listings.listingType,
listingTypeEn: listings.listingTypeEn,
listingUrl: listings.listingUrl,
firstSeen: listings.firstSeen,
lastSeen: listings.lastSeen,
lat: listings.lat,
lng: listings.lng,
titleEnglish: listingsEnglish.titleEnglish,
locationEnglish: listingsEnglish.locationEnglish,
imageId: images.id,
imageSourceUrl: images.sourceUrl,
imageIsMain: images.isMain,
imageCloudfrontUrl: images.cloudfrontUrl,
imageS3Key: images.s3Key,
imageS3BucketName: images.s3BucketName,
})
.from(listings)
.leftJoin(listingsEnglish, eq(listings.listingId, listingsEnglish.listingId))
.leftJoin(images, eq(listings.listingId, images.listingId))
.where(
and(
inArray(listings.listingId, similarListingIds),
eq(listings.isActive, true)
)
)
.orderBy(listings.price);
// Transform the flat results into grouped listing objects with images
const listingMap = new Map<string, any>();
for (const row of similarListings) {
if (!listingMap.has(row.listingId)) {
listingMap.set(row.listingId, {
listingId: row.listingId,
title: row.title,
titleEnglish: row.titleEnglish,
price: parseFloat(row.price?.toString() || '0'),
previousPrice: row.previousPrice ? parseFloat(row.previousPrice.toString()) : null,
location: row.location,
locationEnglish: row.locationEnglish,
sizeSqm: parseFloat(row.sizeSqm?.toString() || '0'),
rooms: row.rooms,
yearBuilt: row.yearBuilt,
listingType: row.listingType,
listingTypeEn: row.listingTypeEn,
listingUrl: row.listingUrl,
firstSeen: row.firstSeen,
lastSeen: row.lastSeen,
lat: row.lat,
lng: row.lng,
images: []
});
}
// Add image if it exists
if (row.imageId) {
listingMap.get(row.listingId).images.push({
id: row.imageId,
sourceUrl: row.imageSourceUrl,
isMain: row.imageIsMain,
cloudfrontUrl: row.imageCloudfrontUrl,
s3Key: row.imageS3Key,
s3BucketName: row.imageS3BucketName
});
}
}
const transformedListings = Array.from(listingMap.values());
return NextResponse.json({
listings: transformedListings,
count: transformedListings.length
});
} catch (error) {
console.error('Error in similar listings API:', error);
return NextResponse.json({
error: 'Internal server error',
details: error instanceof Error ? error.message : 'Unknown error'
}, { status: 500 });
}
}