I am trying to create a search function which can also show related searches. For example. If I try to search 'trees' then it must find me all the rows which contains trees. and which I mistype it then too it must show me some results. For example. 'treesabc' then too it must show me some results. For now I am using Like method which satisfies my first need but it does works when entered addition letters.
So here is my code.
exports.quickSearch = async (req, res) => {
let services = [];
// finding all services which matches the condition
let serviceData = await Service.findAll({
limit: 300, // limiting the number of search
where: {
// here i want to to do something which can also show related searches
[Op.or]: [
{
service_name: sequelize.where(
sequelize.fn("LOWER", sequelize.col("service_name")),
"LIKE",
"%" + req.params.keyword.toLowerCase() + "%",
),
},
{
category: sequelize.where(
sequelize.fn("LOWER", sequelize.col("category")),
"LIKE",
"%" + req.params.keyword.toLowerCase() + "%",
),
},
{
sub_category: sequelize.where(
sequelize.fn("LOWER", sequelize.col("sub_category")),
"LIKE",
"%" + req.params.keyword.toLowerCase() + "%",
),
},
{
master_category: sequelize.where(
sequelize.fn("LOWER", sequelize.col("master_category")),
"LIKE",
"%" + req.params.keyword.toLowerCase() + "%",
),
},
{
gender: sequelize.where(
sequelize.fn("LOWER", sequelize.col("gender")),
"LIKE",
"%" + req.params.keyword.toLowerCase() + "%",
),
},
],
},
});
// custom function asyncForEach
const asyncForEach = async (array, callback) => {
for (let i = 0; i < array.length; i++) {
await callback(array[i]);
}
};
await asyncForEach(serviceData, async (service) => {
// trying to find all te partner which has service_id
let partnerData = await Partner.findOne({
where: {
partner_id: service.partner_id,
banned: false,
},
raw: true,
});
if (partnerData) {
// inserting partners data in service
partnerData.password = null;
service.dataValues.outletdata = partnerData;
services.push(service);
}
});
return res
.status(200)
.json({ message: "Success", services});
};
Try with Op.like:
Example:
queryParams.where = {
[Op.or]: [
Sequelize.where(Sequelize.fn('lower', Sequelize.col('t_device.name')), {
[Op.like]: `%${optionsWithDefault.search}%`,
}),
Sequelize.where(Sequelize.fn('lower', Sequelize.col('t_device.external_id')), {
[Op.like]: `%${optionsWithDefault.search}%`,
}),
Reference Link : https://www.tabnine.com/code/javascript/functions/sequelize/SequelizeStatic/fn