Search code examples
javascriptreactjssupabasesupabase-database

How do I select rows that match any value inside an array in supabase?


I want to select all rows that match at least one of given tags from this table:

enter image description here

If I want to search by tag1 and tag3 it should return 1st, 3rd and 4th row and when I want to search by tag2 and tag4 it should return all of them because they all have this tag and if I want to search by tag4 it should return just 2nd row.

I found how to select ones that have all the tags provided which is:

.select().contains("tags", ["tag1", "tag2"])

but the returned rows meet all two tags at once so it returns just 2nd and 3rd row and I want it to return 4th row as well.


Solution

  • If you want to match any value of that array, then you need to encapsulate it within the OR filter:

    const supabase = createClient(SUPABASE_URL, SUPABASE_KEY);
    const { data: ret, error } = await supabase
      .from('test_tags')
      .select()
      .or('tags.cs.{tag1}','tags.cs.{tag2}');
      
    console.log(ret);
    

    You can also expand and use two or more OR logical operators:

    const { data: ret, error } = await supabase
      .from('test_tags')
      .select()
      .or('tags.cs.{tag1},or(tags.cs.{tag4},tags.cs.{tag3})');
      
    console.log(JSON.stringify(ret));