我有postgres與JSONB數據類型即兩列。 'category'和'subcategory'。我需要根據用戶的輸入來搜索這些列。 JSON在「類別」一欄的樣子:
[{id: 36, name: "categoryName1"},{id: 42, name: "categoryName2"}]
和JSON在「子類別」欄的樣子:
[{id: 52, name: "subCategoryName1"},{id: 56, name: "subCategoryName2"}, {id: 70, name: "subCategoryName1"}]
輸入可以是「ID」,也可以是一個「name'.The查詢我寫了儘可能遠的嘗試在每個提供的輸入列中找到完全相同的名稱。但我想讓用戶甚至可以通過部分名稱查找,所以試圖使用$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%"}}]'
爲什麼ILIKE!?我認爲你應該使用$不需要扣款 – farhadamjady
我想讓搜索大小寫不敏感。我嘗試了'$ ilike',但沒有引用。 – Leo
1)[運營商](http://docs.sequelizejs.com/en/latest/docs/querying/)是'$ iLike'(注意大寫'L')2)你可能不能混合$包含「與其他任何東西。 PostgreSQL沒有任何簡單的操作符來做到這一點。在SQL層面上,你可以通過'('LATERAL')JOIN'jsonb_array_elements()'](http://stackoverflow.com/search?q=%5Bpostgresql%5D+like+json+array),但我懷疑這種續集會隱含地爲你做到這一點。 – pozs