0

I have a product model and a keyword model which looks like this:

class Product{
    String id;
    String name;
    List<KeyWord> keywords;
...

}
class KeyWord{
    String id;
    String title;
}

How to store them in Firestore to enable searching products by their keywords, And show a drop-down list of some pre-saved keywords like what happens in the stack overflow keywords system.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
Amr Hassan
  • 160
  • 8
  • Do you need the Firestore schema for that? How many keywords can be in a single list? – Alex Mamo Oct 03 '22 at 09:54
  • @AlexMamo yeah I need firestore schema for that, each product can have up to 20 keywords – Amr Hassan Oct 03 '22 at 10:08
  • 1
    To a question raised by @AlexMamo answer; Why does the `KeyWord` have an `id`? Are they in some way reusable with other products? If not, then remove that and you can just store the items in an array `0: some keyword` and `1: another keyword` and you are all set with that answer. If not, it could change the entire approach (an array of maps for example) – Jay Oct 03 '22 at 19:40
  • @Jay For sure Jay, it makes totally sense. – Alex Mamo Oct 04 '22 at 05:03

1 Answers1

1

Knowing that a list might have up to 20 keywords, then the database schema might look like this:

Firestore-root
  |
  --- products (collection)
        |
        --- $productId (document)
               |
               --- keywords (array)
                     |
                     --- 0
                         |
                         --- id: "keywordId"
                         |
                         --- title: "keywordTitle"

I'm not sure why would use an id of the keyword, but if you don't actually need it, then I recommend you store strings within the array and not KeyWord objects.

When you store string, you can easily query the products collection based on a specific keyword using:

final productsRef = db.collection("products");
final queryByKeyword = productsRef.where("keywords", arrayContains: "keyword");

Otherwise, you'll have to query using the entire object.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193