postgresql 如何在sequelize中对对象数组使用$ilike和$contains?

2cmtqfgy  于 2023-08-04  发布在  PostgreSQL
关注(0)|答案(3)|浏览(129)

我在postgres中有两个专栏与JSONB数据类型,即。“类别”和“子类别”。我需要在这些列的基础上从用户的输入搜索。“category”列中的JSON看起来像:

[{id: 36, name: "categoryName1"},{id: 42, name: "categoryName2"}]

字符串
“subcategory”列中的JSON看起来像:

[{id: 52, name: "subCategoryName1"},{id: 56, name: "subCategoryName2"}, {id: 70, name: "subCategoryName1"}]


输入可以是'id',也可以是一个'name'。到目前为止,我写的查询试图在两个列中找到完全相同的名称,根据所提供的输入。但我想让用户找到即使部分名称,所以尝试使用$ilike操作符。查询如下:

Model.findAll({
        where: {
          $or: {
            category: {
              $contains: [{
                "name": {
                  $ilike: '%' + term + '%'
                }
              }]
            },
            subcategory: {
              $contains: [{
                "name": {
                  '$ilike': '%' + term + '%'
                }
              }]
            }
          }
        }
      })


原始查询:

SELECT "category", "subcategory" FROM "table" AS "table" 
WHERE "table"."category" @> '[{"name":{"$ilike":"%subCategoryName2%"}}]' 
OR "table"."subcategory" @> '[{"name":{"$ilike":"%subCategoryName2%"}}]'

rdlzhqv9

rdlzhqv91#

这可能是你的答案:

{
    subcategory: {
        $contains: {
          name: {
              $ilike: '%' + term + '%'
      }
    }
   }
  }

字符串

xjreopfe

xjreopfe2#

使用sequelize找到了解决方案

{
                        'category.name': {
                            $iLike: `%${value}%`
                        }
                    }

字符串

gajydyqb

gajydyqb3#

您可以使用jsonb_path_exists函数,该函数检查JSONB值是否与带有通配符的路径表达式匹配。下面是解决方案

Model.findAll({1 where: { [Op.or]: [ 
    Sequelize.literal(
        jsonb_path_exists(
            category, '$[*] ? (@.name like_regex "${term}" flag "i")')), 
    Sequelize.literal(
        jsonb_path_exists(
        subcategory, '$[*] ? (@.name like_regex "${term}" flag "i")')) 
]}});

字符串
你可以在这里阅读更多关于jsonb_path_exsits函数的信息:#postgres

相关问题