Postgres Array intersection: finding elements common to two arrays

I'm currently developing a search function based on tags, within a table structure like this

    CREATE TABLE permission (
      id serial primary key,
      tags varchar(255)[],
    );

After adding a row with the tags "artist" and "default," I aim to retrieve data using tag-based queries (employing the knex query builder). Here's an example:

  async getByTags(tags: string[]): Promise<PermissionTable[]> {
    return this.db<PermissionTable>('permission')
      .select('*')
      .whereRaw("tags @> '{??}'", [tags])
  }

Depending on the number of tags provided, different SQL statements are generated as shown below.

This request functions correctly

    select * from "permission" where tags @> '{"artist"}';

However, when querying with multiple tags, it fails to return the desired row and instead yields an empty array.

    select * from "permission" where tags @> '{"artist", "event"}';

The issue arises when attempting to query by more than one tag. Why is this happening?

Answer №1

@> signifies the "contains" operation, which means a1 @> a2 is considered true when all elements in a2 are found within a1. For instance:

array['artist', 'default'] @> array['artist']            -- True
array['artist', 'default'] @> array['default', 'artist'] -- True
array['artist', 'default'] @> array['artist', 'event']   -- False

Therefore, @> checks whether the right operand is a subset of the left operand.

If you're searching for the "overlaps" operator, it would be:

&&
overlap (shares common elements)

ARRAY[1,4,3] && ARRAY[2,1] -- True

This operator determines if there is a non-empty intersection between the sets on the left and right sides.

A query like:

.whereRaw("tags && '{??}'", [tags])

might suit your needs better.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unexpected Results From Query

I've created an app for my team that allows them to login and logout. I'm trying to retrieve the last logout time for each day, even if an employee logs out and then logs back in again on the same day. SELECT DATE_FORMAT(time, "%d.%m.%Y&q ...

Guide on accessing text content from a sibling div element using jQuery

There are several divs arranged on a page as shown below. If a user clicks a link within the UL .list-links, I want to capture the content inside: <span class="asa_portlet_title">Title here</span> and store it in a variable. I have attempted ...

Jquery Banner Fade In animation malfunctioning

I am facing an issue with my banner on various browsers, especially IE 7,8, and possibly 9. When the fade-in effect is applied at the bottom of the banner, the shadows underneath turn black. Is there anyone who can help me resolve this issue? Website: ww ...

The module for the class could not be identified during the ng build process when using the --

Encountering an error when running: ng build --prod However, ng build works without any issues. Despite searching for solutions on Stack Overflow, none of them resolved the problem. Error: ng build --prod Cannot determine the module for class X! ...

How to pass a single value using onClick event without relying on form submission

I prefer to pass a single value instead of multiple putPriority fetch calls. This value will not be inputted by the user directly, but rather passed through an onClick event. For example, I want the onClick to send a specific number to "status" in the fe ...

Expanding the HTTP Get URL with a click in Ionic 2 and Angular 2

I recently performed a search for my ionic app, which fetches data from an api using a http get method as shown below static get parameters() { return [[Http]]; } searchRecipes(id) { var url = 'http://api.yummly.com/v1/api/recipes?_app_id=// ...

Performing bulk operations on all selected rows in a table using Angular 6

Within my Angular 6 web application, there is a table with checkboxes in each row. My goal is to be able to perform bulk actions on the selected rows, such as deleting them. One approach I considered was adding an isSelected boolean property to the data m ...

Angular transforming full names to initials within an avatar

What is the best way to convert names into initials and place them inside circular icons, like shown in the screenshot below? I already have code that converts the initials, but how do we create and add them inside the icons? The maximum number of icons di ...

Perform an UPDATE query using the results of a SELECT query all in one single statement

Hello, I am facing a challenge with 2 SQL statements. First Statement: SELECT id, name, version FROM mydb WHERE device IS NULL AND Activated=1 ORDER BY id ASC LIMIT 10 Second Statement: UPDATE mydb SET device='$device' WHERE name IN ('$i ...

The online server is unable to access the route from the ajax function in a separate JavaScript file

I am currently working on a Laravel project where each view page has its own separate JS file. However, I have encountered an issue when trying to access route functions from AJAX post or get calls on the online server (Digital Ocean). The error message I ...

A guide to extracting text from HTML elements with puppeteer

This particular query has most likely been asked numerous times, but despite my extensive search, none of the solutions have proven effective in my case. Here is the Div snippet I am currently dealing with: <div class="dataTables_info" id=&qu ...

What is the correct way to handle fetch timeouts in a React component?

Utilizing a JavaScript timeout, I am able to fetch Dogs from my API successfully. However, there are instances where the timeout fails to clear properly: import { useState, useEffect, useCallback } from 'react'; const DogsPage = () => { c ...

What steps should I take to address the issue of the document not being defined?

I encountered an error that I initially thought was related to node.js, but now I'm not entirely sure. How can I go about resolving this issue? [Running] node "c:\Users\Lenovo\Desktop\projectjs\index.js" c:\User ...

What is the process for implementing a custom error when compiling Sass code with node-sass?

When using node-sass to compile my sass code, I am curious about the possibilities during the compilation process. To clarify, I am interested in creating custom rules and generating specific errors under certain conditions while compiling. ...

Utilizing MS SQL, AJAX, PHP, and JSON to fetch dynamic page content based on dropdown selection

I've hit a roadblock in my project. I'm currently working on an event registration system where a user selects an event from a dropdown menu populated by values and IDs retrieved from a SQL stored procedure (index.php). Upon selecting an event, I ...

Tips for efficiently storing and accessing data obtained from the "RESTBuilder" tool on the Total.js platform

After stumbling upon this informative tutorial on how to build a cryptocurrency comparison site with VueJs, I was inspired to create a single-page application using the total.js platform. My goal is to fetch the list of coins from the "coinmarketcap.com" A ...

Using the function goToPage() within the TabbedHeaderPager component

I am currently working on a project that involves using TabbedHeaderPager, and I need to change tabs programmatically. I have been attempting to use the function goToPage() but have run into difficulties accessing it. I have tried passing it as a prop an ...

Expanding the range of colors in the palette leads to the error message: "Object is possibly 'undefined'. TS2532"

I am currently exploring the possibility of adding new custom colors to material-ui palette (I am aware that version 4.1 will include this feature, but it is a bit far off in the future). As I am relatively new to typescript, I am finding it challenging t ...

Troubleshooting sequential image loading in KineticJS and resolving issues with opacity tween when setting fillPatternImg

In my latest project using KineticJS, I am developing a small app that generates multiple nodes in the form of RegularPolygons. Once the stage has loaded (activated with play();), I proceed to sequentially fill each node with an image pattern using loadIma ...

A guide on transferring and transforming text data on the server

While I have a basic understanding of php, ajax, and javascript (including jQuery), I am still a beginner and could use some assistance with connecting the dots for this simple task: My goal is to allow the user to input text (for example: "I saw the sun, ...