Entity Extraction and Combination from Search Query

For the following inputs in form of 4 json files:

  • brands: https://pastebin.com/J20iJiik
    [
        {"id": 1, "name": "Costa Coffee"},
        {"id": 2, "name": "Greggs"},
        {"id": 3, "name": "Subway"},
        ...
    ]
  • cities: https://pastebin.com/9i0hpwjU
[
    {"id": 1, "name": "London"},
    {"id": 2, "name": "Birmingham"},
    {"id": 3, "name": "Glasgow"},
    ...
]
  • diets: https://pastebin.com/reJRXbRu
[
    {"id": 1, "name": "Vegan"},
    {"id": 2, "name": "Vegetarian"},
    {"id": 3, "name": "Pescatarian"},
    ...
]
  • dish-types: https://pastebin.com/eqGD1QnF
[
    {"id": 1, "name": "Meats"},
    {"id": 2, "name": "Lamb"},
    {"id": 3, "name": "Kofte"},
    ...
]

and this is the code that consumes it:

import * as fs from 'fs';

interface Entity {
    id: number;
    name: string;
}

interface Entities {
    cities: Entity[];
    brands: Entity[];
    dish_types: Entity[];
    diets: Entity[];
}

function readJsonFile(filename: string): Entity[] {
    const rawData = fs.readFileSync(filename);
    return JSON.parse(rawData.toString());
}

function loadEntitiesFromJson(): Entities {
    return {
        cities: readJsonFile('./src/data/cities.json'),
        brands: readJsonFile('./src/data/brands.json'),
        dish_types: readJsonFile('./src/data/dish-types.json'),
        diets: readJsonFile('./src/data/diets.json'),
    };
}

async function extractEntities(searchTerm: string): Promise<object[]> {
    const matchedEntities = loadEntitiesFromJson();
    const results: object[] = [];
    const searchTokens = searchTerm.toLowerCase().split(' in ');

    const mainQuery = searchTokens[0];
    const cityName = searchTokens[1];

    const filteredCities = cityName ? matchedEntities.cities.filter(city => city.name.toLowerCase() === cityName) : [];
    const filteredBrands = matchedEntities.brands.filter(brand => mainQuery.includes(brand.name.toLowerCase()));
    const filteredDiets = matchedEntities.diets.filter(diet => mainQuery.includes(diet.name.toLowerCase()));
    const filteredDishTypes = matchedEntities.dish_types.filter(dishType => mainQuery.includes(dishType.name.toLowerCase()));

    const uniqueResults = new Set<object>();

    if (filteredCities.length === 0) {
        for (const brand of filteredBrands) {
            uniqueResults.add({ brand });
        }
        for (const diet of filteredDiets) {
            for (const dishType of filteredDishTypes) {
                uniqueResults.add({ diet, dishType });
            }
        }
    } else {
        for (const city of filteredCities) {
            if (filteredDiets.length > 0 && filteredDishTypes.length > 0) {
                for (const diet of filteredDiets) {
                    for (const dishType of filteredDishTypes) {
                        uniqueResults.add({ city, diet, dishType });
                    }
                }
            }
            if (filteredDiets.length > 0 && filteredBrands.length > 0) {
                for (const diet of filteredDiets) {
                    for (const brand of filteredBrands) {
                        uniqueResults.add({ city, diet, brand });
                    }
                }
            }
            if (filteredDiets.length === 0 && filteredDishTypes.length > 0) {
                for (const dishType of filteredDishTypes) {
                    uniqueResults.add({ city, dishType });
                }
            }
            if (filteredDiets.length === 0 && filteredBrands.length > 0) {
                for (const brand of filteredBrands) {
                    uniqueResults.add({ city, brand });
                }
            }
        }
    }

    results.push(...uniqueResults);

    return results;
}

// Example usage
(async () => {
    const searchTerm = "vegan sushi in London";
    console.log('Search Term:', searchTerm);
    const entities = await extractEntities(searchTerm);
    console.log('entities:', JSON.stringify(entities, null, 2));
})().catch(error => console.error('Error:', error.stack));

Examples

For searchTerm=McDonald's the function should return:

[{ 
brand: {id: 4, name: "McDonald's"}
}]

For searchTerm=McDonald's in London the function should return:

[{ 
city: {id: 1, name: "London"},
brand: {id: 4, name: "McDonald's"}
}]

Any ideas what’ wrong?

In this case the code should return

[{ 
city: {id: 1, name: "London"},
diet: {id: 1, name: "Vegan"},
dishType: {id: 72, name: "Sushi"}
},
{ 
city: {id: 1, name: "London"},
diet: {id: 1, name: "Vegan"},
brand: {id: 15, name: "Sushimania"}
}]

but instead it returns:

[
  {
    "city": {
      "id": 1,
      "name": "London"
    },
    "diet": {
      "id": 1,
      "name": "Vegan"
    },
    "dishType": {
      "id": 72,
      "name": "Sushi"
    }
  }
]

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật