Optimised searching for multiple tags at once

This commit is contained in:
neviyn 2021-05-06 21:30:11 +01:00
parent 90bb712bc3
commit f97358aeb4
2 changed files with 3 additions and 3 deletions

View File

@ -56,7 +56,7 @@ class ImageController
"" -> imageRepository.findAll(page) "" -> imageRepository.findAll(page)
else -> { else -> {
val distinctTags = tags.split(" ").distinct() val distinctTags = tags.split(" ").distinct()
val tagData = distinctTags.mapNotNull { tagRepository.findByTagIs(it) } // Try to get actual tag objects val tagData = tagRepository.findAllByTagIn(distinctTags) // Try to get actual tag objects
when { when {
tagData.isEmpty() -> null // No tags existed with the specified search terms tagData.isEmpty() -> null // No tags existed with the specified search terms
tagData.size != distinctTags.size -> null // Error if an invalid tag was supplied tagData.size != distinctTags.size -> null // Error if an invalid tag was supplied

View File

@ -13,10 +13,9 @@ interface UserRepository : CrudRepository<User, Long> {
interface RoleRepository : CrudRepository<Role, Long> interface RoleRepository : CrudRepository<Role, Long>
interface ImageRepository : JpaRepository<Image, Long> { interface ImageRepository : JpaRepository<Image, Long> {
//@Query("select i from Image i join i.tags t where t in ?1 group by i.id having count(i.id) = ?2")
@Suppress("SqlResolve") @Suppress("SqlResolve")
@Query( @Query(
value = "select * from booru.image i where i.id in (select image_id from booru.tag_image ti where ti.tag_id in ?1 group by ti.image_id having count(ti.image_id) = ?2) order by i.id", value = "WITH X AS (SELECT IMAGE_ID FROM BOORU.TAG_IMAGE TI WHERE TI.TAG_ID in ?1 GROUP BY TI.IMAGE_ID HAVING COUNT(TI.IMAGE_ID) = ?2) SELECT I.* FROM BOORU.IMAGE I RIGHT JOIN X ON I.ID = X.IMAGE_ID ORDER BY I.ID",
nativeQuery = true nativeQuery = true
) )
fun findByTagsOrderById(tagIDs: List<Tag>, tagCount: Long, pageable: Pageable): Page<Image> fun findByTagsOrderById(tagIDs: List<Tag>, tagCount: Long, pageable: Pageable): Page<Image>
@ -26,4 +25,5 @@ interface ImageRepository : JpaRepository<Image, Long> {
interface TagRepository : CrudRepository<Tag, Long> { interface TagRepository : CrudRepository<Tag, Long> {
fun findByTagIs(tag: String): Tag? fun findByTagIs(tag: String): Tag?
fun findAllByTagIn(tags: List<String>): List<Tag>
} }