tminglei / slick-pg

Slick extensions for PostgreSQL
BSD 2-Clause "Simplified" License
839 stars 180 forks source link

how to filter list of Int #462

Open slmzig opened 4 years ago

slmzig commented 4 years ago

I have a table

  case class JsonBean2(id: Long, json: JsValue)

  class JsonTestTable(tag: Tag) extends Table[JsonBean2](tag, "JsonTest2") {
    def id = column[Long]("id", O.AutoInc, O.PrimaryKey)
    def json = column[JsValue]("json", O.Default(Json.parse(""" {"a":"v1","b":2} """)))
    def * = (id,  json) <> (JsonBean2.tupled, JsonBean2.unapply)
  }
  val JsonTests = TableQuery[JsonTestTable]

and I insert data


  val testRec5 = JsonBean2(33L, Json.parse(""" {"interestedIn":[11],"countries":["IT", "UK"]} """))
  val testRec6 = JsonBean2(34L, Json.parse(""" {"interestedIn":[12],"countries":["US", "UK"]} """))
  val testRec7 = JsonBean2(35L, Json.parse(""" {"interestedIn":[13],"countries":["IT2", "UK"]} """))
  val testRec8 = JsonBean2(36L, Json.parse(""" {"interestedIn":[14],"countries":["IT3", "UK"]} """))
  val testRec9 = JsonBean2(37L, Json.parse(""" {"interestedIn":[16],"countries":["IT1", "UK"]} """))

I know how to filter in array of string

db.run(
        JsonTests
          .filter(row => row.json.+>("countries") ?| List("US").bind)
          .result
    )

but how I can filter in array of Int?

db.run(
        JsonTests
          .filter(row => row.json.+>("interestedIn") ?| List(11).bind)
          .result
    )

my variant does not work

tminglei commented 4 years ago

@slmzig try it's not easy, but you can try

val jsonL = toJson(List(11)) // convert List(11) to json value
(row.json.+>("interestedIn") @> jsonL) && (jsonL <@ row.json.+>("interestedIn"))

to get the result.