How can I incorporate the LIKE operator in a query when dealing with PostgreSQL's String array type using TypeORM?

My database backend is PostgreSQL and I have a TypeORM object simplified as follows:

@Entity()
@Index(['name'], {unique: true})
export class Foo extends BaseEntity {
 @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column()
  name: string;

  @Column('varchar', { array: true })
  bar: string[];
}

I am currently building an API query handler to handle searches. I can easily perform a LIKE query on the name attribute like this:

 let qs = Foo.createQueryBuilder('foo');
 qs.andWhere('foo.name ILIKE :name', {
    name:'%${name}%'
  });

However, I also want to be able to search for any "bar" value that contains a specific query term using a soft comparison method. Despite finding documentation on how to exact match a search term in the "bar" attribute, I cannot find information on performing a soft comparison.

The main goal is to allow users to enter a specific query, such as "%oo%", and retrieve the first two records where the "bar" strings contain that substring. For example, given the following dataset:

[
{id: 1, name: 'whatever', bar: ['apple','banana','yeti','woo']},
{id: 2, name: 'something else', bar: ['red','blue','green', 'boo']},
{id: 3, name: 'i dunno', bar: ['ford','chevy']},
]

Users should be able to query "%oo%" and receive the first two records based on the presence of that substring within the "bar" values.

Answer №1

PostgreSQL offers a variety of array functions and operators that can assist you in crafting intricate queries.

In this scenario, one effective method would be:

  1. Converting the array into a string
  2. Applying the LIKE operation to that string

You can achieve this with code similar to the following:

.createQueryBuilder('foo')
.where("array_to_string(foo.bar, ',') LIKE :bar", {
 bar: '%aa%',
})
.getMany();

Answer №2

I am not familiar with typeorm, but based on the discussion in this GitHub thread

The SQL query provided is:

WITH cte (
    id,
    name,
    bar
) AS (
    VALUES (1, 'whatever', ARRAY['apple', 'bananna', 'yeti', 'woo']),
        (2, 'something else', ARRAY['red', 'blue', 'green', 'boo']),
        (3, 'i dunno', ARRAY['ford', 'chevy'])
),
cte1 AS (
    SELECT
        json_agg(row_to_json(cte.*)) AS json_all
    FROM
        cte
)
SELECT
    value
FROM
    cte1,
    json_array_elements(json_all)
WHERE
    value ->> 'bar' ~ 'oo';

According to the information on the GitHub page, the query would look like this:

getConnection().query("
with cte(id,name,bar) as (values
 (1,'whatever',array ['apple','bananna','yeti','woo'])
,(2,'something else',array  ['red','blue','green', 'boo'])
,(3,'i dunno',array ['ford','chevy'])
),cte1 AS
(select json_agg(row_to_json(cte.*)) as json_all from cte)
select value
from cte1,json_array_elements(json_all)
where value->>'bar' ~ @0", ['oo']);

To perform a case-insensitive match, use value->>'bar' ~* @0"

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

Typescript enhances Solid JS by using the "as" prop and the "component" prop

Hey there, I've been experimenting with solid-js lately and I'm facing a challenge integrating it with typescript. My objective is to make my styling more modular by incorporating it within my components. type RelevantTags = Exclude<keyof ...

When using nodejs with sqlite3, the first callback parameter returns the class instance. How can this be resolved in order to prevent any issues?

Exploring a TypeScript class: class Log { public id: number; public text: string; construct(text: string){ this.text = text; } save(){ db.run( `insert into logs(text) values (?) `, this.text, ...

Error: Could not find module: Unable to locate 'rxjs/add/observable/throw' in 'D:AngularhttpErrorHandlingExamplesrcapp'

I'm working on an Angular project to practice error handling, but I encountered an issue when trying to import the 'throw' module. The error message reads as follows: Error Message: "ERROR in ./src/app/employee.service.ts Module not found: E ...

What external libraries does Angular 4 utilize during execution, aside from RxJS?

Angular 4 relies on RxJS types in its public API and also internally depends on RxJS. It would be beneficial to explore if Angular utilizes other external packages for certain functionalities, allowing us to incorporate them into our own projects. This ap ...

Calculate the total sum with a group by clause using xquery

Looking for assistance converting the following SQL query: SELECT SUM((((1-Discount)*Quantity)*[Unit Price])) AS AMOUNT FROM Orders LEFT JOIN [Order Details] ON Orders.[Order ID] = [Order Details].[Order ID] WHERE ((([Order Date]) BETWEEN #1/1/20 ...

Storing the typeof result in a variable no longer aids TypeScript in type inference

Looking at the code snippet below: export const func = (foo?: number) => { const isNumber = typeof foo === 'number'; return isNumber ? Math.max(foo, 0) : 0; }; A problem arises when TypeScript complains that you cannot apply undefined to ...

How to Modify CSS in Angular 6 for Another Element in ngFor Loop Using Renderer2

I have utilized ngFor to add columns to a table. When a user clicks on a <td>, it triggers a Dialog box to open and return certain values. Using Renderer2, I change the background-color of the selected <td>. Now, based on these returned values, ...

Updating meta tags dynamically in Angular Universal with content changes

Hello, I'm encountering an issue with a dynamic blog page. I am trying to update meta tags using data fetched from the page. Here's the code snippet: getBlogPost() { this.http.get(...) .subscribe(result => { this.blogPost = re ...

Link the ngModel input to an object within an ngFor iteration

Looking to create a dynamic form using an array that includes FieldLabel and DataModel references. I want to use the DataModel as an object reference, so when the user updates an input field, the referenced model is updated. I have searched extensively bu ...

Acquiring the download link for Firebase Storage in Angular 2+ technology

reference: AngularFireStorageReference; task: AngularFireUploadTask; uploadState: Observable<string>; uploadProgress: Observable<number>; downloadLink: Observable<string>; beginUpload(event) { const id = Math.floor(Math.random() * 1000 ...

Tips for modifying JSON response using a function

When I call the function buildFileTree, I store its response in a constant variable called data. const data = this.buildFileTree(dataObject, 0); The value of dataObject is: const dataObject = JSON.parse(TREE_DATA); And the content of TREE_DATA is: cons ...

Can you explain the variance between the (Record<string, unknown>) and object type?

Can you explain the distinction between type Record<string, unkown> and type object? Create a generic DeepReadonly<T> which ensures that every parameter of an object - and its nested objects recursively - is readonly. Here's the type I c ...

Is there a convenient method for setting up and activating real-time TypeScript checking in Windows 10 using VS Code?

After successfully installing VS Code on my Windows 10 system, I decided to follow the instructions provided here. Upon completion, Node and NPM were also installed correctly. However, I noticed a gap in the setup instructions between installing TypeScrip ...

Synchronizing data between parent and child components using two-way binding with emit in Vue 3 using TypeScript

Within my code, there is a child component: <template> <label :class="className + ' ctrl'"> <span><LocCtrl :page="pageName" :locKey="labelLoc" /></span> <input type=&q ...

Can someone show me how to properly set up nested child routes in Angular 2?

My application structure is organized as shown below . ├── photos ├── posts ├── users │   ├── detail │   │   ├── address │   │   ├── family │   │   ├── information │   │   └ ...

Utilize Typescript to inject types into a library

I have a code snippet that reads data from a JSON file and creates a type based on it, which is then used for further operations. import jsonData from './mydata.json' type CustomType = typeof jsonData .... This process ensures that the generate ...

Creating an optimized database structure for a cutting-edge voting platform

I am looking for a way to store votes for items based on their id in a system. I anticipate that there will be approximately 5 million votes to handle. Each vote will include: The id of the item being voted on Userdata1 Userdata2 Date and time of the vot ...

Create interfaces for a TypeScript library that is available on npm for export

I have a project in TypeScript that I am packaging as a library to be used by both JavaScript and TypeScript projects. After compiling, I upload the .js and .d.ts files to npm. The main.ts file exports the following: interface MyInterface{ // ... } clas ...

What is the source of EntityKeyValue in miniprofiler SQL investigations?

Currently, I am in the process of debugging some duplicate SQL statements within my MVC application using miniprofiler. I'm facing difficulty in identifying the origin of certain SQL statements, many of which start with declaring a parameter named En ...

Problems with the zoom functionality for images on canvas within Angular

Encountering a challenge with zooming in and out of an image displayed on canvas. The goal is to enable users to draw rectangles on the image, which is currently functioning well. However, implementing zoom functionality has presented the following issue: ...