improved search by ranking results based on how early search terms appear in captions

This commit is contained in:
Henry Hobbs 2024-05-25 14:11:04 -04:00
parent 19cdff0c6b
commit b0ee3a69f1
2 changed files with 20 additions and 9 deletions

View File

@ -14,14 +14,24 @@ export async function GET(request: NextRequest) {
console.log(search) console.log(search)
const cleanedSearch = search.replace(/[^a-zA-Z\s]/g, "").toLowerCase() const cleanedSearch = search.replace(/[^a-zA-Z\s]/g, "").toLowerCase()
const searchWords = cleanedSearch.split(/\s+/) const searchWords = cleanedSearch.split(/\s+/)
const filteredData = cardData.filter((card) => const filteredData = cardData.filter((card) => {
searchWords.some((word) => let captionArray = card.caption?.toLowerCase().split(/[^a-z]/)
card.caption if (!captionArray) {
?.toLowerCase() return false
.split(/[^a-z]/) }
.includes(word) const words = searchWords.filter((word) => captionArray.includes(word))
) if (words.length) {
) card.rank = 999999
for (const word of words) {
const index = captionArray.indexOf(word)
if (index && index < card.rank) {
card.rank = index
}
}
return true
}
return false
})
filteredData.sort((a, b) => a.rank! - b.rank!)
return Response.json(filteredData) return Response.json(filteredData)
} }

View File

@ -5,5 +5,6 @@ export type CardType = {
oracleId: string oracleId: string
caption: string caption: string
url?: string url?: string
rank?: number
mediumImageUrl: string mediumImageUrl: string
} }