Skip to content

Support for the Postgres JSONB existence operator (?) #11671

Description

@samuelgoldenbaum

Issue Description

Is your feature request related to a problem? Please describe.

Are there any plans, or WIP, to bring in support for the postgres jsonb existence operator The current support to search within jsonb array results in casts in the generated SQL which causes major performance penalties.

Considering a table like:

CREATE TABLE public.collectibles
(
    id uuid NOT NULL,
    "attributes" jsonb,
    CONSTRAINT collectibles_pkey PRIMARY KEY (id)
)

The attributes column would contain data like:

{
   artists: ['Bob Kane', 'Dick Sprang'],
   pageCount: 33,
   ...
}

Searching now requires something like:

sequelize.collectibles.findAll({
            where: {
                'attributes.coverArtists::jsonb': {
                    [Op.contains]: '["Bob Kane"]'
                }
            },
            attributes: ['id'],
        });

which generates a nasty CAST statement:

SELECT "id" 
FROM "collectibles" AS "collectibles" 
WHERE CAST(("collectibles"."attributes"#>>'{coverArtists}') AS JSONB) @> '["Bob Kane"]';

Explain:

"Gather  (cost=1000.00..22710.38 rows=1000 width=48) (actual time=9.668..889.708 rows=208 loops=1)"
"  Workers Planned: 2"
"  Workers Launched: 2"
"  ->  Parallel Seq Scan on collectibles  (cost=0.00..21610.38 rows=417 width=48) (actual time=5.604..879.752 rows=69 loops=3)"
"        Filter: (((attributes #>> '{coverArtists}'::text[]))::jsonb @> '["Bob Kane"]'::jsonb)"
"        Rows Removed by Filter: 333264"
"Planning Time: 0.079 ms"
"Execution Time: 889.800 ms"

The equivalent statement with an existence operator is infinitely quicker:

SELECT id
FROM "collectibles" 
WHERE "attributes"->'coverArtists' ? 'Bob Kane';

Explain:

"Bitmap Heap Scan on collectibles  (cost=23.75..3115.45 rows=1000 width=16) (actual time=0.169..0.615 rows=208 loops=1)"
"  Recheck Cond: ((attributes -> 'coverArtists'::text) ? 'Bob Kane'::text)"
"  Heap Blocks: exact=207"
"  ->  Bitmap Index Scan on idx_coverartists  (cost=0.00..23.50 rows=1000 width=0) (actual time=0.095..0.095 rows=208 loops=1)"
"        Index Cond: ((attributes -> 'coverArtists'::text) ? 'Bob Kane'::text)"
"Planning Time: 0.096 ms"
"Execution Time: 0.669 ms"

889.800 ms vs 0.669 ms

Even if we can get a way to remove the CAST, we can improve the performance by 75%.

Describe the solution you'd like

Ideally, support for a new operator so we can include where statements like:

where: {
   'attributes.coverArtists': {
      [Op.existence]: 'Bob Kane'
   }
}

Why should this be in Sequelize

JSONB is an essential feature in Postgres and this has major a performance penalty with the current CAST

Describe alternatives/workarounds you've considered

Currently having to execute a raw query:

            sequelize
            .query(`SELECT id
                    FROM "collectibles"
                    WHERE "attributes"->'coverArtists' ? 'Bob Kane';`, {
                model: sequelize.models.test,
                mapToModel: true
            });

Issue Template Checklist

Is this issue dialect-specific?

  • No. This issue is relevant to Sequelize as a whole.
  • Yes. This issue only applies to the following dialect(s): postgres

Would you be willing to resolve this issue by submitting a Pull Request?

New to sequelize, but yeah, can dig in and assist.

  • Yes, I have the time and I know how to start.
  • Yes, I have the time but I don't know how to start, I would need guidance.
  • No, I don't have the time, although I believe I could do it if I had the time...
  • No, I don't have the time and I wouldn't even know how to start.

Activity

  1. papb commented on Jan 15, 2020

    @papb
    Member

    Understood, thanks for the very detailed report!

  2. papb commented on Jan 15, 2020

    @papb
    Member

    [x] Yes, I have the time but I don't know how to start, I would need guidance.

    Nice!! What kind of guidance do you need?

    For now I suggest you look at another PR which is also implementing a new operator in postgres, this might help you get started. It is the PR #10956. It is in progress though.

    Let me know if I can help further :)

  3. added
    dialect: postgres
    status: understood
    type: feature
    on Jan 15, 2020
  4. github-actions commented on Nov 5, 2021

    @github-actions
    Contributor

    This issue has been automatically marked as stale because it has been open for 7 days without activity. It will be closed if no further activity occurs. If this is still an issue, just leave a comment or remove the "stale" label. 🙂

  5. added
    topic: operators
    on Oct 6, 2022
  6. GuillaumeCisco commented on Jun 29, 2023

    @GuillaumeCisco

    Any updates on this.
    Is it possible to support the existence operator ? ?

    Using something like [Op.existence]?
    If no, is there a way to use it, with a literal or something?

  7. ephys commented on Jun 29, 2023

    @ephys
    Member

    The issue is that Sequelize interprets ? as the replacement token. We plan on deprecating that in v7 and remove that in v8 to be able to implement the JSONB ? operator: #15082

    The good news is that sequelize 6 only tries to interpret ? tokens if you use the replacements option:

    sequelize/src/sequelize.js

    Lines 611 to 613 in a3213f0

    if (options.replacements) {
    sql = injectReplacements(sql, this.dialect, options.replacements);
    }

    So you could use literal() (or sql in v7) to implement this (#13011, https://sequelize.org/docs/v7/querying/operators/#custom-operators).

  8. changed the title [-]Support for the Postgres JSONB existence operator[/-] [+]Support for the Postgres JSONB existence operator (`?`)[/+] on Mar 27, 2024
  9. added theissue type on Mar 9, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    dialect: postgresstatus: understoodtopic: operatorstype: feature

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions