Predictive search

Hello everyone,

I have written a code for predictive search where I pass a tag, and it retrieves all the products in the store that contain that tag. However, now I want the search to look for the specified tag only within the products of a specific collection, not the entire store.

Can anyone help with this

Here is my code.

document.addEventListener(“DOMContentLoaded”, function () {
console.log(“Page has been loaded!”);

// Step 1: Fetch value from localStorage
const savedValue = localStorage.getItem(“selectedCity”);
if (!savedValue) {
console.warn(“No value found in localStorage for ‘searchTag’.”);
return;
}

console.log(“Searching for products with tag:”, savedValue);

// Step 2: Call Shopify Predictive Search API
fetch(
https://${window.location.hostname}/search/suggest.json?q=${encodeURIComponent(savedValue)}&resources[type]=product&resources[options][fields]=tag
)
.then((response) => {
if (!response.ok) {
throw new Error(HTTP error! status: ${response.status});
}
return response.json(); // Parse JSON response
})
.then((data) => {
// Step 3: Filter products with the matching tag
const products = data.resources.results.products || ;
const matchingProducts = products.filter((product) =>
product.tags.includes(savedValue) // Check if the product’s tags include the saved value
);

console.log(“Matching products:”, matchingProducts);

if (matchingProducts.length > 0) {
// Display matching products
matchingProducts.forEach((product) => {
console.log(Product Name: ${product.title});
console.log(Product Name: ${product.tag});
});
} else {
console.log(“No products found with the given tag.”);
}
})
.catch((error) => {
console.error(“Error fetching predictive search:”, error);
});
});

Hi [email removed]

To modify your code to search for the specified tag only within products of a specific collection, you’ll need to adjust your current approach. The current code retrieves products from the entire store, but you want to narrow down the search to products in a specific collection.

Approach:1. Get the collection’s ID or handle.

  1. Modify the API request to filter by collection in addition to the tag.
  2. Alternatively, if the Shopify Predictive Search API doesn’t allow collection filtering, you can first retrieve the products of the specific collection and then filter those by the tag.

Solution 1: Fetch Products From a Specific Collection and Filter by Tag

Since the Shopify Predictive Search API does not support searching within a specific collection directly, we’ll need to fetch all the products from a specific collection first, then filter them by the tag.

Here’s the updated code with these steps:

document.addEventListener("DOMContentLoaded", function () {
    console.log("Page has been loaded!");

    // Step 1: Fetch value from localStorage
    const savedValue = localStorage.getItem("selectedCity");
    const collectionHandle = "your-collection-handle";  // Specify the handle of the collection you want to search in

    if (!savedValue) {
        console.warn("No value found in localStorage for 'searchTag'.");
        return;
    }

    console.log("Searching for products with tag:", savedValue);

    // Step 2: Fetch products from a specific collection using the Shopify API
    fetch(
        `https://${window.location.hostname}/collections/${collectionHandle}/products.json`
    )
    .then((response) => {
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json(); // Parse JSON response
    })
    .then((data) => {
        // Step 3: Filter products within the collection with the matching tag
        const products = data.products || [];
        const matchingProducts = products.filter((product) =>
            product.tags.includes(savedValue) // Check if the product's tags include the saved value
        );

        console.log("Matching products:", matchingProducts);

        if (matchingProducts.length > 0) {
            // Display matching products
            matchingProducts.forEach((product) => {
                console.log(`Product Name: ${product.title}`);
                console.log(`Product Tags: ${product.tags}`);
            });
        } else {
            console.log("No products found with the given tag in this collection.");
        }
    })
    .catch((error) => {
        console.error("Error fetching products:", error);
    });
});

To modify your code to search for the specified tag only within products of a specific collection, you’ll need to adjust your current approach. The current code retrieves products from the entire store, but you want to narrow down the search to products in a specific collection.

Approach:1. Get the collection’s ID or handle.

  1. Modify the API request to filter by collection in addition to the tag.
  2. Alternatively, if the Shopify Predictive Search API doesn’t allow collection filtering, you can first retrieve the products of the specific collection and then filter those by the tag.

Solution 1: Fetch Products From a Specific Collection and Filter by Tag

Since the Shopify Predictive Search API does not support searching within a specific collection directly, we’ll need to fetch all the products from a specific collection first, then filter them by the tag.

Here’s the updated code with these steps:

Updated Code:

javascript

Copy code

document.addEventListener(“DOMContentLoaded”, function () { console.log(“Page has been loaded!”); // Step 1: Fetch value from localStorage const savedValue = localStorage.getItem(“selectedCity”); const collectionHandle = “your-collection-handle”; // Specify the handle of the collection you want to search in if (!savedValue) { console.warn(“No value found in localStorage for ‘searchTag’.”); return; } console.log(“Searching for products with tag:”, savedValue); // Step 2: Fetch products from a specific collection using the Shopify API fetch( https://${window.location.hostname}/collections/${collectionHandle}/products.json ) .then((response) => { if (!response.ok) { throw new Error(HTTP error! status: ${response.status}); } return response.json(); // Parse JSON response }) .then((data) => { // Step 3: Filter products within the collection with the matching tag const products = data.products || ; const matchingProducts = products.filter((product) => product.tags.includes(savedValue) // Check if the product’s tags include the saved value ); console.log(“Matching products:”, matchingProducts); if (matchingProducts.length > 0) { // Display matching products matchingProducts.forEach((product) => { console.log(Product Name: ${product.title}); console.log(Product Tags: ${product.tags}); }); } else { console.log(“No products found with the given tag in this collection.”); } }) .catch((error) => { console.error(“Error fetching products:”, error); }); });

Key Modifications:1. Collection Handle: Add the collection handle (e.g., your-collection-handle). This will allow you to limit the search to only the products in that specific collection.

  1. API Request: The new endpoint https://${window.location.hostname}/collections/${collectionHandle}/products.json fetches all products from the specified collection.

  2. Filtering by Tag: After fetching the products in that collection, we filter the products by checking if the tags array includes the savedValue tag.

I need to check it while staying on the homepage, and I want to use predictive search. This is not the correct way, and it is also working correctly.

Let me know if you need further refinements!