Skip to content

Error when using $contains operator with JSONB array field #5173

Open

Description

@buunguyen

Hello, I have a table with a field doc which is of type JSONB. Each doc has a browsers array. I try to search for rows where doc->browsers contains some value using the $contains operator, like this:

model.find({where: {
  doc.browsers = {
    $contains: [browserName]
  }
}})

And got this error:

ERROR:  operator does not exist: text @> text[] at character 478
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.

Do you know how to support this use case in Sequelize? Thanks!

Activity

  1. mickhansen commented on Jan 9, 2016

    @mickhansen
    Contributor

    Please post the complete SQL query when errors are related to SQL query generation.

  2. buunguyen commented on Jan 9, 2016

    @buunguyen
    Author

    Here you go

    ERROR:  operator does not exist: text @> text[] at character 39
    HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.
    
    STATEMENT:  
    SELECT "id", "doc", "createdAt", "updatedAt", "deletedAt" 
    FROM "Devices" AS "Device" 
    WHERE ("Device"."deletedAt" IS NULL AND ("Device"."doc"#>>'{browsers}') @> ARRAY['chrome']) 
    LIMIT 1;
    
  3. mickhansen commented on Jan 9, 2016

    @mickhansen
    Contributor

    Hmm yeah so the problem is likely that the syntax we use for looking up a nested element will return that item as a value, rather than as a json object.

    Can you show me the correct SQL for that query?

  4. buunguyen commented on Jan 10, 2016

    @buunguyen
    Author

    I've found 3 queries that work:

    • Require casting to JSONB and argument must be JSON array
    ("Device"."doc"#>>'{browsers}')::jsonb @> '["chrome"]') 
    
    • Use #> to avoid casting, argument still needs to be JSON array
    ("Device"."doc"#>'{browsers}') @> '["chrome"]') 
    
    • Use ?& operator so that argument can be ARRAY instead of JSON
    ("Device"."doc"#>'{browsers}') ?& ARRAY['chrome']) 
    
  5. mickhansen commented on Jan 10, 2016

    @mickhansen
    Contributor

    It having to be an JSON array makes sense, and we should likely do that conversion.
    Using the non string converting lookup when using $contains looks like the way to go.

  6. buunguyen commented on Jan 11, 2016

    @buunguyen
    Author

    Sounds good. Hope there'll be a fix for this soon.

  7. added
    type: bug
    dialect: postgres
    on Jan 18, 2016
  8. duylam commented on Feb 28, 2016

    @duylam

    Given json structure

    SELECT myJsonCol FROM myTable
    
    {locked: true, browsers: [{name: "chrome"}, {name: "firefox"}] }
    

    I can get rows having name = "chrome" in browsers array using below query

    model.find({
      where: {
        myJsonCol: {
          '$contains': { browsers:[{name: "chrome"}] }
        }
      }
    })
    

    Here is the generated SQL statement

    SELECT  ...
    FROM "myTable"
    WHERE "myTable"."myJsonCol" @> '{"browsers":[{"name":"chrome"}]}';
    
  9. marol-hadidjaja commented on Mar 14, 2016

    @marol-hadidjaja

    really need this bug fixed...

  10. zaggino commented on Mar 24, 2016

    @zaggino
    Contributor

    my current workaround:

    model.find({where: {
      doc.browsers = {
        $contains: sequelize.cast('["' + browserName + '"]', 'jsonb')
      }
    }})
    
  11. aliatsis commented on Apr 27, 2016

    @aliatsis

    +1

  12. keymsg commented on Apr 27, 2016

    @keymsg

    +1

  13. matthewheck commented on Jun 7, 2016

    @matthewheck
    Contributor

    I'm taking a look into fixing this. @mickhansen - Just to be clear, you recommend the first option from @buunguyen's list?

    ("Device"."doc"#>>'{browsers}')::jsonb @> '["chrome"]')

  14. mickhansen commented on Jun 8, 2016

    @mickhansen
    Contributor

    @matthewheck I think i simply agreed that we need to convert the value to a JSON array rather than a PG array.

  15. 22 remaining items

  16. mathieumagalhaes commented on Oct 16, 2018

    @mathieumagalhaes

    @vkm912 Not sure, I'm still using my workaround for certain use-cases with JSON Arrays in MySQL.

    As @janmeier pointed out, in Postgres the JSONB field and the $contains operator is working,
    not sure if it's the case now with MySQL JSON fields as well.

  17. vkm912 commented on Oct 17, 2018

    @vkm912

    @vkm912 Not sure, I'm still using my workaround for certain use-cases with JSON Arrays in MySQL.

    As @janmeier pointed out, in Postgres the JSONB field and the $contains operator is working,
    not sure if it's the case now with MySQL JSON fields as well.

    @mathieumagalhaes , Thanks for the reply. Yes I tried using $contains through Sequelize for MySQL, but that was getting converted into "#>" symbol which is not supported in MySQL.
    @janmeier : Please let us know in case if you got a chance to try your solution for MySQL as well.

  18. mathieumagalhaes commented on Oct 17, 2018

    @mathieumagalhaes

    @vkm912 There is no JSONB field in MySQL, only JSON DataType is supported in MySQL/Sequelize. Therefore his solution will not work with the MySQL dialect setup in Sequelize.

    You could find a workaround for almost anything using 'literal' and 'fn' following the JSON MySQL documentation.

    But it would be nice to see it being supported natively in Sequelize.

  19. haracejacob commented on Mar 20, 2019

    @haracejacob

    In PostgreSQL, Can be used $contains operator with JSONB ARRAY by..

    Data Format
    {
      "doc": {
        "browsers": ["foo", "bar"]
      }
    }
    In Sequelize
    model.find({
      where: {
        'doc.browsers::jsonb': {
          $contains: '["foo"]'
        }
      }
    }
    query
    SELECT * FROM model WHERE CAST((doc #>> '{browsers}') AS JSONB) @> '["foo"]'

    update 2022.04.07

    if you want to use an index, you shouldn't use the code above.
    In my case, I just use literal.

    Data Format
    {
      "doc": {
        "browsers": ["foo", "bar"]
      }
    }
    In Sequelize
    import { literal, Op } from 'sequelize'
    
    model.find({
      where: {
        [Op.and]: [
          literal(`("Model"."doc" -> 'browsers') @> '["foo"]'`
        ]
      }
    }
  20. samuelgoldenbaum commented on Nov 12, 2019

    @samuelgoldenbaum

    In PostgreSQL, Can be used $contains operator with JSONB ARRAY by..

    Data Format
    {
      "doc": {
        "browsers": ["foo", "bar"]
      }
    }
    In Sequelize
    model.find({
      where: {
        'doc.browsers::jsonb': {
          $contains: '["foo"]'
        }
      }
    }
    query
    SELECT * FROM model WHERE CAST((doc #>> '{browsers}') AS JSONB) @> '["foo"]'

    The cast here has big performance hit, especially with large datasets

  21. haracejacob commented on Nov 12, 2019

    @haracejacob

    @samuelgoldenbaum

    I'm just suggesting one way. If you consider performance, don't put JSONB ARRAY on where clause.

  22. samuelgoldenbaum commented on Nov 12, 2019

    @samuelgoldenbaum

    @samuelgoldenbaum

    I'm just suggesting one way. If you consider performance, don't put JSONB ARRAY on where clause.

    This issue is really the CAST that's needed to get sequelize to work, not your example. There is no issue with searching a jsonb array, especially once the appropriate GIN index has been created. I am able to search several million records on my pretty avg notebook and return results in 0.4ms which is acceptable for my use case.

    See issue #11671 I have created.

    PS, I am currently resorting to raw queries for this scenario, similar to:

    sequelize
                .query(`SELECT id
                        FROM "model"
                        WHERE "doc"->'browsers' ? 'foo';`, {
                    model: sequelize.models.model,
                    mapToModel: true
                });
    
  23. haracejacob commented on Nov 12, 2019

    @haracejacob

    @samuelgoldenbaum Yes, you're right.
    I also created a similar issue #10599. but closed.

  24. afzalIbnSH commented on Feb 3, 2022

    @afzalIbnSH

    What worked for me;

                        'doc.browsers::JSONB': {
                            $contains: db.sequelize.literal(`'["${browserName}"]'`)
                        }
    
  25. chenzewang commented on Apr 4, 2022

    @chenzewang

    that work for me ,thx bro

  26. mariusa commented on Apr 10, 2022

    @mariusa

    Related: How can one run these 2 raw queries with sequelize.query and passing the array as a replacement, so it would handle escaping?

    SELECT * FROM product where tags @> '["tag1", "tag2"]';
    SELECT * FROM product where tags ?| ARRAY['tag1', 'tag2']; 
    

    product.tags is a JSONB array in Postgres.

    I tried

    let [recs, meta] = await sequelize.query(`SELECT * FROM product WHERE tags @> ?`, {
            replacements: [['tag1', 'tag2']]
        })
    

    but sequelize produces SELECT * FROM product WHERE tags @> 'tag1', 'tag2'
    If I add another set of [] (why would it be needed?), as in replacements: [[['tag1', 'tag2']]], then
    then it produces SELECT * FROM product WHERE tags @> ('tag1', 'tag2')

    The 2nd query also doesn't work, the ? in ?| operator is parsed as a replacement.
    Thanks!

  27. ephys commented on Apr 10, 2022

    @ephys
    Member

    Could you open another issue for that?
    It's a valid issue, and the related regexp needs to be improved, but let's keep this issue strictly about automatically casting to JSONB for this scenario

    Edit: the other issue is #14410

  28. 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: mysqldialect: postgrestype: bug

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions