feat(search): Add denormalized search_text column for better book search (#1791)

* fix(search): Optimize book search with denormalized search_text column

Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>

* fix(search): Enhance search text normalization for diacritics in author names

Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>

* fix(migration): Implement batch processing for populating search text and enhance error handling

Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>

* fix(search): Manually trigger search text update after author modifications and enhance special character handling

Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>

* fix(search): Update special character handling to be more permissive in search text normalization

Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>

* feat(AppMigrationService): add FileService dependency for enhanced file handling

Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>

* feat(database): add search_text column to book_metadata for improved search functionality

Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>

* feat(database): add search_text column to book_metadata for improved search functionality

Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>

* fix(database): correct join condition and ordering in findBooksForMigrationBatch query

Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>

---------

Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>
This commit is contained in:
Balázs Szücs
2025-12-10 12:51:18 -07:00
committed by GitHub
parent d76251ba21
commit 3bfece030b
14 changed files with 447 additions and 44 deletions
@@ -1,5 +1,6 @@
package com.adityachandel.booklore.model.entity;
import com.adityachandel.booklore.util.BookUtils;
import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.persistence.*;
import lombok.*;
@@ -232,6 +233,15 @@ public class BookMetadataEntity {
@Column(name = "embedding_updated_at")
private Instant embeddingUpdatedAt;
@Column(name = "search_text", columnDefinition = "TEXT")
private String searchText;
@PrePersist
@PreUpdate
public void updateSearchText() {
this.searchText = BookUtils.buildSearchText(this);
}
@OneToOne(fetch = FetchType.LAZY)
@MapsId
@JoinColumn(name = "book_id")
@@ -74,12 +74,8 @@ public interface BookOpdsRepository extends JpaRepository<BookEntity, Long>, Jpa
@Query("""
SELECT DISTINCT b.id FROM BookEntity b
LEFT JOIN b.metadata m
LEFT JOIN m.authors a
WHERE (b.deleted IS NULL OR b.deleted = false) AND (
LOWER(m.title) LIKE LOWER(CONCAT('%', :text, '%'))
OR LOWER(m.subtitle) LIKE LOWER(CONCAT('%', :text, '%'))
OR LOWER(m.seriesName) LIKE LOWER(CONCAT('%', :text, '%'))
OR LOWER(a.name) LIKE LOWER(CONCAT('%', :text, '%'))
m.searchText LIKE CONCAT('%', :text, '%')
)
ORDER BY b.addedOn DESC
""")
@@ -96,14 +92,10 @@ public interface BookOpdsRepository extends JpaRepository<BookEntity, Long>, Jpa
@Query("""
SELECT DISTINCT b.id FROM BookEntity b
LEFT JOIN b.metadata m
LEFT JOIN m.authors a
WHERE (b.deleted IS NULL OR b.deleted = false)
AND b.library.id IN :libraryIds
AND (
LOWER(m.title) LIKE LOWER(CONCAT('%', :text, '%'))
OR LOWER(m.subtitle) LIKE LOWER(CONCAT('%', :text, '%'))
OR LOWER(m.seriesName) LIKE LOWER(CONCAT('%', :text, '%'))
OR LOWER(a.name) LIKE LOWER(CONCAT('%', :text, '%'))
m.searchText LIKE CONCAT('%', :text, '%')
)
ORDER BY b.addedOn DESC
""")
@@ -72,26 +72,35 @@ public interface BookRepository extends JpaRepository<BookEntity, Long>, JpaSpec
""")
List<BookEntity> findAllFullBooks();
@Query(value = """
SELECT DISTINCT b.* FROM book b
LEFT JOIN book_metadata m ON b.id = m.book_id
WHERE (b.deleted IS NULL OR b.deleted = false)
ORDER BY b.id
LIMIT :limit OFFSET :offset
""", nativeQuery = true)
List<BookEntity> findBooksForMigrationBatch(@Param("offset") int offset, @Param("limit") int limit);
@Query("""
SELECT DISTINCT b FROM BookEntity b
LEFT JOIN FETCH b.metadata m
LEFT JOIN FETCH m.authors
WHERE b.id IN :bookIds
""")
List<BookEntity> findBooksWithMetadataAndAuthors(@Param("bookIds") List<Long> bookIds);
@Query(value = """
SELECT DISTINCT b FROM BookEntity b
LEFT JOIN b.metadata m
LEFT JOIN m.authors a
WHERE (b.deleted IS NULL OR b.deleted = false) AND (
LOWER(m.title) LIKE LOWER(CONCAT('%', :text, '%'))
OR LOWER(m.subtitle) LIKE LOWER(CONCAT('%', :text, '%'))
OR LOWER(m.seriesName) LIKE LOWER(CONCAT('%', :text, '%'))
OR LOWER(a.name) LIKE LOWER(CONCAT('%', :text, '%'))
m.searchText LIKE CONCAT('%', :text, '%')
)
""",
countQuery = """
SELECT COUNT(DISTINCT b.id) FROM BookEntity b
LEFT JOIN b.metadata m
LEFT JOIN m.authors a
WHERE (b.deleted IS NULL OR b.deleted = false) AND (
LOWER(m.title) LIKE LOWER(CONCAT('%', :text, '%'))
OR LOWER(m.subtitle) LIKE LOWER(CONCAT('%', :text, '%'))
OR LOWER(m.seriesName) LIKE LOWER(CONCAT('%', :text, '%'))
OR LOWER(a.name) LIKE LOWER(CONCAT('%', :text, '%'))
m.searchText LIKE CONCAT('%', :text, '%')
)
""")
Page<BookEntity> searchByMetadata(@Param("text") String text, Pageable pageable);
@@ -83,6 +83,7 @@ public class BookCreatorService {
.map(authorName -> authorRepository.findByName(authorName)
.orElseGet(() -> authorRepository.save(AuthorEntity.builder().name(authorName).build())))
.forEach(authorEntity -> bookEntity.getMetadata().getAuthors().add(authorEntity));
bookEntity.getMetadata().updateSearchText(); // Manually trigger search text update since collection modification doesn't trigger @PreUpdate
}
private String truncate(String input, int maxLength) {
@@ -76,7 +76,6 @@ public class BookMetadataUpdater {
boolean thumbnailRequiresUpdate = StringUtils.hasText(newMetadata.getThumbnailUrl());
boolean hasMetadataChanges = MetadataChangeDetector.isDifferent(newMetadata, metadata, clearFlags);
boolean hasValueChanges = MetadataChangeDetector.hasValueChanges(newMetadata, metadata, clearFlags);
if (!thumbnailRequiresUpdate && !hasMetadataChanges) {
log.info("No changes in metadata for book ID {}. Skipping update.", bookId);
return;
@@ -90,7 +89,6 @@ public class BookMetadataUpdater {
MetadataPersistenceSettings settings = appSettingService.getAppSettings().getMetadataPersistenceSettings();
boolean writeToFile = settings.isSaveToOriginalFile();
boolean convertCbrCb7ToCbz = settings.isConvertCbrCb7ToCbz();
BookFileType bookType = bookEntity.getBookType();
boolean hasValueChangesForFileWrite = MetadataChangeDetector.hasValueChangesForFileWrite(newMetadata, metadata, clearFlags);
@@ -226,11 +224,14 @@ public class BookMetadataUpdater {
if (replaceAll) {
if (!merge) e.getAuthors().clear();
e.getAuthors().addAll(newAuthors);
e.updateSearchText(); // Manually trigger search text update since collection modification doesn't trigger @PreUpdate
} else if (replaceMissing && e.getAuthors().isEmpty()) {
e.getAuthors().addAll(newAuthors);
e.updateSearchText(); // Manually trigger search text update since collection modification doesn't trigger @PreUpdate
} else if (replaceMode == null) {
if (!merge) e.getAuthors().clear();
e.getAuthors().addAll(newAuthors);
e.updateSearchText(); // Manually trigger search text update since collection modification doesn't trigger @PreUpdate
}
}
@@ -112,6 +112,7 @@ public class MetadataManagementService {
for (BookMetadataEntity metadata : booksWithOldAuthor) {
metadata.getAuthors().remove(oldAuthor);
metadata.getAuthors().addAll(targetAuthors);
metadata.updateSearchText(); // Manually trigger search text update since collection modification doesn't trigger @PreUpdate
}
bookMetadataRepository.saveAll(booksWithOldAuthor);
@@ -3,11 +3,13 @@ package com.adityachandel.booklore.service.migration;
import com.adityachandel.booklore.config.AppProperties;
import com.adityachandel.booklore.model.entity.AppMigrationEntity;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
import com.adityachandel.booklore.repository.AppMigrationRepository;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.service.book.BookQueryService;
import com.adityachandel.booklore.service.file.FileFingerprint;
import com.adityachandel.booklore.service.metadata.MetadataMatchService;
import com.adityachandel.booklore.util.BookUtils;
import com.adityachandel.booklore.util.FileService;
import com.adityachandel.booklore.util.FileUtils;
import jakarta.transaction.Transactional;
@@ -42,6 +44,49 @@ public class AppMigrationService {
private AppProperties appProperties;
private FileService fileService;
@Transactional
public void populateSearchTextOnce() {
if (migrationRepository.existsById("populateSearchText")) return;
int batchSize = 1000;
int processedCount = 0;
int offset = 0;
while (true) {
List<BookEntity> bookBatch = bookRepository.findBooksForMigrationBatch(offset, batchSize);
if (bookBatch.isEmpty()) break;
List<Long> bookIds = bookBatch.stream().map(BookEntity::getId).toList();
List<BookEntity> books = bookRepository.findBooksWithMetadataAndAuthors(bookIds);
for (BookEntity book : books) {
BookMetadataEntity m = book.getMetadata();
if (m != null) {
try {
m.setSearchText(BookUtils.buildSearchText(m));
} catch (Exception ex) {
log.warn("Failed to build search text for book {}: {}", book.getId(), ex.getMessage());
}
}
}
bookRepository.saveAll(books);
processedCount += books.size();
offset += batchSize;
log.info("Migration progress: {} books processed", processedCount);
if (bookBatch.size() < batchSize) break;
}
log.info("Migration 'populateSearchText' completed. Total books processed: {}", processedCount);
migrationRepository.save(new AppMigrationEntity(
"populateSearchText",
LocalDateTime.now(),
"Populate search_text column for all books"
));
}
@Transactional
public void populateMissingFileSizesOnce() {
if (migrationRepository.existsById("populateFileSizes")) {
@@ -17,6 +17,7 @@ public class AppMigrationStartup {
appMigrationService.populateMetadataScoresOnce();
appMigrationService.populateFileHashesOnce();
appMigrationService.populateCoversAndResizeThumbnails();
appMigrationService.populateSearchTextOnce();
appMigrationService.moveIconsToDataFolder();
}
}
@@ -11,6 +11,7 @@ import com.adityachandel.booklore.repository.BookOpdsRepository;
import com.adityachandel.booklore.repository.ShelfRepository;
import com.adityachandel.booklore.repository.UserRepository;
import com.adityachandel.booklore.service.library.LibraryService;
import com.adityachandel.booklore.util.BookUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
@@ -78,19 +79,19 @@ public class OpdsBookService {
if (libraryId != null) {
validateLibraryAccess(libraryId, userLibraryIds, isAdmin);
Page<Book> books = query != null && !query.isBlank()
? searchByMetadataInLibrariesPageInternal(query, Set.of(libraryId), page, size)
? searchByMetadataInLibrariesPageInternal(BookUtils.normalizeForSearch(query), Set.of(libraryId), page, size)
: getBooksByLibraryIdsPageInternal(Set.of(libraryId), page, size);
return applyBookFilters(books, userId);
}
if (isAdmin) {
return query != null && !query.isBlank()
? searchByMetadataPageInternal(query, page, size)
? searchByMetadataPageInternal(BookUtils.normalizeForSearch(query), page, size)
: getAllBooksPageInternal(page, size);
}
Page<Book> books = query != null && !query.isBlank()
? searchByMetadataInLibrariesPageInternal(query, userLibraryIds, page, size)
? searchByMetadataInLibrariesPageInternal(BookUtils.normalizeForSearch(query), userLibraryIds, page, size)
: getBooksByLibraryIdsPageInternal(userLibraryIds, page, size);
return applyBookFilters(books, userId);
}
@@ -1,5 +1,7 @@
package com.adityachandel.booklore.util;
import com.adityachandel.booklore.model.entity.AuthorEntity;
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
import lombok.experimental.UtilityClass;
import java.util.regex.Pattern;
@@ -8,9 +10,49 @@ import java.util.regex.Pattern;
public class BookUtils {
private static final Pattern WHITESPACE_PATTERN = Pattern.compile("\\s+");
private static final Pattern SPECIAL_CHARACTERS_PATTERN = Pattern.compile("[.,\\-\\[\\]{}()!@#$%^&*_=+|~`<>?/\";:]");
private static final Pattern SPECIAL_CHARACTERS_PATTERN = Pattern.compile("[!@$%^&*_=|~`<>?/\"]");
private static final Pattern PARENTHESES_WITH_OPTIONAL_SPACE_PATTERN = Pattern.compile("\\s?\\(.*?\\)");
public static String buildSearchText(BookMetadataEntity e) {
if (e == null) return null;
StringBuilder sb = new StringBuilder();
if (e.getTitle() != null) sb.append(e.getTitle()).append(" ");
if (e.getSubtitle() != null) sb.append(e.getSubtitle()).append(" ");
if (e.getSeriesName() != null) sb.append(e.getSeriesName()).append(" ");
try {
if (e.getAuthors() != null) {
for (AuthorEntity author : e.getAuthors()) {
if (author != null && author.getName() != null) {
sb.append(author.getName()).append(" ");
}
}
}
} catch (Exception ex) {
// LazyInitializationException or similar - authors won't be included in search text
}
return normalizeForSearch(sb.toString().trim());
}
public static String normalizeForSearch(String term) {
if (term == null) {
return null;
}
String s = java.text.Normalizer.normalize(term, java.text.Normalizer.Form.NFD);
s = s.replaceAll("\\p{InCombiningDiacriticalMarks}+", "");
s = s.replace("ø", "o").replace("Ø", "O")
.replace("ł", "l").replace("Ł", "L")
.replace("æ", "ae").replace("Æ", "AE")
.replace("œ", "oe").replace("Œ", "OE")
.replace("ß", "ss");
// Use cleanSearchTerm instead of cleanAndTruncateSearchTerm
s = cleanSearchTerm(s);
return s.toLowerCase();
}
public static String cleanFileName(String fileName) {
String name = fileName;
if (name == null) {
@@ -25,13 +67,18 @@ public class BookUtils {
return name;
}
public static String cleanAndTruncateSearchTerm(String term) {
public static String cleanSearchTerm(String term) {
if (term == null) {
return "";
}
String s = term;
s = SPECIAL_CHARACTERS_PATTERN.matcher(s).replaceAll("").trim();
s = WHITESPACE_PATTERN.matcher(s).replaceAll(" ");
return s;
}
public static String cleanAndTruncateSearchTerm(String term) {
String s = cleanSearchTerm(term);
if (s.length() > 60) {
String[] words = WHITESPACE_PATTERN.split(s);
if (words.length > 1) {
@@ -0,0 +1 @@
ALTER TABLE book_metadata ADD COLUMN IF NOT EXISTS search_text TEXT;