Skip to content

Commit

Permalink
improve search a lot
Browse files Browse the repository at this point in the history
  • Loading branch information
ethanniser committed Oct 18, 2024
1 parent 423156e commit c6d16a8
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 19 deletions.
1 change: 1 addition & 0 deletions src/components/search-dropdown.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ export function SearchDropdownComponent() {
useEffect(() => {
const search = async () => {
const results = await searchProducts(searchTerm);
console.log(results);
setFilteredItems(results);
};

Expand Down
67 changes: 48 additions & 19 deletions src/lib/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,25 +61,54 @@ export async function removeFromCart(formData: FormData) {
}

export async function searchProducts(searchTerm: string) {
const results = await db
.select()
.from(products)
.where(
sql`to_tsvector('english', ${products.name}) @@ plainto_tsquery('english', ${searchTerm})`,
)
.limit(5)
.innerJoin(
subcategories,
sql`${products.subcategory_slug} = ${subcategories.slug}`,
)
.innerJoin(
subcollection,
sql`${subcategories.subcollection_id} = ${subcollection.id}`,
)
.innerJoin(
categories,
sql`${subcollection.category_slug} = ${categories.slug}`,
);
let results;

if (searchTerm.length <= 2) {
// If the search term is short (e.g., "W"), use ILIKE for prefix matching
results = await db
.select()
.from(products)
.where(sql`${products.name} ILIKE ${searchTerm + "%"}`) // Prefix match
.limit(5)
.innerJoin(
subcategories,
sql`${products.subcategory_slug} = ${subcategories.slug}`,
)
.innerJoin(
subcollection,
sql`${subcategories.subcollection_id} = ${subcollection.id}`,
)
.innerJoin(
categories,
sql`${subcollection.category_slug} = ${categories.slug}`,
);
} else {
// For longer search terms, use full-text search with tsquery
const formattedSearchTerm = searchTerm
.split(" ")
.map((term) => `${term}:*`)
.join(" & ");

results = await db
.select()
.from(products)
.where(
sql`to_tsvector('english', ${products.name}) @@ to_tsquery('english', ${formattedSearchTerm})`,
)
.limit(5)
.innerJoin(
subcategories,
sql`${products.subcategory_slug} = ${subcategories.slug}`,
)
.innerJoin(
subcollection,
sql`${subcategories.subcollection_id} = ${subcollection.id}`,
)
.innerJoin(
categories,
sql`${subcollection.category_slug} = ${categories.slug}`,
);
}

return results.map((item) => {
const href = `/products/${item.categories.slug}/${item.subcategories.slug}/${item.products.slug}`;
Expand Down

0 comments on commit c6d16a8

Please sign in to comment.