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

Encountering an issue while trying to import the validator module in NextJS 13

I encountered a peculiar issue while trying to import a module. Nextjs presented the following error message: ./application/sign_in/sign_in_store.ts:2:0 Module not found: Can't resolve 'validator' 1 | import { createEvent, createStore } fr ...

Angular 4 animation issue: duration of transitions not being properly implemented

Why isn't the transition working as expected? Even though the animate function is set with a time of 2 seconds, the transition happens instantly. trigger('showMenu', [ state('active', style({ marginLeft: '0px' }) ...

Save the chosen information into the database

My goal is to insert a Foreign key, acc_id, into the patient_info table from the account_info table. I have successfully retrieved the data from my database and now I want to use it as a Foreign key in another table. Here is the code snippet: try { $ ...

Next.js allows for the wrapping of a server component within a client component, seamlessly

I am currently working on a project where I have implemented a form to add data to a JSON using GraphQL and Apollo Client. The project is built with TypeScript and Next.js/React. However, I am facing a conflicting error regarding server client components ...

Transmit information using jQuery to an MVC controller

I am developing an ASP.NET MVC3 application and need to send three pieces of data to a specific action when the user clicks on an anchor tag: <a onclick='sendData(<#= Data1,Data2,Data3 #>)'></a> Here is the javascript function ...

Convert the entirety of this function into jQuery

Can someone please help me convert this code to jQuery? I have a section of jQuery code, but I'm struggling with writing the rest! function showUser(str) { if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); } else { ...

Can I bypass an invalid SSL certificate when making a request using a JavaScript library?

Is it possible to bypass invalid SSL certificates when using the widely-used request library? You can find more information about the library here: https://www.npmjs.com/package/request I am currently integrating this library into a Node.js server to send ...

SQL query that includes data containing single quotes

Trying to Insert New Data INSERT INTO Clients (ClientId, PhoneNumber, MessageText, CityName, ZipCode, CountryName) VALUES (1, '123456', '["https://picsum.photos/id/237/200/300","Give your loved ones surprise gifts&quo ...

Trouble with a basic Angular demonstration

After replicating an angular example from w3schools (found here), I encountered some issues with it not functioning correctly. Despite my efforts, the code appears to be accurate. Can anyone spot what might be going wrong? To provide more context, here is ...

How can Angular display an alert when no items are visible?

I want to display a message saying "Item doesn't exist" when the item is not found. Suppose this is my list: user 0 user 1 user 2 The following code displays the list above: <ng-container *ngFor="let user of users | async; let i = index"> ...

Creating multiple synchronous loops within a Vue component using JavaScript

I'm dealing with a JavaScript loop that processes data from an Excel file. The loop loops through the results and retrieves a list of PMIDs. If the PMIDList has more than 200 items, it needs to be split into segments of 200 for processing due to restr ...

Utilizing Node Js and Selenium webdriver, what is the process of dragging and dropping an element from its current position to a new position just below it?

After multiple attempts, I have come to realize that the following code is ineffective. driver.findElement(By.xpath(xpath)).then(function (element1) { driver.findElement(By.xpath(xpath)).then(function (element2) { ...

Click the 'expand' button for additional details on every row in the table

I am facing a challenge with my HTML table where I have a lot of information to add for each row. However, displaying everything at once makes the page look cluttered. Therefore, I am looking to add a "view more" button in another column for each row. Des ...

Develop an application using ASP.NET MVC that allows for returning a JavascriptResult along with a

Imagine this situation When using MVC, it is quite simple to send a Javascript code back to the client for execution public ActionResult DoSomething() { return JavaScript("alert('Hello world!');"); } On the client side, ...

Unlimited scrolling feature in Ionic using JSON endpoint

Trying to create an Ionic list using data from a JSON URL. JSON Code: [{"id":"1","firstName":"John", "lastName":"Doe"}, {"id":"2","firstName":"Anna", "lastName":"Smith"}, {"id":"3","firstName":"Peter", "lastName":"Jones"},{......................}] app.j ...

Efficiently centering content in a grid layout using automatic fit repetition for optimized responsiveness

I've implemented a responsive grid where each item has its own hidden details section that is revealed upon clicking the item. The structure of the HTML/CSS setup is as follows: <div class="grid"> <div class="item"> ...

Retrieve the status callback function from the service

Can anybody show me how to set up a call-back function between a component and a service? I apologize for my lack of experience with Angular and TypeScript. getDiscount(){ let getDisc = []; getDisc.push({ price: Number(this.commonService.getP ...

angular displaying incorrect values for counter

Hi there, I am new to using Angular and I'm currently facing an issue with increasing and decreasing product quantity on the cart page. The problem is that in my first index it works fine, but in the second index, the value starts with the first index ...

Image Handpicked by JCrop User

Successfully implemented JCrop example code for selecting an area on an image with a preview and getting coordinates. However, the challenge lies in allowing users to select an image from their file system, display it in the browser, and perform the afore ...

When Infinite Scroll is integrated into another file with HTML tags stacked on top, it will not load additional posts when scrolling down

I have implemented an Infinite Scroll feature that dynamically loads more data from a database as users scroll to the bottom of the page. However, I encountered an issue when trying to include this functionality in another .PHP file. If I insert any HTML ...